简体   繁体   中英

How to make the JSON result as selected in HTML select option on page load

I want to get the select option value as selected on load of page through JSON.

On load based on from time and to time passed through ajax, I will filter shift timings name and id as JSON result. Everything working fine but I don't know how to make the JSON result as selected in the html select option value.

This is my select HTML:

<select name="shift_name<%=index%>" id="shift_name<%=index%>" class="form-control"><option value="1">Morning Shift</option>
<option value="2">Evening Shift</option>
<option value="3">Night Shift</option>
<option value="4">Full Day Shift</option>
<option value="5">Full Night Shift</option></select>

This is my onload function to get JSON result values for select.

$(document).ready(function () {
var from_time = $('.from_time_<%=index%>').val();
var to_time = $('.to_time_<%=index%>').val();
    $.ajax({
        type: "GET",
        url: "/employees/gate_passes/get_shift_timings",
        dataType: "json",
        data: {'from_time': from_time, 'to_time':to_time },
        success: function(result){
            for(term in result){
                alert(result[term].id) #getting select option value to be selceted here
                alert(result[term].name)
                render = false;
            //$('.select option[value="2"]').prop('selected', true);
            //$('select#shift_time<%=i.index%> option[value="+result[term].id+"]').prop('selected', true);
            }
        }
    })
    });

I have 3 select in one page. so that based on that form index select id and name will change. In JSON result I am getting the appropriate value based on my index. but I don't know how to make it selected in the particular select option.

You can see a commented section in my JSON result, that is making the option value selected for all my 3 select inputs with select option value 2 (ie I mean all my select inputs are getting selected with Evening shift name). But my second commented line not working based on id and value.

Change the double quotes for single quotes.

$('select#shift_time<%=i.index%> option[value='+result[term].id+']').prop('selected', true);

With the double quotes, you defined a string... So you where looking for an option with a value of +value=result[term].id+ instead of value="2" .

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