$("#qwerq").submit(function (e){
e.preventDefault();
var check=0;
if($("#firstName").val() == "") {
check=1;
}
if(check!=1){
$("#qwerq").unbind("submit") ;
$("#qwerq").submit();
//$("#qwerq").trigger('submit', [true]);
}
});
When the form is having id="qwerq" is as per needs and the submit gets unbinded, the form does not submit on its own.
I have tried using .submit() and .trigger("submit"). I have to manually click on submit again.
What should I add so that I don't have to click again?
Instead of unbinding the events, why won't you just prevent submitting only on error?
if(check === 1) return false;
return false in jQuery's event handler means preventDefault and stopPropagation.
I think you were trying to submit a form on a button click.
Then you need to make some changes in your code:
Provide an id to your form and change button type="button" (instead of "submit"):
<form id="form_1" action="yourserverpagename.php" method="post">
<input id="firstName" type="text" value="" />
<input id="qwerq" type="button" value="Send" />
</form>
Now your script should like below:
<script>
$("#qwerq").click(function (e) {
e.preventDefault();
var check = 0;
if ($("#firstName").val() == "") {
check = 1;
}
if (check != 1) {
//-- here is the way to submit the form using form id --
$('#form_1').submit();
}
});
</script>
When I try to validate the jsp form on keypress event, the alert box appears before entering any data into an input field
<html>
<head>
<script text/javascript>
var inputs = document.getElementsByTagName("input");
function checkTabPress(e)
{
for(var i=0;i<inputs.length;i++)
{
if((inputs[i].value === undefined || inputs[i].value.length == 0) && (e.keyCode == 9))
{
alert("plz write");
return false;
}
}
return true;
}
document.addEventListener('keyup', function (e) {
checkTabPress(e);
}, false);
</script>
</head>
<body>
Enter Your Name: <input onkeypress="checkTabPress('abc')" type='text' id="abc" placeholder=''><br>
Enter <input onkeypress="checkTabPress('xyz')" type='text' id="xyz" placeholder=''>
</body>
</html>
You need to change your onkeypress event to onblur (of the text inputs) and there is no need of addEventListener for keypress
Updated DEMO JSFiddle URL : https://jsfiddle.net/n6j7oy3b/3/
Hope this helps!
HTML:
<form method="post" name="contact" id="frmContact" action="smail.php">
...
<label for="security" class="smallPercPadTop">Please enter the result:</label> <br /><h3 id="fNum" class="spnSecurity"></h3><h3 id="nCalcType" class="spnSecurity"></h3><h3 id="sNum" class="spnSecurity"></h3> = <input type="text" placeholder="Enter the result" name="security" id="security" class="required input_field_custom" />
<br /><br />
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
<input type="reset" value="Reset" id="reset" name="reset" class="submit_btn" />
</form>
Script:
$('form').on('submit', function(e) {
e.preventDefault();
var vGetResult = $("#security").val();
if (vGetResult == vResult) { //""vResult"" is a value that I set when the page loads...
alert("good");
$("#frmContact").submit();
}
});
What I am trying to do is, once I validate what the user entered is the same as another number then I would like to submit the form. Instead of submitting the form, I keep getting the alert statement infinitely.
How can I fix it?
Move e.preventDefault() to else block when the validation condition fails. Also you don't need to resubmit the form using $("#frmContact").submit()
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult == vResult) { //""vResult"" is a value that I set when the page loads...
alert("good");
//$("#frmContact").submit();
}else{
e.preventDefault();
}
});
Or, you just modify statement as
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult !== vResult) { //""vResult"" is a value that I set when the page loads...
e.preventDefault();
}
alert("good");
});
Your form goes in infinite loop. try this simple code.
$('form').on('submit', function(e) {
var vGetResult = $("#security").val();
if (vGetResult != vResult)
{
e.preventDefault();
}
});
Return true to allow the form to submit or false to suppress :
$('#frmContact').on('submit', function(e) {
if ($("#security").val() == vResult) {
alert("good");
return true;
} else {
return false;
}
});
Or, if the alert is not needed :
$('#frmContact').on('submit', function(e) {
return $("#security").val() == vResult;
});
You can let the jQuery event get prevented ...and trigger the native event
Just change
$("#frmContact").submit();
To
$("#frmContact")[0].submit();
I am very new to JQuery: I am a little perplexed to ask but asking is better than the alternative:
I am trying to disable a button but enable it when something is in the field/textbox.
This is simply experimental, just getting my feet wet here.
Alternatively I could disable the button on windows load or apply the attribute directly on the form element.
$(document).ready(function() {
$('#btnSubmit').attr('disabled', true);
$('#myForm :input').blur(function(){
if($('#myField').val() == '')
{
$('#btnSubmit').attr('disabled', true);
}
else
{
$('#btnSubmit').attr('disabled', false);
}
});
});
The problem is after I enter a value and leave the field the button is enabled but as soon as I click the button it is disabled again:
What am I missing?
Thanks my friends.
It is because the button is also considered an input field.
Try
$('#myForm :input:not(:button)').
Demo: Fiddle
Also use .prop() instead of .attr() to set disabled state
try using this:
$('#btnSubmit').attr('disabled', 'disabled'); // to disable buttons
$('#btnSubmit').removeAttr('disabled'); // to enable them
Try this one, this should work
HTML sample
<input type = "text" id = "txt1">
<button class = "btnSubmit">Submit</button>
And the jquery
$(".btnSubmit").attr("disabled", "disabled");
$("#txt1").keyup(function() {
if(jQuery.trim($(this).val()) != '') {
$('.btnSubmit').removeAttr('disabled');
}
});
$('#myForm:input').on('keyup' , function() {
if($.trim($('#myField').val()).length > 0){
$('#btnSubmit').prop('disabled', false);
}
else {
$('#btnSubmit').prop('disabled', true);
}
});
*This would work. Please try*
You can try this,onkeyup check if the textbox is empty is so disbale the button , else enable the button.
HTML:
<form id="myForm">
<input id="myField" type="text"/>
<input id="btnSubmit" value="hi" type="button"/>
</form>
jQuery:
$(document).ready(function() {
//Load with button disabled,since the value of the textbox will be empty initially
$('#btnSubmit').attr('disabled', true);
//onkeyup check if the textbox is empty or not
$('#myForm input[type="text"]').keyup(function(){
if($('#myField').val() == '')
{
$('#btnSubmit').prop('disabled', true);
}
else
{
$('#btnSubmit').prop('disabled', false);
}
});
});
$(document).ready(function() {
$('#btnSubmit').prop('disabled', true);
$('#myForm input[type="text"]').keyup(function(){
if($('#myField').val() == '')
{
$('#btnSubmit').prop('disabled', true);
}
else
{
$('#btnSubmit').prop('disabled', false);
}
}); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input id="myField" type="text"/>
<input id="btnSubmit" value="hi" type="button"/>
</form>
In jQuery, is there a simple way to test if any of a form's elements have changed?
Say I have a form and I have a button with the following click() event:
$('#mybutton').click(function() {
// Here is where is need to test
if(/* FORM has changed */) {
// Do something
}
});
How would I test if the form has changed since it was loaded?
You can do this:
$("form :input").change(function() {
$(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:
$('.checkChangedbutton').click(function() {
if($(this).closest('form').data('changed')) {
//do something
}
});
References: Updated
According to jQuery this is a filter to select all form controls.
http://api.jquery.com/input-selector/
The :input selector basically selects all form controls.
If you want to check if the form data, as it is going to be sent to the server, have changed, you can serialize the form data on page load and compare it to the current form data:
$(function() {
var form_original_data = $("#myform").serialize();
$("#mybutton").click(function() {
if ($("#myform").serialize() != form_original_data) {
// Something changed
}
});
});
A real time and simple solution:
$('form').on('keyup change paste', 'input, select, textarea', function(){
console.log('Form changed!');
});
You can use multiple selectors to attach a callback to the change event for any form element.
$("input, select").change(function(){
// Something changed
});
EDIT
Since you mentioned you only need this for a click, you can simply modify my original code to this:
$("input, select").click(function(){
// A form element was clicked
});
EDIT #2
Ok, you can set a global that is set once something has been changed like this:
var FORM_HAS_CHANGED = false;
$('#mybutton').click(function() {
if (FORM_HAS_CHANGED) {
// The form has changed
}
});
$("input, select").change(function(){
FORM_HAS_CHANGED = true;
});
Looking at the updated question try something like
$('input, textarea, select').each(function(){
$(this).data("val", $(this).val());
});
$('#button').click(function() {
$('input, textarea, select').each(function(){
if($(this).data("val")!==$(this).val()) alert("Things Changed");
});
});
For the original question use something like
$('input').change(function() {
alert("Things have changed!");
});
$('form :input').change(function() {
// Something has changed
});
Here is an elegant solution.
There is hidden property for each input element on the form that you can use to determine whether or not the value was changed.
Each type of input has it's own property name. For example
for text/textarea it's defaultValue
for select it's defaultSelect
for checkbox/radio it's defaultChecked
Here is the example.
function bindFormChange($form) {
function touchButtons() {
var
changed_objects = [],
$observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
var
$input = $(this),
changed = false;
if ($input.is('input:text') || $input.is('textarea') ) {
changed = (($input).prop('defaultValue') != $input.val());
}
if (!changed && $input.is('select') ) {
changed = !$('option:selected', $input).prop('defaultSelected');
}
if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
changed = (($input).prop('defaultChecked') != $input.is(':checked'));
}
if (changed) {
return $input.attr('id');
}
}).toArray();
if (changed_objects.length) {
$observable_buttons.removeAttr('disabled')
} else {
$observable_buttons.attr('disabled', 'disabled');
}
};
touchButtons();
$('input, textarea, select', $form).each(function () {
var $input = $(this);
$input.on('keyup change', function () {
touchButtons();
});
});
};
Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.
$('form').each(function () {
bindFormChange($(this));
});
Implementation as a jQuery plugin is here https://github.com/kulbida/jmodifiable
var formStr = JSON.stringify($("#form").serializeArray());
...
function Submit(){
var newformStr = JSON.stringify($("#form").serializeArray());
if (formStr != newformStr){
...
formChangedfunct();
...
}
else {
...
formUnchangedfunct();
...
}
}
You need jQuery Form Observe plugin. That's what you are looking for.
Extending Udi's answer, this only checks on form submission, not on every input change.
$(document).ready( function () {
var form_data = $('#myform').serialize();
$('#myform').submit(function () {
if ( form_data == $(this).serialize() ) {
alert('no change');
} else {
alert('change');
}
});
});
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
$("#result").html($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form "your_form_name"</h2>
<form name="your_form_name">
<input type="text" name="one_a" id="one_a" value="AAAAAAAA" />
<input type="text" name="one_b" id="one_b" value="BBBBBBBB" />
<input type="text" name="one_c" id="one_c" value="CCCCCCCC" />
<select name="one_d">
<option value="111111">111111</option>
<option value="222222">222222</option>
<option value="333333">333333</option>
</select>
</form>
<hr/>
<h2>Form "your_other_form_name"</h2>
<form name="your_other_form_name">
<input type="text" name="two_a" id="two_a" value="DDDDDDDD" />
<input type="text" name="two_b" id="two_b" value="EEEEEEEE" />
<input type="text" name="two_c" id="two_c" value="FFFFFFFF" />
<input type="text" name="two_d" id="two_d" value="GGGGGGGG" />
<input type="text" name="two_e" id="two_f" value="HHHHHHHH" />
<input type="text" name="two_f" id="two_e" value="IIIIIIII" />
<select name="two_g">
<option value="444444">444444</option>
<option value="555555">555555</option>
<option value="666666">666666</option>
</select>
</form>
<h2>Result</h2>
<div id="result">
<h2>Click on a field..</h2>
</div>
In addition to above #JoeD's answer.
If you want to target fields in a particular form (assuming there are more than one forms) than just fields, you can use the following code:
$('form[name="your_form_name"] input, form[name="your_form_name"] select').click(function() {
// A form element was clicked
});
Try this:
<script>
var form_original_data = $("form").serialize();
var form_submit=false;
$('[type="submit"]').click(function() {
form_submit=true;
});
window.onbeforeunload = function() {
//console.log($("form").submit());
if ($("form").serialize() != form_original_data && form_submit==false) {
return "Do you really want to leave without saving?";
}
};
</script>
First, I'd add a hidden input to your form to track the state of the form. Then, I'd use this jQuery snippet to set the value of the hidden input when something on the form changes:
$("form")
.find("input")
.change(function(){
if ($("#hdnFormChanged").val() == "no")
{
$("#hdnFormChanged").val("yes");
}
});
When your button is clicked, you can check the state of your hidden input:
$("#Button").click(function(){
if($("#hdnFormChanged").val() == "yes")
{
// handler code here...
}
});