user1020713
user1020713

Reputation: 45

Select option selected dynamically: Using JSP + Jquery

I have a Page with 4 links and each links looks like below.

 <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. 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.

Is it possible to do in Jquery?

Upvotes: 0

Views: 1915

Answers (2)

Chris Sobolewski
Chris Sobolewski

Reputation: 12945

As long as you have the subject listed in the URL you can get it with something like this:

$(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();
    }
});

Upvotes: 0

BalusC
BalusC

Reputation: 1108802

A selected option is identified by presence of selected attribute in the HTML <option> element.

Just let JSP generate the desired HTML accordingly.

<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. 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.

Upvotes: 1

Related Questions