简体   繁体   English

将JQuery SelectBox的值设置为来自模型的变量

[英]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. 我有一个jquery selectbox,可用于为用户提供用于过滤页面的选项。 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. 问题是我似乎无法将selectbox值设置为先前选择的值。

The HTML for the selectbox looks like this: 选择框的HTML如下所示:

<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: 他们选择的值保存在我的模型中,因此在jspx页面的顶部有以下内容:

<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. 我尝试了多种方法将其设置为“ myFilterValue”,但似乎无法对其进行设置。

--- 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 jsFiddle演示作品

I found following: https://github.com/marcj/jquery-selectBox/blob/master/readme.md 我发现以下内容: https : //github.com/marcj/jquery-selectBox/blob/master/readme.md

Code: 码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM