javascript - 当在其他地方以编程方式选中复选框时,如何使 jQuery 代码执行?

标签 javascript jquery

我有一个带有下拉框的 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/

相关文章:

javascript - jquery 脚本无法在 HTML 中运行

javascript - 在悬停时使用替换后恢复 div

jquery - Webkit 关键帧不适用于 safari 或 chrome

javascript - javascript 中的当前日期

javascript - 在当前JS中添加fadeOut

javascript - 如何使用 Immutability-helper 进行条件更新

javascript - 在 Javascript 文件中组织顶级函数

Javascript/Jquery 在浏览器宽度变化时运行函数?

jquery - Bootstrap 4 - 进度条进度

javascript - jQuery 多行表单 : disable submit until each row has a radio checked