Jerielle
Jerielle

Reputation: 7520

How to get the value of a custom attribute using jquery?

Can you help me with my problem? My problem is, I am trying to create a dynamic form. In my form I have a part that has a check all function. But what I want is. The check all function will trigger if the custom attribute is found.

Here's my sample code:

 <input type="checkbox" data-check="checkAll" />CHECK ALL<br/> <!-- The data-check is used for validating if the user check the checkbox -->

<div id="container">
    <div id="parent1">
        <div id="child1">
            <input type="checkbox" val="45" />ITEM A
        </div>
    </div>

    <div id="parent2">
        <div id="child2">
            <input type="checkbox" val="41" />ITEM B
        </div>
    </div>

    <div id="parent3">
        <div id="child3">
            <input type="checkbox" val="1" />ITEM C
        </div>
    </div>
</div>

The expected result should be:

  1. After the user check the check all checkbox, the system should validate if there is an existing data-check value.
  2. If found, the checkboxes from the parents should be checked

By the way I am using jquery 1.5.2

Upvotes: 0

Views: 901

Answers (4)

palaѕн
palaѕн

Reputation: 73886

You can do this:

$("input[data-check='checkAll']").change(function(){
     $("#container :checkbox").prop("checked",this.checked);
});

Fiddle Demo

Upvotes: 1

Rituraj ratan
Rituraj ratan

Reputation: 10378

$("input[data-check='checkAll']").change(function(){
if($(this).is(":checked"))
{
$("#container").find(":checkbox").prop("checked",true);
}
else{
$("#container").find(":checkbox").prop("checked",false);
}

});

reference prop() and :checked

Upvotes: 1

TGH
TGH

Reputation: 39248

var customData = $('input[type="checkbox"]').data("check");

Try the above

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

To read the data-* attribute value you can use .data(), like in $(el).data('check')

$('input[type="checkbox"]').change(function(){
    var $this = $(this);// this is the checkbox
    var checkdata = $this.data('check');
    if(checkdata == 'all'){
    }
})

or you you want to add a handler for only the check all checkbox then

$('input[type="checkbox"][data-check="checkAll"]').change(function(){
    //this will be fired only of the checkall checkbox is changed
    $('input[type="checkbox"]').not(this).prop('checked', this.checked)
})

Demo: Fiddle

Upvotes: 1

Related Questions