Reputation: 35
I am trying for get all value of drop down list with multiple option
<select name="select" multiple id="select">
<option value="aa">aa</option>
<option value="bb">bb</option>
</select>
<BR><BR>
<input type=submit value="Print All" onClick="printAll()">
<script>
function printAll()
{
var selectedValues = $("#select").val();
alert(selectedValues);
}
</script>
Any body help me?
Upvotes: 0
Views: 886
Reputation: 4578
You need to change the button type = "submit"
to type = "button"
and give that button some id :
<input type="button" value="Print All" id="print">
and use this following jQuery code :-
$(document).ready(function()
{
$('#print').click(function()
{
var val = $("#select").val();
alert(val);
});
});
Working Demo :- JSFiddle Demo
Or you can do like this :
$(document).ready(function()
{
$('#print').click(function()
{
$('#select option:selected').each(function()
{
alert(this.value);
});
});
});
Upvotes: 0
Reputation: 107586
What you've done should work (eventually). val()
will return an Array
of selected option values, e.g.:
console.log(selectedValues); // [ "aa", "bb" ]
If you want to turn the array back into a string to display it, you might do:
alert(selectedValues.join(', ')); // "aa, bb"
But first you need to change your input type to button
so your page isn't posting back:
<input type="button" value="Print All" onClick="printAll()">
Or, since you're using jQuery, do this the right way with an unobtrusive event binding (removing the inline onClick
handler):
<input type="button" id="print" value="Print All">
And then add a click
handler with jQuery:
<script type="text/javascript">
$(function() {
$('#print').click(function() {
var selectedValues = $("#select").val();
alert(selectedValues.join(', '));
});
});
</script>
Upvotes: 3
Reputation: 7954
$('#select option:selected').each(function(){
console.log(this.value);
});
Upvotes: 1
Reputation: 28513
Try this : What you have done should work, also you can try below jquery which gives you option values which are selected.
function printAll()
{
var selectedValues = new Array();
$("#select option:selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
// for comma seperated values use
// alert(selectedValues.join(', '));
}
Upvotes: 0