0

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!

L84
  • 45,514
  • 58
  • 177
  • 257
JustSimplyQ
  • 1
  • 1
  • 2
  • what about holding that `myFilterValue` in a hidden field and retrieve that using jquery.? – Rajaprabhu Aravindasamy Dec 04 '13 at 18:50
  • possible duplicate of [Change the selected value of a drop-down list with jQuery](http://stackoverflow.com/questions/499405/change-the-selected-value-of-a-drop-down-list-with-jquery) – Felix Kling Dec 04 '13 at 18:58
  • @RajaprabhuAravindasamy I'm still kind of new to some of this so how would I hold that myFilterValue in a hidden field and retrieve that using jquery? – JustSimplyQ Dec 04 '13 at 19:16

2 Answers2

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

jsFiddle Demo works

DevlshOne
  • 8,357
  • 1
  • 29
  • 37
  • I just tried both of those and it didn't work. The value in the dropdown is still 'All'. I've even modified the label to display myFilterValue to make sure it's got the right value and it does. – JustSimplyQ Dec 04 '13 at 19:08
  • Have you tried typing either of them in the console while on the page with this dropdown? – DevlshOne Dec 04 '13 at 19:18
0

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

Code:

 $('select').selectBox('value', 1);
ping
  • 663
  • 6
  • 13