简体   繁体   English

选择动态选择的选项:使用JSP + Jquery

[英]Select option selected dynamically: Using JSP + Jquery

I have a Page with 4 links and each links looks like below. 我有一个包含4个链接的页面,每个链接如下所示。

 <a href="contact.jsp?subject=one">Link1</a>
 <a href="contact.jsp?subject=two">Link2</a>
 <a href="contact.jsp?subject=three">Link3</a>
 <a href="contact.jsp?subject=Four">Link4</a>

The contact.jsp is just a form which has a text box and a with 4 options. contact.jsp只是具有文本框和带有4个选项的表单。 Whenever the user clicks on the links above it should take to the contact form with the actual subject option selected in line with the query parameter(subject) passed in the HREF link. 每当用户单击上方的链接时,都应进入联系表,并根据HREF链接中传递的查询参数(主题)选择实际的主题选项。

Is it possible to do in Jquery? 可以在Jquery中做吗?

A selected option is identified by presence of selected attribute in the HTML <option> element. 通过在HTML <option>元素中存在selected属性来标识所选选项。

Just let JSP generate the desired HTML accordingly. 只需让JSP相应地生成所需的HTML。

<select name="subject">
    <option value="one" ${param.subject == 'one' ? 'selected' : ''}>one</option>
    <option value="two" ${param.subject == 'two' ? 'selected' : ''}>two</option>
    <option value="three" ${param.subject == 'three' ? 'selected' : ''}>three</option>
    <option value="four" ${param.subject == 'four' ? 'selected' : ''}>four</option>
</select>

No need for weird JS/jQuery workarounds. 不需要怪异的JS / jQuery解决方法。 They're meant for progressive enhancement anyway. 无论如何,它们都是为了逐步增强。 In other words, your webapp should be designed/developed in such way that it retains the core functionality even with JS disabled. 换句话说,您的webapp的设计/开发方式即使在禁用JS的情况下也应保留其核心功能。

As long as you have the subject listed in the URL you can get it with something like this: 只要您在URL中列出了主题,就可以通过以下方式获取它:

$(document).ready(function(){
    function getURLParameter(name) {
        return decodeURI(
            (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
        );
    }
    $('#mySelect').val(getURLParameter('subject'));
});

Then just make sure the value of the select box options corespond to the possibilities "one, two, three" and "four". 然后,只需确保选择框选项的值对应于可能性“一,二,三”和“四”即可。

In response to your comment below, if you'd like to then check the value and potentially show a file upload input, the code might look something like this: 为了回应您在下面的评论,如果您想检查该值并可能显示文件上传输入,则代码可能如下所示:

$(document).ready(function(){
    function getURLParameter(name) {
        return decodeURI(
            (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
        );
    }
    $('#mySelect').val(getURLParameter('subject'));
    if($('#mySelect').val() == 'three'){
        $('#myFileUpload').show();
    }
});

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

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