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>
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>
Trigger the change event like this:
$('button').click(function(){
$("#address").val("hi")
$("#address").trigger('change');
});
$("#address").change(function(){
alert("The text has been changed.");
});
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.