admin管理员组

文章数量:1326506

If I have a Text Input field in a form with id say "input_id". During loading the page I would populate the field with existing data

While submitting the form using a button of id "form_submit", I want to determine if the field has been altered in any way. So that I would take particular action pertaining to the change.

In Jquery:

$("#input_id").on("keyup",function(){
    //set a flag to indicate the field is altered
})

$("#form_submit").on("click",function(){
    //check flag to see if #input_id is changed
}

So how do I set a flag in one event, and read it in another without using a global variable ?

Thanks in advance

If I have a Text Input field in a form with id say "input_id". During loading the page I would populate the field with existing data

While submitting the form using a button of id "form_submit", I want to determine if the field has been altered in any way. So that I would take particular action pertaining to the change.

In Jquery:

$("#input_id").on("keyup",function(){
    //set a flag to indicate the field is altered
})

$("#form_submit").on("click",function(){
    //check flag to see if #input_id is changed
}

So how do I set a flag in one event, and read it in another without using a global variable ?

Thanks in advance

Share Improve this question edited Mar 31, 2016 at 17:50 Barath Ravikumar asked Mar 31, 2016 at 17:10 Barath RavikumarBarath Ravikumar 5,8363 gold badges25 silver badges39 bronze badges 3
  • 2 so what is the question? – Kartikeya Khosla Commented Mar 31, 2016 at 17:11
  • I want to set a flag in one event, and read it at another event. How do I do that – Barath Ravikumar Commented Mar 31, 2016 at 17:12
  • You don't need to pass anything around, if you just go for the simple option of paring the current value with the defaultValue property. (Be aware, that is a property of the HTML element object, not of the jQuery object - so you'll have to de-reference it before accessing that property, $("#input_id")[0].defaultValue.) – C3roe Commented Mar 31, 2016 at 17:54
Add a ment  | 

3 Answers 3

Reset to default 5

One option would be to use the form data attribute:

$("#input_id").on("keyup",function(){
    //set a flag to indicate the field is altered
    $(this).closest('form').data('changed',true);
})

$("#form_submit").on("click",function(){
    //check flag to see if #input_id is changed
    console.log($(this).closest('form').data('changed'));
}

You can use .data() for this purpose,

var submit = $("#form_submit");

$("#input_id").on("keyup",function(){
 submit.data("changed",true);
});

submit.on("click",function(){
   if($(this).data("changed")){ //do something }
}

So why not just an upper scope flag?

var flag = false;
$("#input_id").on("keyup",function(){
  // check stuff ...
  flag = true;
});

$("#form_submit").on("click",function(){
  if (flag) {

  } else {

  }
}

本文标签: javascriptPass a flag from one event to another in JqueryStack Overflow