简体   繁体   English

多个jQuery切换未正确更改

[英]Multiple jQuery toggles not changing correct

I have 2 toggle buttons, like this: 我有2个切换按钮,如下所示:

  $(".ui.toggle" ).on( "click", function() { if (!$('#thetoggle').is(':checked')) { $('#thetoggle').prop('checked', true ); } else { $('#thetoggle').prop('checked', false); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="ui toggle checkbox"> <input id="thetoggle" value="false" name="ownplace" type="checkbox"> <label>&nbsp;</label> </div> <div class="ui toggle checkbox"> <input id="thetoggle" value="false" name="otherplace" type="checkbox"> <label>&nbsp;</label> </div> 

So when i click the second toggle, the first one changes the checked status, which it shouldn't do - I want them to change independently. 因此,当我单击第二个切换开关时,第一个切换了选中状态,这是不应该的-我希望它们独立进行更改。 I get why it isn't working, as I dont have any selectors for the second as this is the same as the first. 我知道为什么它不起作用,因为我没有第二个选择器,因为它与第一个相同。 However, I was wondering if there is a way to do this using some sort of easy selector which will work on all toggles in the future, with the ID of thetoggle 不过,我想知道是否有办法做到这一点使用某种容易选择的,这将在未来所有的切换工作,用的ID thetoggle

An id can only refer to one element, $('#thetoggle') will always return the first element with that id found in the DOM. 一个id只能引用一个元素, $('#thetoggle')将始终返回在DOM中找到的具有该id的第一个元素。 You should use class instead, and in your event handler you can use: 您应该改为使用class ,并且在事件处理程序中可以使用:

$(this).find('.thetoggle`);

to get the child node. 获取子节点。 You could also remove class and id and just use tag type: 您也可以删除类和ID,仅使用标记类型:

var checkbox = $(this).find('input[type=checkbox]');

Checkboxes are able to be checked independanty without any javascript: 复选框可以独立检查,而无需使用任何JavaScript:

 <div class="ui toggle checkbox"> <input class="thetoggle" value="false" name="ownplace" type="checkbox"> <label>&nbsp;</label> </div> <div class="ui toggle checkbox"> <input class="thetoggle" value="false" name="otherplace" type="checkbox"> <label>&nbsp;</label> </div> 

Although if you are looking for them to behave like radio buttons (ie only one can be checked at a time), you can try this (which does change the id's to classes): 尽管如果您希望它们的行为类似于单选按钮(即一次只能检查一个),则可以尝试执行此操作(它将ID更改为类):

 $(".thetoggle").change(function() { $(".thetoggle").prop('checked', false); $(this).prop('checked', true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="ui toggle checkbox"> <input class="thetoggle" value="false" name="ownplace" type="checkbox"> <label>&nbsp;</label> </div> <div class="ui toggle checkbox"> <input class="thetoggle" value="false" name="otherplace" type="checkbox"> <label>&nbsp;</label> </div> 

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

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