简体   繁体   English

使用jQuery根据用户输入(到另一个复选框)来选中复选框

[英]Using jQuery to check boxes based on user input (to another check box)

This is a very simple use of jQuery that I can't get working. 这是jQuery的非常简单的用法,我无法使用。

When one check box is checked, I'd like the other to become checked. 选中一个复选框后,我希望另一个复选框也被选中。

HTML: HTML:

<input onchange="toggleRegion()" id="ESARO" type="checkbox" class="region"
value="ESARO" name="ESARO">ESARO

<br /><br />

<input type="checkbox" class="country" value="Afghanistan" name="country2"
/>Afghanistan

jQuery: jQuery的:

function toggleRegion() {
    if ($('#ESARO').is(':checked')) {
        $('input[value="Afghanistan"]').attr('checked', true);
    }
}

jsfiddle: 的jsfiddle:

http://jsfiddle.net/jsJU8/ http://jsfiddle.net/jsJU8/

What I've tried: 我尝试过的

I have another function which does a very similar thing for a group of check boxes by class which works perfectly: 我有另一个函数,它对一组按类别显示的复选框执行非常相似的操作,效果非常好:

function toggleStatus() {
if ($('#TLO1').is(':checked')) {
        $('.country').attr('checked', true);

    } 
}

So I presume that the error lies in the selection of the element by value, rather than by class, as this is the only difference between the functions. 因此,我认为错误在于按值而不是按类别选择元素,因为这是函数之间的唯一区别。

To this end I've tried adjusting that selector;'s syntax to match various examples I've found (single quote, double quote, no quote etc) but haven't had any luck.# 为此,我尝试调整选择器;的语法以匹配我发现的各种示例(单引号,双引号,无引号等),但是没有任何运气。

Although I note that it may be a possible error that I'm using javascript (onChange) to call a jQuery function. 虽然我注意到我使用javascript(onChange)调用jQuery函数可能是一个错误。 Is that an issue? 那是个问题吗?

All help greatly appreciated - thank you 感谢所有帮助-谢谢

You code is working but you have to choose no-wrap (body) option in first drop down. 您的代码正在运行,但是您必须在第一个下拉列表中选择no-wrap(body)选项。

Live Demo 现场演示

function toggleRegion() {
    if ($('#ESARO').is(':checked')) {
        $('input[value="Afghanistan"]').attr('checked', true);
    }
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM