Reputation: 63
I want to get the value of the dropdown on document ready but i am getting only the first value of the drop down I have tried this
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var car=$('.car').val();
alert(car);
});
</script>
</head>
<body>
<select class="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
Upvotes: 1
Views: 6842
Reputation: 1719
$(document).ready(function()
{
$('.car').on('change',function(){
var car=$('.car').val();
alert(car);
});
});
Upvotes: 0
Reputation: 54
May be you could add attribute 'selected' to your desired option. Please consider html below. P.S.: I've added attribute on 'Mercedes'.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var car=$('.car').val();
alert(car);
});
</script>
</head>
<body>
<select class="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes" selected>Mercedes</option>
<option value="audi">Audi</option>
</select>
</body>
</html>
Upvotes: 0
Reputation: 4210
You have to given the onchange=""
in the select tag so that when you change the select it will be fetching the value and then it will be alerting it.
Here is the sample that i have provided for you to understand.
function myalert(a)
{
alert(a);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="test" id="test" onchange="myalert(this.value)">
<option value="">Please Select</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
Output: - It will be alerting the value based on the chosen value from the select tag
Upvotes: 0
Reputation: 3302
try this
<script>
$(document).ready(function()
{
var car = $('.car :selected').val();
alert(car);
});
</script>
Upvotes: 2