I have two onchange methods and two values I need to pass - javascript

function changeHiddenInput(cLeague, nLeague) {
console.log(cLeague);
console.log(nLeague);
var objHidden1 = document.getElementById("hiddenInput1");
var objHidden2 = document.getElementById("hiddenInput2");
objHidden1.value = cLeague.value;
objHidden2.value = nLeague.value;
var a = objHidden1.value;
var b = objHidden1.value;
result.innerHTML = a + b;
}
<select class="form-control" id="currentleague" onchange="document.getElementById('currentleague').src=this.value; changeHiddenInput(select)">
<option value="rankicons/bronze5.png" (another value goes somewhere in here)>Bronze V</option>
</select>
Basically the first onchange changes the image in value, the second onchange passes in a value and does some math. Is there an alternative I could use to value or could I somehow pass in two values and somehow tell them apart?

You can have 2 values within the value property:
<option value="rankicons/bronze5.png,value nr 2">...</option>
Sample:
function changeHiddenInput(league) {
var league_values = league.split(",");
var objHidden1 = document.getElementById("hiddenInput1");
var objHidden2 = document.getElementById("hiddenInput2");
objHidden1.value = league_values[0];
objHidden2.value = league_values[1];
var a = objHidden1.value;
var b = objHidden1.value;
result.innerHTML = a + b;
// remove comment and set uniqe id to set img element src
//document.getElementById('img_id').src=league_values[0];
}
HTML:
<select class="form-control" id="currentleague" onchange="changeHiddenInput(this.options[this.selectedIndex].value)">
<option value="rankicons/bronze5.png,value nr 2">...</option>
</select>
The value document.getElementById('currentleague').src=this.value; I removed as it referenced the select element itself (same id) and added it to your function instead.

Related

Javascript iteration with thymeleaf, how to pass index to array in thymeleaf

I'm setting 2 select in html, the second one depends of the first one, so I use a script "onchange", so when the first value of the select change, the second one change too, I don't know how to get the variable of my FOR to get the index of the thymeleaf model in my script
SCRIPT-
So my problem here it's inside the if when I tried to get the value of documentos[i].proyecto.id, but I can get documentos[0, 1 or any number].proyecto.id
/*<![CDATA[*/
function load(){
var e = document.getElementById("proyecto-id");
var value = e.options[e.selectedIndex].value;
var sub = document.getElementById("documento-id");
var length = sub.options.length;
for (z = 0; z < length; z++) {
sub.options[z] = null;
}
for(i=0;i<[[${#lists.size(documentos)}]];i++){
if([[${documentos[ i ].proyecto.id}]] == value){
var opt = document.createElement('option');
opt.value = [[${documentos[ i ].id}]]
opt.text = [[${documentos[ i ].nombre}]];
sub.add(opt);
}
}
}
/*]]>*/
HTML select
<select id="proyecto-id" class="custom-select" th:onchange="load()">
<option th:each="p : ${proyectos}"
th:text="${p.nombre}"
th:value="${p.id}">
</option>
</select>
<select id="documento-id" class="custom-select">
</select>

Unable to fectch dataset numerical value

<select class="license_type" name="license_type" id="license_type">
<option value="l_one" data-one="500">License 1</option>
<option value="l_two" data-two="700">License 2</option>
<option value="l_three" data-three="1400">License 3</option>
</select>
These 500, 700, 1400 will later come programmatically through PHP. So my goal is to fetch them in JS through the dataset.
The JS function that I wrote is:
function someFunction() {
var vOne= document.getElementById("license_type");
var vTow = vOne.options;
var c1 = vTow.dataset.one;
var c2 = vTow.dataset.two;
var c3 = vTow.dataset.three;
}
then in another JS instead of the hard coded prices like this :
var prices = [500, 700, 1400];
and this:
var prices = ['c1', 'c2', 'c3'];
But this generates NAN that means c1, c2, c3 doesn't have numerical values.
whats the Fix?
Looking at your code it seems that it has three static options, so considering that below code will work.
function someFunction() {
var license_type= document.getElementById("license_type");
var c1 = license_type.options[0].getAttribute('data-one');
var c2 = license_type.options[1].getAttribute('data-two');
var c3 = license_type.options[2].getAttribute('data-three');
var prices = [c1, c2, c3];
console.log(prices)
}
But if the options are dynamic than you'll have to loop through the options.
You should use getAttribute and parseInt. Also loop through the options, and use destructuring like so:
function someFunction() {
var vOne = document.getElementById("license_type");
var options = vOne.getElementsByTagName("option");
var [c1, c2, c3] = options.map(e => e.getAttribute("data-one"));
}
First, I will use querySelectorAll() to get all options of the target select. Then, I will use Array::map() to map all options to his data-* attribute. Note I have to get the second part of the name of data-* attribute from the value attribute, because the data-* attribute appears to be related to the value attribute (is not an uniform name):
var prices;
function someFunction()
{
var opts = document.querySelectorAll("#license_type option");
prices = Object.values(opts).map(o =>
{
let token = o.getAttribute("value").match(/l_(\w+)/)[1];
return o.getAttribute("data-" + token);
});
console.log(prices);
}
someFunction();
<select class="license_type" name="license_type" id="license_type">
<option value="l_one" data-one="500">License 1</option>
<option value="l_two" data-two="700">License 2</option>
<option value="l_three" data-three="1400">License 3</option>
</select>

Unable to populate dropdowns dynamically using angularJs

I have 3 dropdowns, A, B, C.
Based on dropdown A selection, dropdown B will be filled.
Then based on dropdown B selection, dropdown C will be filled.
I am able to achieve first 2 steps. But I am unable to achieve third point.
jsfiddle link
What about
<div data-ng-app data-ng-controller="myCtrl">
<select data-ng-model="option1" data-ng-options="option for option in options1 " data-ng-change="getOptions2($index)">
</select>
<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
</select>
<select data-ng-model="option3" data-ng-options="option for option in options3" data-ng-show='options3.length'>
</select>
</div>
function myCtrl($scope) {
$scope.options1 = option1Options;
$scope.options2 = []; // we'll get these later
$scope.options3 = [];
$scope.getOptions2 = function() {
$scope.options2 = option2Options[option1Options.indexOf($scope.option1)];
$scope.getOptions3();
};
$scope.getOptions3 = function() {
var mergedOptions2=[].concat.apply([], option2Options )
$scope.options3 = option3Options[mergedOptions2.indexOf($scope.option2)];
}
}
Working fiddle
You are unable to achieve third point because you are trying to do that when dropdown A has a value, not B. If you add a new trigger on B, with the same functionality related to B, it will work.
Step 1: Add change trigger to your dropdown:
<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions3()">
Step2: Add a function on your controller to update options for dropdown C:
$scope.getOptions3 = function() {
var key2 = $scope.options2.indexOf($scope.option2);
var myNewNewOptions = option3Options[key2];
$scope.options3 = myNewNewOptions;
};
I've updated your fiddle accordingly: http://jsfiddle.net/Xku9z/1196/
You have forget to call getOption2() function for fetching option3
<select data-ng-model="option2" data-ng-options="option for option in options2" data-ng-show='options2.length' data-ng-change="getOptions2()">
</select>
Fiddler
http://jsfiddle.net/Xku9z/1198/
If I were you I would change your drop downs to call different functions. That way you aren't setting the third set of options before you need to.
Verified it works on JSFiddle.
Instead of..
function myCtrl($scope) {
$scope.options1 = option1Options;
$scope.options2 = []; // we'll get these later
$scope.options3 = [];
$scope.getOptions2 = function() {
var key = $scope.options1.indexOf($scope.option1);
var key2 = $scope.options2.indexOf($scope.option2);
var myNewOptions = option2Options[key];
var myNewNewOptions = option3Options[key2];
$scope.options2 = myNewOptions;
$scope.options3 = myNewNewOptions;
};
}
Use this...
function myCtrl($scope) {
$scope.options1 = option1Options;
$scope.options2 = []; // we'll get these later
$scope.options3 = [];
$scope.getOptions2 = function() {
var key = $scope.options1.indexOf($scope.option1);
var myNewOptions = option2Options[key];
$scope.options2 = myNewOptions;
};
$scope.getOptions3 = function() {
var key2 = $scope.options2.indexOf($scope.option2);
var myNewNewOptions = option3Options[key2];
$scope.options3 = myNewNewOptions;
};
}
And make sure you call data-ng-change="getOptions3()" on your second select tag.

How to get value of 2 dropdown list who's value coming from javascript function

I have 2 dropdownlist in jsp as 'speciality' and 'super_speciality'[clicking on speciality related superspeciality populates] and their values coming from javascript file 'specialities.js', how to get values of these 2 dropdownlist in Servlet or JSP ???
my
// specialities.js file
// speciaities
var spl_arr = new Array("Dentist","Gynecologist/obstetrician","Dermatologist/cosmetologist",
"Pediatrician","General Physician","Ayurveda","Cardiologist",
"Orthopedist","Ear-nose-throat (ent)","Homeopath");
// Super Specialities
var SupSpl_arr = new Array();
SupSpl_arr[0]="";
SupSpl_arr[1]="General Dentists|Oral Pathologists|Periodontists|Orthodontists|Cosmetic Dentists|";
SupSpl_arr[2]="Maternal-fetal medicine|Family planning|Reproductive endocrinology and infertility|Female pelvic medicine and reconstructive surgery|Menopausal and geriatric |";
SupSpl_arr[3]="Cosmecaregiver|Desairologist|Hair colorist|Esthecaregiver|";
SupSpl_arr[4]="Fictional pediatricians‎|Neonatologists‎|Pediatric ophthalmologists‎|Pediatric organizations|Women pediatricians|";
SupSpl_arr[5]="Auto-isopathy|Classical homeopathy|Clinical homeopathy|Homotoxicology|Pluralistic homeopathy|";
SupSpl_arr[6]="Multiple Sclerosis (MS)|Parkinson’s disease (PD)|Ankylosing Spondylities (AS)|Rheumatoid arthritis (RA)|Paralysis|";
SupSpl_arr[7]="Cardiac electrophysiology|Echocardiography|Interventional cardiolog|Nuclear cardiology|Pediatric cardiology|";
SupSpl_arr[8]="Hand and Plastic Surgery|Pediatric Orthopaedics|Back and spine conditions|Trauma|";
SupSpl_arr[9]="OTOLOGY-NEUROTOLOGY (EAR)|RHINOLOGY (NOSE)|LARYNGOLOGY (THROAT)|HEAD/NECK/THYROID|ALLERGY|GENERAL OTOLARYNGOLOGY|PEDIATRIC OTOLARYNGOLOGY (CHILDREN)|";
SupSpl_arr[10]="Allergy and Immunology|Anaesthesiology|Endocrinology|Gastroenterology|";
function populateSuperSpecialities( specialityElementId, superSpecialityElementId ){
var selectedSpecialityIndex = document.getElementById( specialityElementId ).selectedIndex;
var superSpecialityElement = document.getElementById( superSpecialityElementId );
superSpecialityElement.length=0; // Fixed by Julian Woods
superSpecialityElement.options[0] = new Option('Select Super Speciality','');
superSpecialityElement.selectedIndex = 0;
var super_arr = SupSpl_arr[selectedSpecialityIndex].split("|");
for (var i=0; i<super_arr.length; i++) {
superSpecialityElement.options[superSpecialityElement.length] = new Option(super_arr[i],super_arr[i]);
}
}
function populateSpecialities(specialityElementId, superSpecialityElementId){
// given the id of the <select> tag as function argument, it inserts <option> tags
var specialityElement = document.getElementById(specialityElementId);
specialityElement.length=0;
specialityElement.options[0] = new Option('Select Speciality','-1');
specialityElement.selectedIndex = 0;
for (var i=0; i<spl_arr.length; i++) {
specialityElement.options[specialityElement.length] = new Option(spl_arr[i],spl_arr[i]);
}
// Assigned all countries. Now assign event listener for the states.
if( superSpecialityElementId ){
specialityElement.onchange = function(){
populateSuperSpecialities( specialityElementId, superSpecialityElementId );
};
}
}
// inside my jsp
<script type= "text/javascript" src = "js/specialities.js"></script>
Select Speciality: <select id="speciality" name="speciality">
<script language="javascript">
populateSpecialities("speciality", "super_speciality");
</script>
</select>
Select Super-Speciality: <select id="super_speciality" name="super_speciality" style="width: 198px">
<script language="javascript">
populateSuperSpecialities("speciality", "super_speciality");
</script>
</select>
In Jsp and Servlet you can get the values of the elements using request object.
To get the value of any element use the method called getParameter of request object. Below code in servlet and jsp will give you the value.
String value = request.getParameter("super_speciality");
Similarly, You can get the value of other parameter as well.

I am still new with JS and can't see my mistake for this basic calculation script

I got the code from
Calculate one variable based on changing input
I have written the following based on my limited understanding
<td>
<select name='breadstick'>
<option value='0' selected >-- Choose Breadstick --</option>
<option value='4.06'>Breadstick</option>
<option value='3.8'>Melba Toast</option>
</select>
</td>
<td>
<input id="input_bread" type="text" name="input_bread" style="width:50px;" onkeyup="do_calc3(this.value);">
</td>
<td>
<input id="bread_results" class="" readonly name="bread_results" style="width:50px;" value="" />
<script>
function do_calc3() {
var bread_choice = document.getElementById('breadstick');
var bread_weight = document.getElementById('input_bread');
var bread_r = bread_choice * bread_weight;
document.getElementById("bread_results").value = bread_r;
}
</script>
</td>
First:
You need to use the .value property for getting the elements' values.
Change:
var bread_r = bread_choice * bread_weight;
to:
var bread_r = bread_choice.value * bread_weight.value;
In your original code, bread_choice and bread_weight are references to DOM elements. When you try to multiply them, that won't be a numerical result.
You are attempting to get their values (what's selected in the dropdown and what's typed in the textbox), so you should get them with .value.
It's similar to your next line, where you set the bread_results element's value with .value = bread_r.
Second:
Your <select> element doesn't have an id of "breadstick", it has a name. So change your element to be:
<select id='breadstick' name='breadstick'>
or change your retrieval of the element to be:
var bread_choice = document.querySelector('select[name="breadstick"]');
Third:
Since you are using the inline event handler for onkeyup, you are already passing this.value, which means the textbox's value. Therefore, you don't need to get the textbox and its value in the function. Just add a parameter and use it.
function do_calc3(bread_weight) {
var bread_choice = document.getElementById('breadstick').value;
var bread_r = bread_choice * bread_weight;
document.getElementById("bread_results").value = bread_r;
}
Fourth:
You shouldn't use inline event handlers. For many reasons, it's better to handle events in your Javascript code. Here's an example of how I'd set it up. (note that the onkeyup="do_calc3(this.value);" was removed and done in the Javascript's window.onload event)
function do_calc3() {
var bread_choice = document.getElementById('breadstick');
var bread_weight = this;
var bread_r = bread_choice.value * bread_weight.value;
if (isNaN(bread_r)) {
bread_r = "Invalid";
}
document.getElementById("bread_results").value = bread_r;
}
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
window.onload = function () {
var textbox = document.getElementById("input_bread");
addEvent(textbox, "keyup", do_calc3);
};
DEMO: http://jsfiddle.net/Gtven/4/
<select name='breadstick' id='breadstick'>
Above needs to be changed, as you don't have an id "breadstick" yet.
Below is a changed function in order to get the actual values of the elements and not just the elements.
function do_calc3() {
var bread_choice = document.getElementById('breadstick').value;
var bread_weight = document.getElementById('input_bread').value;
var bread_r = bread_choice * bread_weight;
document.getElementById("bread_results").value = bread_r;
}
And here I got you a working Fiddle: http://jsfiddle.net/TwqC6/
Use .value:
var bread_choice = document.getElementById('breadstick').value;
var bread_weight = document.getElementById('input_bread').value;

Categories

Resources