I have a page where user prints data and then click button submit.
<form id="myForm" action="/validate-configuration" _method="post" method="post" enctype="multipart/form-data"
onsubmit="return validateForm(this);">
<table>
...
<tr>
<td></td>
<input
type="submit"
value="Obfuscate"
onclick="return doConfirm('<%=messageSource.getMessage("message.DatabasePage", null, LocaleContextHolder.getLocale())%>',
function yes() {
$('#myForm').submit();
},
function no() {});"
/>
</td>
<td> </td>
</tr>
</table>
</form>
<div id="confirmBox" class="modal">
<div class="modal-content">
<div class="message"></div>
<button type="button" class="yes">Yes</button>
<button type="button" class="no">No</button>
</div>
</div>
When a user clicks on submit first appear to confirm window. But I want to rich next behaviour. When something is not inputted first works validation function and after all input fields were completed appear to confirm button after click on submit button.
function validateForm(form) {
return validateConfigurationSelect(form) && validateDBCredentials(form) && validateSalt(form);
}
function doConfirm(msg, yesFn, noFn) {
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Answer:
make function doConfirm like this:
function doConfirm(msg, yesFn, noFn, validationFunc) {
if (validationFunc) {
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
}
and in hmtl markup replace type of button form "submit" to "button" and add function:
input type="button" value="Obfuscate" onclick="
doConfirm('<%=messageSource.getMessage("message.dialog.DatabasePage", null, LocaleContextHolder.getLocale())%>',
function yes() {
$('#myForm').submit();
},
function no() {
},
validateForm()
);"/>
Also note that validateForm() should return boolean value.
Well, first of all, you should not validate on the client (with Javascript) but on the server (with Java). Validating in javascript is bad because it is easy to by pass it.
BUT, to answer your question. Change your code into:
<input type="button"
value="Obfuscate"
onclick="if (validateForm()) { return doConfirm('<%=messageSource.getMessage("message.DatabasePage", null, LocaleContextHolder.getLocale())%>',
function yes() {
$('#myForm').submit();
},
function no() {}); } else { showErrors() } "
/>
You don't need to pass the "form" argument in validateForm() because you can retrieve the values with document.getElementBy("") etc.
So to summarize:
user presses Save button (which is not submit type but just button type button)
validateForm() is called
if true then call doConfirm(), if OK button then $('#myForm').submit();
if false then display some errors
Related
This code should perform the following when clicked:
submit the form
disable the button to prevent double clicks
add a spinner to the button to notify the user something is happening
if the form is invalid, stop the form submission, remove the spinner, and enable the button.
While writing this code, I found that it will perform validation and form submission only when the button type is set to submit. If the button type is button, the form.submit in the button click event does not submit the form. Processing of the form halts, no validation occurs, no form submission. I set up break points inside the jquery #myForm.submit, and they are never hit. Does anyone have an explanation for this behavior?
frameworks: jquery 3.4.1, bootstrap 4
<form action="doSomething" id="myForm">
...
<!-- this performs validation and submits the form -->
<button type="submit" id="aButton" class="btn btn-primary" data-validate="true">
Save
</button>
<!-- this does not perform validation nor submits the form -->
<button type="button" id="bButton" class="btn btn-primary" data-validate="true">
Save
</button>
</form>
Javascript
removeSpinnerFromButton = function (btn) {
var span = btn.find('span[id="spinner"]');
span.remove();
btn.removeAttr('disabled');
btn.removeClass('cursor-wait');
};
addSpinnerToButton = function (btn) {
btn.attr('disabled', 'disabled');
btn.addClass('cursor-wait');
$("<span/>", {
class: 'spinner-border spinner-border-sm',
id: 'spinner',
role: 'status',
aria_hidden: 'true'
}).appendTo(btn);
};
$('button[data-validate="true"]').click(function () {
var $self = $(this);
$('#myForm').submit(function (event) {
addSpinnerToButton($self);
if ($(this).valid()) {
return true;
} else {
event.preventDefault();
removeSpinnerFromButton($self);
return false;
}
});
});
Edit
this bit of code aides in understanding what is happening.
$(function(){
$('#myInputSubmit').click(function(){alert('input of type submit clicked');});
$('#myInputButton').click(function(){alert('input of type button clicked');});
$('#myButtonSubmit').click(function(){alert('button of type submit clicked');});
$('#myButtonButton').click(function(){alert('button of type button clicked');});
$('form').submit(function(e){alert('form submitted');e.preventDefault();});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="button" id="myInputButton" value="input button" />
<input type="submit" id="myInputSubmit" value="input submit" />
<button type="button" id="myButtonButton">button button</button>
<button type="submit" id="myButtonSubmit">button submit</button>
</form>
input or button type="submit" has a default behaviour: Submit the form
button type="button" (or no type at all) doesn't have a default behaviour and you should add it with a listener, as you're already doing for click event. Inside that function you should validate and, if it's the case, submit the form with $('#myForm').submit();, with no params
With this piece of code, you're adding a submit listener to the form instead of submit it:
$('#myForm').submit(function (event) {
addSpinnerToButton($self);
if ($(this).valid()) {
return true;
} else {
event.preventDefault();
removeSpinnerFromButton($self);
return false;
}
});
When button is clicked, do your validations and then submit the form. Right now, you need a plugin to validate with $(this).valid(), otherwise, an error will be thrown.
$('button[data-validate="true"]').click(function () {
var $self = $(this);
addSpinnerToButton($self);
if ($(this).valid()) {
$('#myForm').submit();
} else {
removeSpinnerFromButton($self);
}
});
In my code, onclick function of addDvcPeople() works fine without form.
But once form added, the onclick function of addDvcPeople() works fail.
Here is the code without form which works fine:
<div class="dvcOnShlv" id="dvcOnShlv">
<!--<form action="modify_idc_addDVC.php?act=add&table=IDC" method="POST">-->
<table border="1px" cellspacing="0" id="staTable">
<tr>
<h2 align="center">IDCtable</h2>
</tr>
<tr>
<td style="width:15%" id="addDvcWorker">engineer<br /><input type="button" id="addDvcPeople" onclick="addDvcPeople()" value="addpeople"></td>
</tr>
</table>
<!--</form>-->
</div>
My addDvcPeople() code is:
<script>
function addDvcPeople()
{
alert("test");
}
</script>
Once "form" sentence is added, function addDvcPeople() did nothing.
I don't know why.Who can help me ?
The main problem that you have is that you have given your button the same ID as your function name. You need to ensure that these are different, or your function will always come through as undefined:
function addDvcPeople() {
alert("test");
}
<form>
<input type="button" id="addDvcPeople" onclick="addDvcPeople()" value="Button">
</form>
Here this is shown working with a different ID:
function addDvcPeople() {
alert("test");
}
<form>
<input type="button" id="addDvcPeopleID" onclick="addDvcPeople()" value="Button">
</form>
A secondary problem you'll encounter is that form submission has a default behaviour of actually submitting a form, even without a submit input, meaning that your form will disappear after the button is clicked:
function addDvcPeople() {
alert("test");
}
<form>
<button onclick="addDvcPeople()">Button</button>
</form>
To resolve this, you need to override the default form submission by passing through the event:
function addDvcPeople(event) {
event.preventDefault();
alert("test");
}
<form>
<button onclick="addDvcPeople(event)">Button</button>
</form>
Note that in the above example, the page does not refresh, and the alert appears.
Hope this helps! :)
You just do not set the duplicate id and function name
I have a button, when click, it do a jquery function and submit form too.
This is my HTML code:
<?php echo Form::open(array("class"=>"form-horizontal","method"=>"POST" ,"id"=>"frmMainOrders","enctype" => "multipart/form-data" )); ?>
<div class="search">
<tr class="tblAdvancedSearch">
<th scope="row">備考</th>
<td>
<input class="input_text_search" type="text" name="multi_column" id="multi_column_search" value=""/>
</td>
</tr>
<input type="submit" id="btn_submit" value="検 索" name="adv_search">
</div>
<?php echo Form::close();?>
This is my script jquery:
$('.search').on('click', function() {
showAdvancedForm(); // when click in div class=search, it do a jquery function name showAdvanceForm().
});
function showAdvancedForm() {
if($(".tblAdvancedSearch").css('display') == 'none') {
$(".tblAdvancedSearch").css('display', 'table-row');
} else {
$(".tblAdvancedSearch").css('display', 'none');
}
}
I have tried:
<input type="submit" id="btn_submit" value="検 索" name="adv_search" onclick="$('form').submit()">
This way allow me submit form, but my controller can not get attribute name="adv_search", so my function doesn't work.
I have tried preventDefault() and $('#btn_submit').click(false).
But both of them prevent all submit and jquery function.
Is there a way to submit the form but prevent ONLY jquery function when I click submit button?
You can use e.target.name to find out the name of the element. So based on that you can conditionally fire the method showAdvancedForm() .
e.target - Get the element that triggered a specific event
$('.search').on('click', function(e) {
if (e.target.name == "multi_column") {
console.log('calling method : showAdvancedForm');
showAdvancedForm(); // when click in div class=search, it do a jquery function name showAdvanceForm().
}
});
function showAdvancedForm() {
if ($(".tblAdvancedSearch").css('display') == 'none') {
$(".tblAdvancedSearch").css('display', 'table-row');
} else {
$(".tblAdvancedSearch").css('display', 'none');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="page.html" class="form-horizontal">
<div class="search">
<tr class="tblAdvancedSearch">
<th scope="row">備考</th>
<td>
<input class="input_text_search" type="text" name="multi_column" id="multi_column_search" value="" />
</td>
</tr>
<input type="submit" id="btn_submit" value="検 索" name="adv_search">
</div>
</form>
If you have a form and you want to send data via Ajax you should do something like this:
$('#formID').submit(function(e) {
e.preventDefault();
var submitButtonValue=$(this).children('input[type=submit]').val(); //This is 検 索
var data=$(this).serialize()+ "&adv_search="+submitButtonValue;
//probably your ajax call here...
})
Serialize is a function that you can get all your inputs' values in your form by it, and you also can easily send it via Ajax
You should use submit, because it also will check validations and more
I have 2 submit buttons in an HTML form.
How can I know which submit button has triggered the JavaScript function?
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
// I can't use onclick handler
// I can't use JQuery.. I want to do only with javascript
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1">
<input type="submit" value="submit2">
</form>
<button value="delete row" id="but1" onclick="disps()">delete row</button>
I want to do different actions based on the different submit buttons clicked.
It is not possible to check the button clicked through the onsubmit event. Instead move the call to verifyData() to the onclick handler of each button. Use return in the onclick call to cancel submission if false is returned by verifyData()
<script language="javascript" type="text/javascript">
function verifyData(button) {
// validate
switch (button.value) {
case "submit1":
// do somehting
break;
case "submit2":
// do somehting
break;
// ...
};
// submit the form
return true;
}
</script>
<form method="post">
<input type="submit" value="submit1" onclick="return verifyData(this);">
<input type="submit" value="submit2" onclick="return verifyData(this);">
</form>
How about putting an onclick event handler on both buttons which will set a variable to say which button was clicked?
like so:
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
alert(btnClicked);
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
}
var btnClicked = 0;
function setSubmit(which) {
btnClicked = which; return true;
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1" onclick="return setSubmit(1);">
<input type="submit" value="submit2" onclick="return setSubmit(2);">
</form>
Are you allowed to use the jQuery library?
If you can using this you can easily bind to each submit button based on an id.
For example:
<form id="form1" method="post">
<input type="submit" value="submit1" id="submit1">
<input type="submit" value="submit2" id="submit2" >
</form>
<script type="text/javascript">
$("#submit1").click(function(e)
{
// Do stuff when 1 is clicked.
$("#form1").submit();
});
$("#submit2").click(function(e)
{
// Do stuff when 2 is clicked.
$("#form1").submit();
});
</script>
you could also have the buttons as a type of button to avoid any issues, but you should be able to simply return false; to stop the button of type submit from... submitting
Here is how I would do it... Firstly I would use jQuery so you must include that in your document like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
It would also mean your HTML can be simplified to:
<form method="post">
<input type="submit" value="submit1"/>
<input type="submit" value="submit2"/>
</form>
Then you can use jQuery:
<script>
// When the document is ready
$(function(){
// Action performed when a submit button in the form is clicked
$("form[type='submit']").click(function(e){
// Get the value attribute
var val = $(this).val(),
validation_has_passed = false;
// If it is submit1
if(val == "submit1") {
// Validate submit 1
validation_has_passed = true;
// If it is submit2
} else if(val == "submit2") {
// Validate submit 2
validation_has_passed = true;
}
// If all validation is OK submit the form
if(validation_has_passed === true) {
$("form").submit();
}
// Ensure pressing these buttons doesn't submit the form
e.preventDefault();
});
});
</script>
I've got this simple login screen where is has a text box for the name, and a submit button. The jquery script running is this:
$(document).ready(function() {
$('#btnLogin').click( function() { validate() });
$('#loginForm').submit( function() { validate() });
});
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID=' + $('#txtLogin').val();
$('#lblError').hide();
document.location.href = 'mainmenu.aspx';
}
else {
$('#txtLogin').text('');
$('#lblError').show();
}
}
It works when I click the button, but when I press enter, it doesn't navigate to the mainmenu.aspx. I'm following it with Chrome and it does execute the redirect just like when you press the button, but it just stays on the same page. I also put a break point in the Page_Load function (C#) of the mainmenu.aspx, but it never reaches it.
EDIT:: Here's the html
<form id="loginForm" runat="server">
<div>
<div class='theme login'>
<p>Login</p>
<input type='text' id='txtLogin' maxlength='17' />
<div><input type='button' id='btnLogin' class='button' value='Log In' /></div>
<div><span id='lblError' visible='false' text='*You must enter a valid username'></span></div>
</div>
</div>
</form>
In your form submit handler, use preventDefault() to stop the default submit behavior:
$('#loginForm').submit( function(e) {
e.preventDefault(); // swallow regular submit behavior
validate(); // your stuff
// real submit? your option
});
Reference: http://api.jquery.com/event.preventDefault/
Try making the submit element in the form just a regular button element. The browser may be intercepting something.
The reason for that is your submit still happens when you hit enter. You need to cancel the default behavior by returning false in the event handler function.
function validate() {
// ...
return false;
}
$('#loginForm').submit(validate);
$('#btnLogin').click(validate);
Edit: refer to the function directly instead of an anonymous function?
function validate() {
if ($('#txtLogin').val() != '') {
document.cookie = 'loginID='+$('#txtLogin').val();//set expire and path?
$('#lblError').hide();
location.href = "mainmenu.aspx"; //"submit"
}
else {
$('#lblError').show();
return false; //prevent submit
}
}
$(function() {
$('#btnLogin').click(validate);
$('#loginForm').submit(validate);
});
I changed both some of your HTML and jQuery code. Now it will check and submit on both Enter and when the button is clicked.
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("form").attr("action","javascript:void();"); // No action on form submission
$("input").keypress(function(e) { // Capture keys pressed
if(e.keyCode==13) { // Enter key?
validate();
}
});
$("input:button").click(function() { // Button clicked?
validate();
});
});
function validate() {
if ($("#txtLogin").val()!='') {
document.cookie="loginID="+$("#txtLogin").val();
$("#lblError").hide();
$("form").attr("action","mainmenu.aspx"); // Change form action
$("form").submit(); // Submit the form
} else {
$("#lblError").show();
}
}
</script>
HTML
<form id="loginForm" runat="server">
<div>
<div class="theme login">
<p>Login</p>
<input type="text" id="txtLogin" maxlength="17" />
<div><input type="button" id="btnLogin" class="button" value="Log In" /></div>
<div id="lblError" style="display: none;">* You must enter a valid username</div> <!-- Error message -->
</div>
</div>
</form>