user3681380
user3681380

Reputation: 23

Get the value of an id element in jquery

How in jQuery I can get the value of my element (i.e.: 2).

I try with $(this).("label").attr('for'), but it does not work.

Thanks.


My HTML is:

<div class="checkbox col-sms-6 col-sm-6 moods">
  <label for="2">
    <input type="checkbox" id="2">2
  </label>
</div>

My js is:

$("form").on("click", "div.moods", function(event){
    var moodsId = $(this).("label").attr('for');
    var moodsBtn = $('#moods');
    var moodsBtnValue = $('#moods').val();

    if(moodsBtnValue.toString().indexOf(moodsId) == -1) { moodsBtn.val(moodsBtnValue + moodsId + ","); }
    else { moodsBtn.val(moodsBtnValue.replace(moodsId + ',','')); }
});

Upvotes: 1

Views: 69

Answers (2)

dave
dave

Reputation: 64725

You need to use the .find method to get a subelement:

var id = $(this).find("label").attr('for')

Then to get the value you would do:

$('#moods').find("#" + id).val();

Upvotes: 2

Liam
Liam

Reputation: 2837

Another way

$(this).find(">:first-child").attr('for');

or

$(this).children(":first").attr('for');

Upvotes: 0

Related Questions