How do you handle a form change in jQuery? - javascript

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...
}
});

Related

insert value based on input field changes

I have following JavaScript codes in my view:
$('.f_opf_description_c').val(data['opf_description_c']);
$("#Form_2").on("input", function() {
$('.f_opf_description_c').val(this.value);
});
I need to insert value of data['opf_description_c'] to the field with id Form_2(class is f_opf_description_c ) when this field is not changed. If this field is changed, I need to insert val(this.value). How can I do it?
add some variable and change event
var isChange = false;
$(".f_opf_description_c").on("change", function() {
isChange = true;
});
$("#Form_2").on("submit", function() {
if (isChange)
$('.f_opf_description_c').val(data['opf_description_c']);
});
if I understood you correctly this fiddle can help
$(document).ready(function(){
var data ={'opf_description_c':'some value'};
$(".f_opf_description_c").val(data['opf_description_c']);
$("#Form_2").on("keydown", function() {
if($(this).val() == data['opf_description_c']){
$(this).val('')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<input type="text" class="f_opf_description_c" id="Form_2">
</div>

Validate form input text while user write

I would like to validate my form during the writing by user.
Now I'm using this javascript:
$(document).ready(function (){
validate();
$('#initialKm, #carChassis').change(validate);
});
function validate(){
if ($('#initialKm').val().length > 0 &&
$('#carChassis').val().length > 0 ){
$("#saveCarButton").prop("disabled", false);
}
else {
$("#saveCarButton").prop("disabled", true);
}
}
The only problem is that to execute the validation, after the user has filled the input tag, he has to click elsewhere to activate the button. Is it possible to activate while user fill the field?Thanks
Use $('#initialKm, #carChassis').keyup(validate)
Change only fires after the input focus is lost.
Try using input event
$(document).ready(function () {
validate();
$("#initialKm, #carChassis").on("input", validate);
});
function validate() {
$("#saveCarButton")
.prop("disabled",
!$('#initialKm').val().length
&& !$('#carChassis').val().length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" id="initialKm" />
<input type="text" id="carChassis" /><br>
<button id="saveCarButton">click</button>
$(document).ready(function () {
$("#initialKm, #carChassis").keyup(validate);
});
function validate() {
$("#saveCarButton")
.prop("disabled",
!$('#initialKm').val().length
&& !$('#carChassis').val().length);
}

Disable form button unless all text input fields are filled in

I have a form that has multiple text inputs, I don't want to add id to each one as they are generated from server side code - number of fields may differ etc. I just want to be able to disable the submit button until there is text entered into each text input.
I have gotten this far, but only disables button until text entered in to one text input field - I want it to stay disabled until text entered in to all text inputs.
<script>
$(function () {
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
$('#button').prop('disabled', this.value == "" ? true : false);
})
});
</script>
I have also tried $('input:text').each().keyup(function (){ - but does not make button clickable?
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
var disable = false;
$('input:text').each(function(){
if($(this).val()==""){
disable = true;
}
});
$('#button').prop('disabled', disable);
});
Demo
The callback function for keyup now checks only that specific input field's value (this.value). Instead, this needs to loop through all input fields that need to be filled, and only when all have text do you change the the .prop value.
$('input:text').keyup(function () {
$('#button').prop('disabled', allFieldsAreFilled());
});
function allFieldsAreFilled() {
var allFilled = true;
// check all input text fields
$("#yourForm input:text"]).each(function () {
// if one of them is emptyish allFilled is no longer true
if ($(this).val() == "") {
allFilled = false;
}
});
return allFilled;
}
Try this:
$(function() {
var bool = true, flag = false;
$('#button').prop('disabled', bool); // use prop to disable the button
$(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs
$('input:text').each(function() { // loop through each text inputs
bool = $.trim(this.value) === "" ? true : false; // update the var bool with boolean values
if(bool)
return flag;
});
$('#button').prop('disabled', bool); // and apply the boolean here to enable
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='button' id='button' value='button' />

auto-submit form only if specific number of checkboxes had been checked

I am new to jQuery. I am wondering if there is a way to count the number of checkboxes that have been checked and then auto-submit the form once a specific number of checkboxes had been checked. Let's say the user checks 2 checkboxes, nothing happens. The user checks the 3rd checkbox and the form submits.
<input type="checkbox" onclick="this.form.submit();">
You could try this, using no inline javascript...
HTML
<form>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</form>
jQuery
$('input[type="checkbox"]').on('click', function (event) {
var flag = $('input:checked').length > 2 ? true : false;
if (flag) $('form').submit();
});
Fiddle
$('input[type="checkbox"]').on('change', function() {
if( $("input[type="checkbox"]:checked").length >=3) {
$('form').submit();
}
});
JQuery function:
function SubmitIfReady() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
}
HTML (form not shown):
<input type="checkbox" class="checkbox-class" onclick="SubmitIfReady();">
Or without the onclick:
JQuery function:
$(document).ready(function () {
$('.checkbox-class:checked').on('change', function() {
if ($('.checkbox-class:checked').length == 5) { // specify the number you want
$('#YourForm').submit();
}
});
});
HTML (form not shown):
<input type="checkbox" class="checkbox-class">
Like this...
$(".counted-check").click(function(e){
var myForm = $(this).closest('form');
if(myForm.find(".counted-check").filter(":checked").length > 3){
myForm.submit();
}
});
http://jsfiddle.net/HQ5N9/

jQuery events not firing

I have been trying to get this to work. Basically I have a search box that has a default string in it (i.e. Search) and it should go away when the user clicks on the input field.
Here is the code:
HTML:
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' value="Search <?php print $row[0]?> tweets!" autocomplete="off" />
</form>
Javascript/jQuery: (defaultString is a global variable that has the value of the textbox)
function clearDefault() {
var element = $('#searchBox');
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
element.css('color','black');
}
$('#searchBox').focus(function() {
clearDefault();
});
Problem is here:
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
Change it with:
if(element.val() == defaultString) {
element.val('value');
}
Update: Check it here:
http://jsfiddle.net/mr3T3/2/
The problem was that the event binding was not inside the $(document).ready() handler.
Fixed:
function clearDefault() {
var element = $('#searchBox');
if(element.val() == defaultString) {
element.val("");
}
element.css('color','black');
}
$(document).ready(function() {
$('#searchBox').focus(function() {
clearDefault();
});
});
It could be that event in fact is firing and your problem is in
if(element.attr('value') == defaultString) {
element.attr('value',"");
}
is "defaultString" properly defined?
put a simple alert() inside clearDefaults() and see if the event works.
i don't think clearDefault is reusable function, so don't create unnecessary function for small block of code. See the following code sample, i added a small improvement in your functionality.
<form method="get" action="index.php" id="search">
<span id="searchLogo"></span>
<input type='text' name='q' id='searchBox' default="Search tweets!" value="Search tweets!" autocomplete="off" />
</form>
$(document).ready(function() {
$("#searchBox").focus(function(e){
var $this = $(this);
if($this.val() == $this.attr('default')) $this.val('');
else if($this.val().length == 0 ) $this.val($this.attr('default'));
});
$("#searchBox").blur(function(e){
var $this = $(this);
if($this.val().length == 0 ) $this.val($this.attr('default'));
});
});
I added a default attribute to store default value and used it later on blur event.
See the example in jsFiddler

Categories

Resources