How do I make jQuery code execute when a checkbox is checked programatically somewhere else?
I have a HTML form with a dropdown box (<select id="state"> ... </select>
tag). I have a checkbox next to it (<input type="checkbox" id="not-from-US" />
).
The HTML dropdown item has a list of all United States stas (MO,TX,AL,etc.). But if the user is not from the United States, he/she checks the "Not from US" checkbox. Now in jQuery, I have programmed the checkbox (via .change()
) to generate an additional field for selecting a country when the checkbox is checked. It also makes the dropdown select the "N/A" option.
I also programmed my form so that if the user selects "N/A" from the "States" dropdown menu, the "Not from US" checkbox gets checked. But how do I link the two events together? When the checkbox is programatically checked, the anonymous function for when the checkbox is checked does not fire.
How can I fix this?
Edit: Sorry, I forgot to attach the sample code. Here it is:
------------------index.php------------------
<form action="index.php" method="post">
<select id="state">
<option value="None">None</option>
<option selected="true" value="AL">AL</option>
<option value="AK">AK</option>
<option value="AZ">AZ</option>
<!--etc.-->
</select>
<input type="checkbox" id="not-from-usa" name="not-from-usa" />
</form>
------------------main.js------------------
$(document).ready(function(){
$('#state').change(function(){
if ($(this).val() == "None") {
$('#not-from-usa').attr('checked','checked'); // This is the important bit.
// So now the #not-from-usa checkbox is checked. So the code below should execute, right?
} else {
$('#not-from-usa).removeAttr开发者_JS百科('checked');
}
});
$('#not-from-usa').change(function(){
if($(this).attr('checked')) {
// Create an input element that the user can enter a country
// Code omitted for clarity.
// The code in here should execute once the checkbox is checked or unchecked.
$('#state').val("None"); // Set the dropdown to the "None" selection
} else {
// Remove the extra input element that lets the user enter a country.
}
});
});
Use the function checkbox.click() rather then setting checkbox.checked = true;
I have edited this post.
Well the http://api.jquery.com/trigger/ gives you what you want.
With trigger you dispatch the event. So just add one $("checkbox").trigger('click'); That should do the trick.
In pure javascript,you can use the .checked
attribute:
if(document.getElementById("not-from-US").checked) {
//checked, do something
} else {
//not checked, do something..
}
精彩评论