user3340300
user3340300

Reputation: 67

Checkbox checked in javascript/jquery

Here is my HTML part:

 <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.

Upvotes: 1

Views: 74

Answers (3)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

First change the HTML to use checkboxes:

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

$(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/

Upvotes: 0

uyitalk
uyitalk

Reputation: 51

html:

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

javascript:

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

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

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.

Upvotes: 1

Related Questions