简体   繁体   中英

HTML/JavaScript using JSP and JSTL - select dropdown only showing first option on iphone instead of selected option

I have a <select> element in my html:

<select id="mySelect">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

I am using JSP/JSTL for the back end, and when the page loads I want to dynamically select one of these options based on a page attribute I get from the back end. In other words, in JavaScript/jQuery:

$(document).ready(function() {
    $("#mySelect").find("option[val=${Var}]").prop("selected", true);
});

Ideally, when the page loads, the <select> element should show the option that is selected on screen (eg if ${Var} is 4, it should display 4 by default, and allow the user to use the drop down to select any of the other options. This works fine in my browser and on Android devices, but when testing it on my iPhone 5S, the <select> displays the first option instead of the option that is selected when the page loads (the option with a value of ${Var} ).

Any tips on how to ensure that it displays the correct selected value?

You can do it like this, when your page loads, it will execute this javascript:

var test = '<%= request.getAttribute("var") %>';

Here the var "test" will contain the attribute you set in your servlet called "var".

Then to make things easier, i am using jquery in this example, you can set your dropdown value to var. (but you must make sure that the dropdown select has a value with the variable var.) If var == 4 then it will set the dropdown select to value 4 on load.

 $("#mySelect").val(test);

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