简体   繁体   中英

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>

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

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

DEMO

change:

console.log(select.text());

to

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

Demo:: jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM