简体   繁体   English

通过单击标签来更改输入属性

[英]Change input property by clicking on a label

What I need: 我需要的:

If I click on a label I want to add a checked in the input. 如果单击标签,则要在输入中添加一个选中的内容。

When I try it I got two alerts with a true. 当我尝试它时,我得到了两个带有真实警报。 That isn't correct and in firebug the input field doesn't change. 这是不正确的,并且在Firebug中,输入字段没有更改。

For a test I want to output the filterguid but the alerts are empty and again there are two alert boxes. 对于测试,我想输出filterguid,但警报为空,再次有两个警报框。

HTML Markup: HTML标记:

<li>
 <label>
  <input type="checkbox" filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b"> Weiblich
  </label>
</li>

jQuery: jQuery的:

$('.targetgroup-frame li label').on('click', function(){
   $(this).children().prop('checked', true);
    alert($(this).children().prop('filterguid'));
});

Is my jQuery code correct? 我的jQuery代码正确吗?

Thank you. 谢谢。

HTML - no changes except adding a id on the input for easy jquery-targeting. HTML-除了在输入上添加ID以简化jquery定位之外,没有其他更改。

<li>
    <label>
        <input type="checkbox" id="checkbox" filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b"> Weiblich
    </label>
</li>

You don't have to use jquery to change the state of the checkbox since html does that for you. 您无需使用jquery来更改复选框的状态,因为html会为您执行此操作。

You can listen for the changes and get the checked state and filterguid with the following script. 您可以侦听更改并使用以下脚本获取检查状态和filterguid。

$('#checkbox').change(function() {
    console.log($(this).attr('filterguid'))
    console.log(this.checked)
});

Label for attribute 属性标签

The ID of a labelable form-related element in the same document as the label element. 与label元素在同一文档中的与labelable表单相关的元素的ID。 The first such element in the document with an ID matching the value of the for attribute is the labeled control for this label element. 文档中具有与for属性的值匹配的ID的第一个此类元素是此label元素的带标签的控件。

Also, you should data-attribute instead of attribute . 另外,您应该使用data-attribute而不是attribute attribute is not supported by HTM5 attribute不被支持HTM5

Sample 样品

 $("#chkTest").on("click", function(){ console.log($(this).data("filterguid")) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> <label for="chkTest"> <input id="chkTest" type="checkbox" data-filterguid="895f7bc2-d609-4b09-97f9-c09f9fc90d1b">Weiblich </label> 

References 参考文献

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

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