我有一个带有下拉框的 HTML 表单(<select id="state"> ... </select>
标记)。我旁边有一个复选框 ( <input type="checkbox" id="not-from-US" />
)。
HTML 下拉菜单包含所有美国 stas(MO、TX、AL 等)的列表。但如果用户不是来自美国,他/她会选中“不是来自美国”复选框。现在在 jQuery 中,我已经对复选框进行了编程(通过 .change()
),以生成一个附加字段,用于在选中该复选框时选择一个国家/地区。它还使下拉菜单选择“N/A”选项。
我还对表单进行了编程,以便如果用户从“州”下拉菜单中选择“不适用”,则会选中“不是来自美国”复选框。但我如何将这两个事件联系在一起呢?当以编程方式选中该复选框时,选中该复选框时的匿名函数不会触发。
我该如何解决这个问题?
编辑:抱歉,我忘记附加示例代码。这是:
------------------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('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.
}
});
});
最佳答案
使用函数 checkbox.click() 而不是设置 checkbox.checked = true;
我已经编辑了这篇文章。
关于javascript - 当在其他地方以编程方式选中复选框时,如何使 jQuery 代码执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6932844/