Display value in select tag instead of text
I want to create a dropdown that should display a value instead of text.
But when I click the dropdown, the option should display text instead of value.
I've added an example here, but it doesn't work 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 an example image.
+3
source to share
2 answers
try it
$(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 created an additional option that will not display. Now when the user changes any option, I will change the value and text of the 1st item that is not displayed and then set the first value to be selected
+3
source to share
I don't know how his help is complete, but if you are ok with this, you can use ....
bind the value in both the text box and the value box, and when you get the text, you can match the value with the old one.
<select>
<option name="One" value="1">1</option>
<option name="Two" value="2">2</option>
<option name="Three" value="3">3</option>
<option name="Four" value="4">4</option>
</select>
sorry if this is not worth it for you ....
0
user7584647
source
to share