简体   繁体   中英

Setting the value of a JQuery SelectBox to the variable from a Model

I've got a jquery selectbox that I use to give users options for filtering a page. The default value is 'All' and then there are a series of options they can choose.

When they make their selection, the page gets reloaded with their selection and then I want the selectbox to display their selection. The problem is that I can't seem to get the selectbox value to set to the previously selected value.

The HTML for the selectbox looks like this:

<select id="mySelectMenu">
    <option value="VALUEALL">All</option>
    <option value="VALUE1">A</option>
    <option value="VALUE2">B</option>
    <option value="VALUE3">C</option>
</select>

The value they choose is saved in my model so I have the following at the top of my jspx page:

<c:set value="${myModel.myFilterCriteria}" var="myFilterValue" />

This is in my document.ready

$(function() {
    $( "#mySelectMenu" ).selectBox();
    // this is how I've tried to force my value to 'A' instead of 'All', but it 
    // didn't work.
    $("#mySelectMenu option[value='VALUE1']").prop("selected", true);

    // I'd like to be able to use something like this: 
    $("#mySelectMenu option[value='(myFilterValue)']").prop("selected", true);
});

I've tried various ways to get it set to 'myFilterValue', but can't seem to get it set.

--- FOUND THE RESOLUTION ---

The issue was the following in my function

$( "#mySelectMenu" ).selectBox();

I removed it and added the following and it worked.

$("#mySelectMenu option[value='${myFilterValue}']").prop("selected", true);

So, my function now looks like this:

$(function() {
    $("#mySelectMenu option[value='${myFilterValue}']").prop("selected", true);
});

Thank you all for your help!

$('#mySelectMenu').val(myFilterValue); // or
$('#mySelectMenu').val("VALUE1");

jsFiddle Demo works

I found following: https://github.com/marcj/jquery-selectBox/blob/master/readme.md

Code:

 $('select').selectBox('value', 1);

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