Nezam
Nezam

Reputation: 4132

cant change attribute in jquery

I am simply not able to get to update an attribute of an element using jQuery.

HTML:

<input type="checkbox" name="row1" value="" >

jQuery:

$(document).ready(function (event) {
    $("input[type='checkbox']").change(function (e) {
        var name = $(this).attr('name');
        // grab name of original
        var value = $(this).attr('value');
        // grab value of original
        var ischecked = $(this).is(":checked");
        //check if checked
        if (!ischecked) {
            $('#' + name).removeAttr("checked");
            alert("removed attr ");
        } else {

            $('#' + name).attr("checked", "checked");
            alert($('#' + name).attr("checked"));

        }

    });
});

shows up an alert 'undefined' when i check.

Upvotes: 0

Views: 262

Answers (4)

Jai
Jai

Reputation: 74738

Try changing this way: check the jsbin

$(document).ready(function (event) {
  $("input[type='checkbox']").change(function (e) {
    var name = $(this).attr('name');
    var value = $(this).val();
    var ischecked = $(this).is(":checked");

    if (!ischecked) {
        $(this).prop("checked", false);
        alert("removed attr ");
    } else {
        $(this).prop("checked", true);
        alert($(":checked").val());
    }

  });
});

shows up an alert 'undefined' when i check.

This should be because you are not trying to check the value instead you can check the length of the **$(':checked')**

alert($(":checked").length);

and if you try to check this:

alert($(":checked"));

You will get [object object] in alert.

Upvotes: 1

Vincens von Bibra
Vincens von Bibra

Reputation: 113

Your selector is wrong. You haven´t set an ID to the checkbox. It should look like that:

$("input[name='"+name+"']").removeAttr("checked");

Upvotes: 0

spiritwalker
spiritwalker

Reputation: 2257

'#' works for id but not name

<input type="checkbox" name="row1" id="row1" value="" >

or use this to get reference.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

change $('#' + name) to $(this)

$('#'+name).removeAttr("checked");

to

$(this).removeAttr("checked");

If using jQuery 1.6 or later, you could use

$(this).prop("checked", false);

Upvotes: 2

Related Questions