I want to create a dropdown list, which should display value instead of text.
But, when I click the dropdown, the option should display the text instead of value.
I have added an example here, but it is not working as expected:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<select>
<option name="One" value="1">One</option>
<option name="Two" value="2">Two</option>
<option name="Three" value="3">Three</option>
<option name="Four" value="4">Four</option>
</select>
<script>
$(document).ready(function() {
$('select').click(function() {
$('select :selected').text($('select :selected').val());
});
});
</script>
</body>
</html>
This is a picture of the example.
Try this
$(document).ready(function() {
$("select option[value="+$('select option:selected').val()+"]").css({"background-color":"#0000ff","color":"#fff"});
$('select').change(function() {
$('select option')[0].value=$('select option:selected').val();
$('select option')[0].innerHTML=$('select option:selected').val();
$("select").val($('select option:selected').val());
$("select option").css({"background-color":"","color":""});
$("select option[value="+$('select option:selected').val()+"]").css({"background-color":"#0000ff","color":"#fff"});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option name="One" value="1" style="display:none">1</option>
<option name="One" value="1">One</option>
<option name="Two" value="2">Two</option>
<option name="Three" value="3">Three</option>
<option name="Four" value="4">Four</option>
</select>
I have created an extra option which will be display none. Now whenever user will change any option I will change the value and text of the 1st element which is not displaying and Then setting the first value to be selected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With