JQuery


Problem: How to use jquery to set the values of selected dropdown  and selected checkboxes inside html/jsp

Solution:

Inside your jsp, add script tag and define functions that will called during the events from dropdown(onchange) and onclick for checkboxes

<script>
var drpdown;
var myArray;

function selectDropdown() {
drpdown = $(“#select-dropdown”).val();

alert(drpdown);

}

function showCheckbox(){
//get checkboxes
myArray = new Array(2);
if ($(‘#n-width:checked’).val() !== undefined)
{
myArray[0] = $(‘#cb1’).text();
alert(myArray[0]);
}
if ($(‘#n-height:checked’).val() !== undefined)
{
myArray[1] = $(‘#cb2’).text();
alert(myArray[1]);
}

}

</script>

once the above script is added in head, define body and a table inside to create dropdown and checkbox elements

<body>

<table>

<tr>
<td>
Select From Dropdown:
</td>
<td>
<select id=”select-dropdown” onchange=”selectDropdown();”>
<option selected=”selected”></option>
<option >OPTION1</option>
<option >OPTION2</option>
</select>
</td>
</tr>
<tr>
<td>
<label for=”r-left” id=”cb1″>CHECKBOX1</label>
</td>
<td>
<input type=”checkbox” id=”n-width”  onclick=”showCheckbox();”/>
</td>
</tr>
<tr>
<td>
<label for=”r-left” id=”cb2″>CHECKBOX2</label>
</td>
<td>
<input type=”checkbox” id=”n-height” onclick=”showCheckbox();”/>
</td>
</tr>

</table>

</body>

Upon changing the dropdown, selectDropdown will be called and we are using jquery inside selectDropdown to get the value of teh dropdown. Similarly for checkboxes, showCheckbox will be called and using jquery, i am getting the values for selected checkboxes

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: