Reputation: 1659
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
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
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
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
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