Tarang Hirani
Tarang Hirani

Reputation: 590

Jquery set value of option element to be the text of the element

I need to set the value attribute of the option element equal to the text of the option element itself. This is the code I have currently. For some reason it is concatenating the strings.

Here's the HTML markup.

    <select id="ResidentialBuildingType" name="ResidentialBuildingType">
     <option>SFD</option>
     <option>Test</option>
    </select>

Here's the jquery code:

    <script>
    $(document).ready(function () {
        var select = $('#ResidentialBuildingType > option');
        $(select).each(function (index) {
            console.log(select.text());
        });
    });
    </script>

Upvotes: 1

Views: 54

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use the .attr() receiver function to achieve that,

$('#ResidentialBuildingType > option').attr("value",function(){
  return $(this).text();
});

DEMO

Upvotes: 2

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

change:

console.log(select.text());

to

console.log($(this).text());

Demo:: jsFiddle

Upvotes: 1

Related Questions