JavaScript onclick event in a jsp - javascript

I am trying to select values on Jsp dynamically from Jsp in a dropdown list based on slection of another dropdown.
For example:I have two drop down1-A,B and drop down2 has values 1 to 10.
So when I select A i want 5 values from dropdown to be selected dynamically based on onclick event.Is it possible??

First, this has nothing to do with JSP. It's client side interaction and you need to use JavaScript to manage this.
If you have dropdown using <select> you need to capture change event for the first dropdown - triggered everythime when the value of the dropdown changes.
To make the code easier to read and avoid cross browsers issues, you may use jQuery to take care of this situation.
Hence, if you have a <select> element with ID set to say dropdown1 you can try this:
jQuery("#dropdown1").change(function () {
var selectedValue = jQuery(this).val();
// Now use to value to do other stufffs
});
However, if you are having a 'dropdown' for the second one it's not possible to select multiple values. One basic option is to convert this dropdown into a list and enable multiple slection using multiple="multiple" (Ref: http://www.w3schools.com/tags/att_select_multiple.asp)
That is, you just need to use <select multiple="multiple">
Now, I am not aware of your requirement and logic to pick up which particular values of the second dropdown for each item of the first dropdown. But, it seems you need to apply your own logic here.
However, let's consider that for value A' of dropdown1 the selected values in dropdown2 will be '1', '2' and '4'; for valueB' of dropdown1 the selected values in dropdown2 will be '2', '5' and '6','8' and '10' you can use code like this:
jQuery( document ).ready( function () {
jQuery("#dropdown1").change(function () {
var selectedValue = jQuery(this).val(),
mappedValues = {
"A": {"1": true, "2": true, "4": true},
"B": {"2": true, "5": true, "6": true, "8": true, "10": true}
},
selectedMappedValues = mappedValues[selectedValue] || {},
dropdown2 = jQuery("#dropdown2"),
dropdown2Options = dropdown2.find('option'),
dropdown2Option;
dropdown2Options.prop('selected', false);
dropdown2Options.each(function () {
dropdown2Option = jQuery(this);
if (selectedMappedValues[dropdown2Option.val()]) {
dropdown2Option.prop('selected', true);
}
});
});
});
Live Example: http://jsfiddle.net/sudipto/uzmbko17/

try this.
this jsp code.
<select id="dropdown1" name="dropdown1" onchange="selectValue()">
<option value="a">A</option>
<option value="b">B</option>
</select>
<select id="dropdown2" name="dropdown2">
<option value="a1">1</option>
<option value="a2">2</option>
<option value="a3">3</option>
<option value="a4">4</option>
<option value="a5">5</option>
<option value="a6">6</option>
<option value="a7">7</option>
<option value="a8">8</option>
<option value="a9">9</option>
<option value="a10">10</option>
</select>
this is javascript function
function selectValue(){
if(document.getElementById("dropdown1").value == a){
document.getElementById("dropdown2").value = a5;
}
}
thats all.thanx.

Related

How to make 2nd drop down list auto select value based on 1st drop down value

I have two drop down list, one for Client and Location. I would like the location drop down to auto select a value based on the selected Client option.
This is the script i came up with but the value is not being displayed on the location drop down.
function defaultLocation () {
var client2 = document.getElementById('clientList2');
if (client2.value == "Arm") {
document.getElementById('locationList2').value == "Cambridge";
}
}
As of now, I want the value to be auto selected when the Client option is chosen with no need to click a button.
UPDATE:
I would still like the user to be able to choose something else from the location list if the default option is not wanted? How would i do that as of right now, once "Arm" is selected, i can't change the location option
To assign value, you have to use assignment operator (=) not ==:
document.getElementById('locationList2').value = "Cambridge";
once "Arm" is selected, i can't change the location option
But I am unable to raise the issue in the following:
function defaultLocation () {
var client2 = document.getElementById('clientList2');
if (client2.value == "Arm") {
document.getElementById('locationList2').value = "Cambridge";
}
}
<select id="clientList2" onchange="defaultLocation()">
<option value="c1">Client 1</option>
<option value="Arm">Arm</option>
</select>
<select id="locationList2">
<option value="l1">Location 1</option>
<option value="Cambridge">Cambridge</option>
</select>

How to Modify selected option text & Restore Back text after next option

I want to Modify text contents of dynamically generated drop down list using jQuery. Here is my example:
Drop Down Text look like below:
<select id="s1">
<option data-name="volvo" value="1">1:Volvo</option>
<option data-name="saab" value="2">2:Saab</option>
<option data-name="mercedes" value="3">3:Mercedes</option>
<option data-name="audi" value="4">4:Audi</option>
<option data-name="BMW" value="11">11:BMW</option>
</select>
jQuery:
var previous;
$('#s1').focus(function () {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {
//Modify the SelectedOption Display only Number Value
$('#s1').find(':selected').text($('#s1').find(':selected').val());
//Restore the Previous Option : Format 'Number Value : data-name'
alert($("#s1 option[value='"+previous+"']").val());
alert($("#s1 option[value='"+previous+"']").attr('data-name'));
$("#s1 option[value='"+previous+"']").text($("#s1 option[value='"+previous+"']").val() +' '+ $("#s1 option[value='"+previous+"']").attr('data-name'));
});
I also used following attributes :
value: stores number value of that car
data-name: stores the Name of that Car
This is what I want:
Whenever any user select any option, then the selected option text will be modified and removes that Name part: For example: selecting 1:Volvo become 1 only.However if user select another option then the previous option text will be restore back to previous format e.g: 1 becomes 1:Volvo again. That is why i used given attributes to restore format.
I have written a code that works fine if i used alert .But i want to do it without using alert and then it does not work.
Here is my code:
jsfiddle
please help.
You have set data-name and value attributes, so you can easily loop over the options and use those attributes to update the text:
$('#s1').change(function() {
$(this).find('option').each(function(){
$(this).text(
$(this).attr('value')+( $(this).is(':selected') ? '' : ':'+$(this).attr('data-name'))
);
});
});
$('#s1').change(function() {
$(this).find('option').each(function(){
$(this).text(
$(this).attr('value')+( $(this).is(':selected') ? '' : ':'+$(this).attr('data-name'))
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
<option data-name="volvo" value="1">1:Volvo</option>
<option data-name="saab" value="2">2:Saab</option>
<option data-name="mercedes" value="3">3:Mercedes</option>
<option data-name="audi" value="4">4:Audi</option>
<option data-name="BMW" value="11">11:BMW</option>
</select>
EDIT (comment)
I'd say that with a normal usage, the code above will have no impact on user experience. It will be slower in a mathematics(?) meaning - negligible differences in execution time, as DOM is modified (each <option> is updated) inside $.each() loop, which isn't the best idea. But nothing that usar can notice.
For the OP example, where only 5 options are involved, it's arguable that updating all of them VS updating only 2, won't make any difference in speed. If there would be hundrets of options, then (speaking about user experience) I, as a user, wouldn't be so glad having so many options to pass through, searching the one I need. So the main issue would be there.
But, if there are any concerns about the above script speed, there's another (a better?) way, without using global flags and loops.
It creates a temporary data-last attribute for identifying previously selected <option> and only two options are modified at a time :
$('#s1').change(function() {
$(this).find('option:selected').attr('data-last','Yes').text(this.value)
.siblings('[data-last]').removeAttr('data-last').text(function(){
return this.value+':'+$(this).attr('data-name');
});
});
$('#s1').change(function() {
$(this).find('option:selected').attr('data-last','Yes').text(this.value)
.siblings('[data-last]').removeAttr('data-last').text(function(){
return this.value+':'+$(this).attr('data-name');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
<option data-name="volvo" value="1">1:Volvo</option>
<option data-name="saab" value="2">2:Saab</option>
<option data-name="mercedes" value="3">3:Mercedes</option>
<option data-name="audi" value="4">4:Audi</option>
<option data-name="BMW" value="11">11:BMW</option>
</select>
And there's a speed comparison between these two methods (200 options) :
JSFiddle

selectmenuchange appending object list only on first event

I have two selectmenus, one of which $('#parent') relates to certain options in the $('#members') menu (related through a data attribute in their HTML). I have a function to limit the choices in 'members' where they relate to the choice selected in the parent menu.
SCRIPT
$("#parent").selectmenu();
$("#members").selectmenu();
var allMembers = $('#members option'); // keep object list of all of the options for the select menu
$("#parent").on("selectmenuchange", function() {
var someMembers = [];
var id = $('#parent option:selected').data('id');
allMembers.each(function() {
if ($(this).data('parent-id') == id) {
someMembers.push($(this))
}
});
$('#members').empty().append(someMembers);
});
At the moment, this works, but only on the first selectmenuchange event - which is odd because using console.log() when the arrays are recreated in the function I can see that the correct have been selected each time, they just don't show in the menu on subsequent changes.
I can't figure out if this is a problem with selectmenuchange or empty().append()
HTML
<select name="members" id="members">
<option data-id="101" data-parent-id="1">Name1</option>
<option data-id="102" data-parent-id="1">Name2</option>
<option data-id="103" data-parent-id="1">Name3</option>
<option data-id="104" data-parent-id="2">Name4</option>
<option data-id="105" data-parent-id="2">Name5</option>
<option data-id="106" data-parent-id="3">Name6</option>
<option data-id="107" data-parent-id="3">Name7</option>
</select>
<select name="parent" id="parent">
<option data-id="1">Parent1</option>
<option data-id="2">Parent2</option>
<option data-id="3">Parent3</option>
</select>
Well the options were changing but it wasn't reflecting in the selectmenu created by plugin. So one of the way is you destroy it and re-initialize the selectmenu as below:
$('#members').html(someMembers).selectmenu('destroy').selectmenu();
DEMO
Instead of selectmenu('destroy') and re-initializing the select menu you can also use selectmenu('refresh'). Refreshing sounds nicer than destroying it each time.
I have updated the fiddle of Guruprasad Rao with the refresh:
fiddle

How to target a select option based on data attribute?

I'm new to JavaScript and jQuery. I'm trying to create something for a website I'm working on, but I can't figure this out.
How can I get jquery to show or hide a select option of a dropdown, based on the selected data attribute of another dropdown?
IE, selecting option 2 in the first dropdown will show only options 1 and 3 in the second menu, and vice versa?
$(document).ready(function() {
$("#make_id").change(function() {
/* basically if data-make is = to selected data-id option, show option,
if it isn't, hide this option. seems, simple, but I can't figure it out... */
})
})
<select id="make_id" >
<option value="make option 1" data-id="18">option 1</option>
<option value="make option 2" data-id="42">option 1</option>
</select>
<select id="model_id" >
<option value="model option 1" data-make="42">option 1</option>
<option value="model option 2" data-make="18">option 2</option>
<option value="model option 3" data-make="42">option 3</option>
</select>
$("#make-id").change(function(e){
var currentMake = $("#make-id").data("id");
$("#model-id option").not("[data-make='"+currentMake+"']").hide();
$("#model-id option").filter("[data-make='"+currentMake+"']").show();
}
In English:
Whenever make-id changes, get the data-id field from it.
Select all the options under model-id then filter for ones that don't have the same data-make value. Hide those.
Select all the options under model-id then filter for the ones that do have the same data-make value. Show those.
TL;DR
I've changed the way your code works a little to make it work better for the way you want it to. Take a look at this fiddle.
So first of all, you can easily define a callback on the change event which can filter the second select box's option visibility. One problem you may come into if you do this is that "hidden" options will still be in the select's value if they were previously selected (as in Franz's answer).
Here's a slightly different approach in which everything is emptied and loaded dynamically from a JSON object that you define initially:
1. Define your JSON object (data model)
This could come from a database as well of course.
var makesAndModels = {
"makes": [
{"option_id": 1, "id": 18, "name": "make 1"},
{"option_id": 2, "id": 42, "name": "make 2"}
],
"models": [
{"option_id": 1, "make_id": 42, "name": "make 2: model 1"},
{"option_id": 2, "make_id": 18, "name": "make 1: model 1"},
{"option_id": 3, "make_id": 42, "name": "make 2: model 2"}
]
};
2. Define methods to populate each select
Your rules are simple:
To populate the makes, you need no conditions
To populate the models, you need a make ID (foreign key)
function populateMakes() {
var $make = $('#make_id');
// Remove all options before starting
$make.empty();
// Loop the makes from the JSON data object
$.each(makesAndModels.makes, function(key, make) {
// Append new options for each make
$('#make_id')
.append(
$('<option></option>')
.data('id', make.id) // Assign the data-id attribute
.attr('value', 'make option ' + make.option_id) // Give it a value
.text(make.name) // Give it a label
);
});
}
The function above is simply emptying the #make_id select box, then looping the makes in the JSON data object and appending a new option element to the makes select for each result, setting the attributes as it goes.
Then to populate the models, we do the same thing for models as we did for makes, except we'll ignore any models that are for a different make.
function populateModels(makeId) {
// Assign the selector to a variable to repeated use/Don't Repeat Yourself
var $model = $('#model_id');
// Remove all models in the select to start
$model.empty();
// Loop the models in the JSON object
$.each(makesAndModels.models, function(key, model) {
// Ignore any models for other makes
if (model.make_id != makeId) {
return;
}
// Append the new model to the select
$model
.append(
$('<option></option>')
.data('make', model.make_id) // Assign its data-make attribute
.attr('value', 'model option ' + model.option_id) // Give it a value
.text(model.name) // Give it a label
);
});
}
3. Simplified HTML
Once you've got that framework, your HTML and event handlers are going to be very simple.
The HTML select boxes don't need any options since they're populated dynamically, although you may want to leave the ones you have there already in place to help with older browsers or browsers with Javascript turned off (cringe):
<!-- These are populated dynamically now! -->
<select id="make_id"></select>
<select id="model_id"></select>
4. Create your jQuery event handler
...and glue it all together:
$(document).ready(function() {
// Populate the makes select box
populateMakes();
// Define what should happen when you change the make_id select
$("#make_id").change(function() {
// Find the currently selected make's ID from data-id
var selectedMake = $(this).find('option:selected').data('id');
populateModels(selectedMake);
});
// Trigger a change to populate the models the first time
$('#make_id').change();
});
The trick above is that once you've populated the makes and defined your event handler for when the makes select box changes, you can to trigger the change event manually - this will cause populateModels() to be called with the first make in the list, and have the models for that make populated too.
$(document).ready(function() {
$("#make_id").change(function() {
if ($(this).val()=='make option 2') $("#model_id").find("option").eq(1).hide();
else $("#model_id").find("option").eq(1).show();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="make_id" >
<option value="make option 1" data-id="18">option 1</option>
<option value="make option 2" data-id="42">option 2</option>
</select>
<select id="model_id" >
<option value="model option 1" data-make="42">option 1</option>
<option value="model option 2" data-make="18">option 2</option>
<option value="model option 3" data-make="42">option 3</option>
</select>

recreate an array based on options selected

I need help solving a simple requirement.
<select id="my-select1">
<option value="1">This is option 1 ({myop1}|OP)</option>
<option value="2" selected>This is option 2 ({myop1}|OQ)</option>
<option value="3">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="1">This is option 1 ({myop2}|PP)</option>
<option value="2">This is option 2 ({myop2}|PQ)</option>
<option value="3" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="1">This is option 1 ({myop3}|QP)</option>
<option value="2">This is option 2 ({myop3}|QQ)</option>
<option value="3" selected>This is option 3 ({myop3}|QR)</option>
</select>
See the HTML above, I want to recreate my array:
combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
INTO
combo = ["abc-OQ-PR", "def-PR"];
based on the selected options.
Another thing to note is that I cannot simply change the value of the options of the select box, meaning to say the HTML is somewhat as it is, if it would help, the only part i can restructure on that HTML is the text content between <option></option>
I'm not sure, but I'm already spending a couple of hrs just to solve this problem. Maybe due to my limited jQuery knowledge.
Please help. thanks
Get the selected values into an associative array:
var pattern = {};
var s = $('select option:selected').each(function(){
var m = /\((.*?)\|(.*)\)/.exec($(this).text());
pattern[m[1]] = m[2];
});
Then you can replace each place holder in each string in the array with the corresponding value:
combo = $.map(combo, function(e){
return e.replace(/\{.*?\}/g, function(m){
return pattern[m];
});
});
Demo: jsfiddle.net/C97ma/
Based on the information you provided I'm don't get it 100% I guess. But whatever you're trying to do, I guess jQuerys .map() and $.map() would help you here.
Like
var arr = $('select').find('option:selected').map(function(index, elem) {
return elem.textContent || elem.text;
}).get();
Demo: http://www.jsfiddle.net/4yUqL/78/
Within the callback you can modify/match the text in any way you want/need. In your case I could imagine you want to use a regular expression to match the selected strings and recreate those somehow.
I figure you're using javascript for combining those (it can be done with PHP also)..
You need references to your selects, e.g. :
<script type="text/javascript">
a=document.getElementById("myselect").options[1];
</script>
This will assign the 2nd option value from the 'myselect' select element to the variable 'a'
To begin with I would change the values in the select box like this:
<select id="my-select1">
<option value="OP">This is option 1 ({myop1}|OP)</option>
<option value="OQ" selected>This is option 2 ({myop1}|OQ)</option>
<option value="OR">This is option 3 ({myop1}|OR)</option>
</select>
<select id="my-select2">
<option value="PP">This is option 1 ({myop2}|PP)</option>
<option value="PQ">This is option 2 ({myop2}|PQ)</option>
<option value="PR" selected>This is option 3 ({myop2}|PR)</option>
</select>
<select id="my-select3">
<option value="QP">This is option 1 ({myop3}|QP)</option>
<option value="QQ">This is option 2 ({myop3}|QQ)</option>
<option value="QR" selected>This is option 3 ({myop3}|QR)</option>
</select>
Now to update your array:
var comboDef = ["abc-{myop1}-{myop2}", "def-{myop2}"];
var combo = ["abc-{myop1}-{myop2}", "def-{myop2}"];
function updateArray() {
combo = comboDef;
for (i in combo)
{
combo[i] = combo[i].replace("{myop1}",document.getElementById("my-select1").value);
combo[i] = combo[i].replace("{myop2}",document.getElementById("my-select2").value);
combo[i] = combo[i].replace("{myop3}",document.getElementById("my-select3").value);
}
}
Of course, this could be done better with proper arrays (if you gave your select boxes the same name you could iterate through them using document.getElementsByName()). The basic idea is the replace though which I trust is what you're looking for.

Categories