1

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 + ',','')); }
});
  • 1
    It would be better if you made a jsFiddle demo. – nmz787 Aug 15 '14 at 21:01
  • 1
    possible duplicate of [How do I get the value of a textbox using jQuery?](http://stackoverflow.com/questions/463506/how-do-i-get-the-value-of-a-textbox-using-jquery) – agconti Aug 15 '14 at 21:02
  • @DavidThomas - it also doesn't have a HEAD/BODY/HTML tag -- he's just showing us a snippet. – Jason Aug 15 '14 at 21:12
  • So we assume, but since we're not seeing the relevant ('[MCVE](http://stackoverflow.com/help/mcve)') code, it's harder to offer definitive help. – David Thomas Aug 15 '14 at 21:20

2 Answers2

2

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();
dave
  • 62,300
  • 5
  • 72
  • 93
0

Another way

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

or

$(this).children(":first").attr('for');
Liam
  • 2,837
  • 23
  • 36