Hey Guys, I have a form with 4 select tags:
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select class="section_1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4开发者_如何学C">Option 4</option>
</select>
I want to get by jquery all the classes of "section_1" and their selected options value.
I got now: $(".section_1")... by how I continue?
Thanks!
You can use .each
for looping through that
$(".section_1").each(function(){
alert(this.value);
});
or you can use .map()
var selectedValues = $(".section_1").map(function(){
return this.value;
}).get().join(',');
You can see a working demo
To get all the values into an array:
var values = [];
$(".section_1").each(function() {
values.push($(this).val());
});
Or, with .map()
as J-P suggested:
var values = $.map($(".section_1"), function(i) {
return i.value;
});
Really just a matter of taste which one you use.
$(".section_1 option:selected").each(function() {
alert($(this).val());
});
Or as Matt pointed out in the comments, calling .val() on a select
will output all selected option
values in an array:
var values = $('.section_1').val();
alert(values.join(', '));
Something like this?:
$(".section_1").each(function(){
var currentObjVal = $(this).val();
//do something with your currentObjVal...
});
If you just call below and pass it as the data parameter on the jquery ajax call it will take care of packaging the name and value for you. Try it. You don't need to loop through anything and make it a string. If all of the selects are the same name it will pass it as an array with the same names. If they are not it will break it out. Just make sure to have the names of the form elements set.
Example
$(function(){
$("#bt1").click(function(){
var selectedVals = $("select.section_1");
$.ajax({
type: "POST",
url: "www.yoururl.com",
data: selectedVals,
success: function(data) {
}
});
});
});
the option:selected filter is required in cases when you want to do some operations on the options tag, instead of the select tag. In any other cases, you can just use the .val() method.
The cases might be like
$('select option:selected').remove(); // remove the selected items
or
$('select option:not(:selected)').remove() // remove the items not selected
精彩评论