Calling Javascript from jsp onchange of a dropdown value - javascript

I have a list of group and in each group I have a list of members. In jsp each group is shown in a row of table and each row contains a dropdown of members. Please see the image below -
What I am trying to do is - if I select a member from the dropdown then it's onchange trigger a javascript function and the user Id is shown in an alert.(for test purpose I'm now using alert, later I use the userId/member ID for other task).
In the first dropdown there are some members - razib, syeful, proshanto. If I select a member from the first dropdwon then the member id is shown properly in the alert. But if I select any member from the other dropdwon (displaying the member name bulbul and rony) then the javascript function is not triggered. Can any one help me what are the problems with the code -
The jsp snippet -
<select id="userSelect" name="user">
<c:forEach items="${group.users}" var="user" varStatus="status">
<option id="aUser" value="${user.id}"> <c:out value="${user.name}"/> </option>
</c:forEach>
</select>
And the javascript snippet is -
$(document).ready(function() {
$('#userSelect').change(function(event) {
var userId = $("select#userSelect").val();
alert("User ID :"+userId);
});//change()
}); //document.ready()
Thanks in advance
UPDATE: The answer given by San Krish and Carsten Løvbo Andersen works for a single single id of <select>. But I have multiple <select> with the id "userSeelct" because this is in a forEach loop. If I use class instead of ID then it is also not working.Please see How the <select> actually in my code-
<c:forEach id="groupId" var="group" items="${groupListForm.groups}" varStatus="status">
<select id="userSelect" name="user">
<c:forEach items="${group.users}" var="user" varStatus="status">
<option id="aUser" value="${user.id}"> <c:out value="${user.name}"/</option>
</c:forEach>
</select>
</c:forEach>
The earlier given answer is OK for a single <select>. But I think the problem is the <select> is also in a for each loop and there are multiple <select> with the same id/class. In this case how can I solve the problem? Thanks again.

You can simply do it as,
$(document).ready(function() {
$('#userSelect').on('change', function() {
alert( this.value ); // or $(this).val()
});
});

You can do something like this.
$("#userSelect").on("change", function() {
alert( this.value );
});
This should solve your problem!

Related

How to show a HTML table without using getelementbyid and same?

I'm having this problem.
I have a HTML code which will show a table. The problem is I cannot use any id, name or whatever can be identify by getElementByID and same. I also have a dropdownlist have 2 value "Yes" and "No". I want to write a JavaScript or jsp tag which will show the table when I choose the value "Yes", and make it disappear completely when I choose "No".
Note: I cannot write a script make the page to reload
So how should I write the code? I'm thinking about using javescript like
<script>
function onchangedropdownlist
if(dropdownlistvalue = 1)
{
</script>
Code html table
<script>
}
</script>
or maybe I can use c:if. But i'm not sure how to use c:if with onchange.
You can use document.getElementsByTagName("table")[0] to get the reference of your table and then use .style.display to block(show) or none(hide) your table.
Demo Code:
function onchangedropdownlist(dropdownlistvalue) {
//if value is yes
if (dropdownlistvalue == "yes") {
//show table
document.getElementsByTagName("table")[0].style.display = "block"
} else {
//hide table
document.getElementsByTagName("table")[0].style.display = "none"
}
}
<table>
<tr>
<td>
soemthing
</td>
</tr>
</table>
<select onchange="onchangedropdownlist(this.value)">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>

Can the value obtained by dijit.byId('').value be compared to a String?

I am relatively new to Spring MVC and Dojo/Dijit widgets and I am stuck with a problem. I need to unblock a particular div based on the option selected from the dropdown i.e. when the user selects the reason as "Unexperienced" I am supposed to unblock a div with id = "unexpUser" style="display:none;" to collect some additional information.
JSP -
<select data-dojo-type="dijit.form.Select" name="userReason" id = "reason">
<option value="opt0">Experienced</option>
<option value="opt1">Not experienced</option>
</select>
JC -
<script>
if(dijit.byId('reason').value == "opt1"){
unexpUser.style.display = 'block';
}
</script>
When the page loads, the option displayed on the dropdown is "Experienced". When I change the option to "Not experienced" , I need to unblock the div but this particular code doesn't seem to be the right code for comparing. Please help.
.value is not the right way to get value from a dijit widget instead use:
dijit.byId('reason').get("value")
Use onchange listener :
dijit.byId('reason').on("change",function(evt){
alert(evt); //(evt == value of option )
// your code here
});
okay I got my mistake. This is the solution. #Harpreet Singh your solution works perfectly with this code.
JSP-
<form:select data-dojo-type="dijit.form.Select" path "" name="userReason" id = "reason" onchange="myFunction1();">
<option value="opt0">Experienced</option>
<option value="opt1">Not experienced</option>
</form:select>
and in my JS I created a function for the String comparison.
JS -
<script>
function myFunction1(){
if(dijit.byId('reason').get("value") == "opt1"){
unexpUser.style.display = 'block';
}
</script>
this works. Thank you so much for your help!

Compare select dropdown value with another input and display matched one

HTML code:
<div class="controls" id="display">
<input type="text" name="demos" class="" value="1" id="displays"/>
<select class="input-medium">
<option value="">Select</option>
<option value="1">II</option>
<option value="2">AS</option>
<option value="3">AR</option>
</select>
</div>
Jquery code:
$("input[name='demos']").each(function(i,e){
var SValue = $('#displays').val();
$('option[value=' + SValue + ']').attr('selected',true);
});
I will be displaying the above html code as dynamic one for multiple times.
I will be comparing the value of #displays with the select options and make the select option as selected.
The value in #displays comes from database.
Since, am using multiple times the above html code when I pass the different values from database to that multiple code. All the multiple code shows only the first html code selected value.
However, I want all the multiple html code to show the selected value to their respective #displays.
In debug I found that $("input[name='demos']").each(function(i,e){ is not performing correctly because when i put console for Svalue it shows only the first html code input value for all the multiple html codes.
How can I fix this??
In HTML, the ID attribute is unique. You cannot use the same ID for more than one control in the same page. So, you'll need to use another approach.
I would do something like:
$("div.controls").each(function() {
$(this).children("select").eq(0).val($(this).children("input").eq(0).val());
});
EDIT: And it works, I've just made this demo!
Try this:
$("#displays").blur(function () {
var data = $(this).val();
$("#select > option").each(function () {
if (this.value == data)
$(this).attr("selected", "selected");
});
});
This example will get the input from user then the system will select the matching value.
Here is the fiddle: http://jsfiddle.net/t6kBY/
try
$("input#displays").each(function(i,e){
});

using a variable from drop down list

I'm attempting to create a dynamic drop down list, but after searching for hours I'm still completely stumped as to how to do it. So I am experimenting with variables in a list. This is the code I've started with.
<body>
<form method = "post">
<select id = "State" onchange = "a = this.options[selectedIndex].value;">
<option value = ""> Select a state</option>
<option value = "S3"> Pennsylvania</option>
<option value = "S4"> California</option>
<option value = "I4"> Texas</option>
<option value = "I5"> New York</option>
</select>
</form>
</body>
my question is what can I do with the variable 'a' so that I could create a dynamic drop down list based off it? One thing I had hoped to do was use an if-statement to display a second list. I wanted to remain on the same page too.
Note: I apologize if this seems like a basic question, but I've been scouring websites for answers and all I've figured out was that I can't send javascript variables to php, otherwise I'd have gotten this done forever ago
try this way
<select id="appamt" name="appamt">
<? while($amt=mysql_fetch_array($amount)){ ?>
<option value="<?=$amt['amount']?>"><?=$amt['amount']?></option>
<? } ?></select>
When your page detects the onchange event, what you need to do is either have all the combinations of options you want readily available but hidden on the page e.g. $('#sub-option1).hide(); and when the value is selected use $('#sub-option1).show();
Secondly you can have a ajax request that returns a JSON value of key=>value pairs, then use these key value pairs to dynamically build another dropdown using jquery .each() function.
Loop through your json values and add them to a previously hidden selector and then display it.
Hope this helps but if not email me and I will skype you through it.
Jim C

When an option tag is selected, how do you navigate to another page and then run a jQuery function automatically?

I am creating a way-finding app using HTML5, jQuery and Javascript. There are 3 total html pages and each page has a different legend. In this app I have buttons that call a jQuery click function to display stars on the map above the location you have selected. Each button has an id and the buttons work how I want them to work. The problem is that I want to add a drop down list that will provide the same functionality as the buttons on the legend. So basically what I want to be able to do is select a section from the drop down list and then jump to the page that has that section and have the stars already displayed for the selected section. IE: If I select Restrooms, I want to be able to jump the ground floor and have stars displayed over the restrooms. Is this possible to do? I tried using a Javascript function to make the URL navigate to the value of the select list option I wanted but that didn't make the stars show up. I am fairly new to Javascript and jQuery so please help. Thanks! Here is my code:
HTML:
<form method="get" name="form1" action="">
<select name="locations" onchange="gotoSection(this.form)">
<option selected>Please pick a Section</option>
<option disabled>---Ground Floor---</option>
<option value="grdFloor.html#mc" >Mayor's Commision on Literacy</option>
<option value="grdFloor.html#ch">Children's</option>
<option value="grdFloor.html#sr">Story Book Room</option>
<option value="grdFloor.html#eo">Extensions Office</option>
<option value="grdFloor.html#ma">Montgomery Auditorium</option>
<option value="grdFloor.html#restRm">Restrooms</option>
</select>
</form>
<div id="restRm" class="legend">
<a href="#restRm" ><img src="floorMaps/restBTN.png"/></a>
</div>
jQuery:
$(document).ready(function(){
$('.legend, .arrows').show('slow');
$('.stars').hide();
$('#restRm').click(function(){
$('.stars:not(#restStar1, #restStar2)').fadeOut('slow');
$('#restStar1, #restStar2').toggle('pulsate');
}); //end restroom
Javascript:
function gotoSection(form) {
var newIndex = form.locations.selectedIndex;
if ( newIndex == 0 ) {
alert( "Please select a Section!" );
} else {
cururl = form.locations.options[ newIndex ].value;
window.location.assign( 'http://libwww3.freelibrary.org/maps/central/' + cururl );
}
}
Try this:
<select name="locations" onchange="gotoSection(this.value)">
function gotoSection(cururl) {
window.location.assign( 'http://libwww3.freelibrary.org/maps/central/' + cururl );
}
EDIT:
Maybe i should read the entire question before i answer, i thought the problem was that your navigation didn't work, i apologize.
But as to the question about the stars, if i understand your question and example code correctly, you're navigating within the same page, just with diferent #hash tags. And if thats the case, your document.ready won't run.
Instead you can make a function that triggers the stars and call that from your gotoSection method, after you've assigned the new url.

Categories

Resources