Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display value in select tag instead of text

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.

example

like image 856
Raffel Avatar asked Oct 18 '22 08:10

Raffel


1 Answers

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

like image 152
Sourabh Somani Avatar answered Oct 27 '22 08:10

Sourabh Somani