Simon
Simon

Reputation: 116

Add 'value' to option in jquery based on text

I want to add value to option based on text in option field.

Here is code:

<select id="select_1">
 <option>09:30</option>
 <option>10:00</option>
 <option>11:30</option>
</select>

jQuery code itself is to automatically add the 'value' attribute and value based on the text

<select id="select_1">
 <option value="0930">09:30</option>
 <option value="1000">10:00</option>
 <option value="1130">11:30</option>
</select>

It's possible?

Upvotes: 0

Views: 35

Answers (2)

Developer
Developer

Reputation: 136

Try this

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <select id="select_1">
 <option>09:30</option>
 <option>10:00</option>
 <option>11:30</option>
</select>
</body>
<script>
    $(document).ready(function() {
        $("option").each(function(index) {
            $(this).attr("value", $(this).html());
        });
    });
</script>

</html>

Upvotes: 1

BOZ
BOZ

Reputation: 2020

Yes, this is possible,

To test it, run the code snippet and change the select list.

$("#select_1 > option").each(function() {
  this.value = this.text.replace(':', '');
});

$("#select_1").on('input', function() {
  alert(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select_1">
  <option>09:30</option>
  <option>10:00</option>
  <option>11:30</option>
</select>

Inspect in chrome seem like this

enter image description here

Upvotes: 1

Related Questions