Reputation: 3085
I am trying to get the value of <select>
tags which is kind of a simple task. I have done it several time before but it looks wired no to work this time.
My select tag is as following:
<select id="tshirt['+$(this)[0].id+'][size]" style="width: 55px;" name=tshirt['+$(this)[0].id+'][size]">
<option value="small">S</option>
<option value="medium" selected="selected">M</option>
<option value="large">L</option>
<option value="xlarge">XL</option>
</select>
I tried to retrieve the selected element as following
$('#tshirt['+id+'][size] :selected').text()
$('select #tshirt['+id+'][size]').val()
$('#tshirt['+id+'][size]').children("option").filter(":selected").text()
I always get either undefined or []
or ""
. Any suggestions on how to solve?
Upvotes: 1
Views: 396
Reputation: 385789
In CSS selectors, #tshirt[foo]
does not mean "match the element with id tshirt[foo]
. It means "match the element with id tshirt
that has <invalid condition>".
To avoid this problem, restrict yourself to ids that don't contains CSS metacharacters or escape the metacharacters.
$('#tshirt\\['+id+'\\]\\[size\\] :selected')
Tested with the following:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<select id="tshirt[foo][size]" style="width: 55px;" name="tshirt[foo][size]">
<option value="small">S</option>
<option value="medium" selected="selected">M</option>
<option value="large">L</option>
<option value="xlarge">XL</option>
</select>
<script>
var id = "foo";
var rs = $('#tshirt\\['+id+'\\]\\[size\\] :selected');
alert("size = " + rs.size());
rs.each(function(i, ele){ alert("value = " + ele.value); });
</script>
Upvotes: 2