user973479
user973479

Reputation: 1659

Jquery - How to get the input value from a label

If I have a bunch of label/selects like:

<label for="blah" class="myClass">
<select id="blah" multiple="multiple" size="5">

How would I get the value of the selected item based off the label?

So far I have..

    $('label[class="myClass"]').each(function(){
        var labelTxt = $(this).text();
        var labelForTxt = $(this).attr('for');
        var inputVal = $('#'+labelForTxt).val();
    });

but inputVal isn't the value I expect to see. Instead I get either null/undefined. Am I missing something?

Thanks!

Upvotes: 4

Views: 8851

Answers (5)

Yash Agrawal
Yash Agrawal

Reputation: 51

In my use case i was working with mdc(material design) and wanted to untick the checkbox whenever i reopen the checkbox after ticking and cancelling in previous operation.

var checkbox = document.querySelector("#checkbox-"+ $(this).val()+ "-label")

var inputId = checkbox.htmlFor

var input = document.getElementById(inputId)
input.checked = false;

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

For multiple select:

$("label.myClass select").change(function () {
          var inputval = "";
          $("select option:selected").each(function () {
                inputval += $(this).val() + " ";
              });
          $("div[id='content']").text(inputval);
        });
<div id='content'></div>

Upvotes: 1

dku.rajkumar
dku.rajkumar

Reputation: 18568

everything is fine, if you hav given close tag for label and select and options in select .check the code , i have modified and implemented. http://jsfiddle.net/XaMg9/5/

Upvotes: 4

U-DON
U-DON

Reputation: 2140

One thing to note. You can use the selector $('label.myClass') instead of $('label[class="myClass"]'). It's just more standard. That said, if you want the value of each select contained within a label, do this.

$('label.myClass select').each(function(){
    var inputVal = $(this).val();
});

Upvotes: 1

tmjam
tmjam

Reputation: 1039

Not sure if you are looking for something like this TEST

Upvotes: 1

Related Questions