7

I want execute the alert inside the $("#address").change function , but that needs to be done only if the the value is changed using the button .

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
   $('button').click(function(){
    $("#address").val("hi")
   })
   $("#address").change(function(){
    alert("The text has been changed.");
   });

});
</script>
</head>
<body>
<input type="text" id="address">
<button>Click</button>
</body>
</html>
2
  • 1
    $("#address").change will trigger if you perform any change in text field. If you want to trigger alert only when button click why you don't use alert inside button click function. Commented Mar 26, 2014 at 6:30
  • This is not my original application ! My application deals with changing values dynamically to all the txt fields and i have to trigger event for each! This sample can help with my application ! So i posted this Commented Mar 26, 2014 at 6:33

3 Answers 3

8

You can trigger change event in click function:

$('button').click(function(){
  $("#address").val("hi")
  $("#address").change(); //or $("#address").trigger("change");
});
$("#address").change(function(){
  alert("The text has been changed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="address" type="text">
<button>Change</button>

Sign up to request clarification or add additional context in comments.

Comments

0

Trigger the change event like this:

$('button').click(function(){
    $("#address").val("hi")
    $("#address").trigger('change');
  });
  $("#address").change(function(){
    alert("The text has been changed.");
  });

Comments

0

If you want the alert on #address change only when the button is clicked and not when changing the #address value manually:

var textChangedHandler = function() {
    alert("The text has been changed.");
};

$('button').click(function(){
    // Attach event handler for 'change' to #address
    $("#address").bind("change", textChangedHandler);

    // Update #address value
    $("#address").val("hi");

    // Trigger 'change'
    $("#address").trigger('change');

    // Remove event handler for 'change' from #address
    $("#address").unbind("change", textChangedHandler);
});

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.