简体   繁体   English

复选框已在javascript / jquery中选中

[英]Checkbox checked in javascript/jquery

Here is my HTML part: 这是我的HTML部分:

 <input type="radio" name="checkbox_1"  id="checkbox_1" value="john" emp-id="john">
 <input type="radio" name="checkbox_1"  id="checkbox_2" value="john" emp-id="jim">
 <input type="radio" name="checkbox_1"  id="checkbox_3" value="john" emp-id="sam">
 <input type="radio" name="checkbox_1"  id="checkbox_4" value="john" emp-id="George">

I want to compare value and emp-id and if it is true, i need the checkbox to be checked so that checkbox will be displayed in the frontend as checked. 我想比较值和emp-id,如果为true,则需要选中该复选框,以便选中时该复选框将显示在前端。

You could filter radios: 您可以过滤收音机:

$(':radio').filter(function(){
   return $(this).attr("emp-id") === this.value
}).prop('checked', true);

Wrap it inside document ready handler if needed. 如果需要,将其包装在文档就绪处理程序中。

html: HTML:

<input type="radio" ... checked>

javascript: JavaScript的:

document.getElementById("checkbox_3").checked=true;

First change the HTML to use checkboxes: 首先将HTML更改为使用复选框:

HTML HTML

<input type="checkbox" name="checkbox_1"  id="checkbox_1" value="john" emp-id="john">
<input type="checkbox" name="checkbox_1"  id="checkbox_2" value="john" emp-id="jim">
<input type="checkbox" name="checkbox_1"  id="checkbox_3" value="john" emp-id="sam">
<input type="checkbox" name="checkbox_1"  id="checkbox_4" value="john" emp-id="George">

Javascript 使用Javascript

$(document).ready(function(){
    $("input[name='checkbox_1']").each(function(i,e){
       var el = $(this);
        this.checked = el.attr("emp-id") == el.val();
    });
});

JS Fiddle: http://jsfiddle.net/MFpUQ/3/ JS小提琴: http //jsfiddle.net/MFpUQ/3/

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

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