Archive for category JQuery

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

Leave a comment