简体   繁体   中英

selected option doesn't select using JQuery

I'm working on my web appliction using JQuery. My select option menu doesn't print selected option.

 $(function() { $(document).on('click', ".class", function() { var id = $(this).attr("id"); var index = $('#mySelect').val(); if (id == "mySelect") { /* for(let i=0; i<3; i++) $("#mySelectOptionIndex"+i).attr("selected", false) $("#mySelectOptionIndex"+index).attr("selected", true) */ $("#mySelect").val(index); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="mySelect" class="form-control form-control-sm class"> <option id="mySelectOptionIndex0" value=0 selected> A </option> <option id="mySelectOptionIndex1" value=1> B </option> <option id="mySelectOptionIndex2" value=2> C </option>

My code is working and select correct option but it doesn't print the selected option. Using browser I see that selected attribute is righty added. I tried using e.preventDefault();, using .prop(selected, true) instead .attr() but without soluton. How can I solve? Thanks

try it to access option value or option html :

$(function() {
        $(document).on('change', ".class", function() {
            var optionSelected = $("option:selected", this);
            
            var selectedText = $(optionSelected).html();
            var valueSelected = this.value;

            console.log(selectedText, valueSelected);
        });
    });

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