Reputation: 473
i want to get select box option value and option text in click event using jquery my code is below
Html Code:
<select id="tskill" name="tskill" >
<option value="1">One </option>
<option value="2">Two </option>
<option value="3">three </option>
<option value="4">four </option>
</select>
Jquery:
$('#tskill').click(function(){
var id = $(this).val();
});
If i click "four" in dropdown it will return id=4 but i want to get id with text "four". i used that syntax
$(this).text();
$(this).html();
But it will return whole select box text. How can i get click able text value?
Upvotes: 0
Views: 9173
Reputation: 18987
I am not sure why you are using click
event to get the selected option value and text. If this is what you really want, then try below code.
$('#tskill').click(function(){
var id = $(this).val();
var text = $(this).find('option:selected').text();
alert(id + ', ' + text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="tskill" name="tskill" >
<option value="1">One </option>
<option value="2">Two </option>
<option value="3">three </option>
<option value="4">four </option>
</select>
Mean while
I would recommend using the change
event handler to get the job done. Like this
$('#tskill').change(function(){
var id = $(this).val();
var text = $(this).find('option:selected').text();
alert(id + ', ' + text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="tskill" name="tskill" >
<option value="1">One </option>
<option value="2">Two </option>
<option value="3">three </option>
<option value="4">four </option>
</select>
Upvotes: 1
Reputation: 20740
Use change
event instead of click
like following.
$('#tskill').change(function () {
var id = $(this).val();
var text = $('option:selected', this).text(); //to get selected text
alert(text)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="tskill" name="tskill" >
<option value="1">One </option>
<option value="2">Two </option>
<option value="3">three </option>
<option value="4">four </option>
</select>
Upvotes: 1