Do dependent dropdown in html using javascript with value and text - javascript

I have already a dependent dropdown list in my html form by using only javascript, but when my php script returns values these are just numbered by the position of the text in an array. I would like to have both Value and Text the same value
Here is what I have so far:
SCRIPT IN HEAD TAG:
var my_variable=[
["dropA_opt1","dropA_opt2",dropA_opt3"],
["dropB_opt1","dropB_opt2",dropB_opt3"],
["dropC_opt1","dropC_opt2",dropC_opt3"]
];
function variable(idx) {
var f=document.my_form;
f.drop_nr_2.length=null;
for(var i=0; i<my_variable[idx].length; i++) {
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], i);
}
}
SELECT for main DROPDOWN
<select name="drop_nr_1" onchange="my_variable(this.selectedIndex)">
<option value="" selected disabled></option>
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
SELECT for dependent DROPDOWN
<select name="drop_nr_2">
</select>
The code i have basically creates the options from the array index, but there is no value="" attribute. From that reason I am getting the array index back - but I need a value="same as the text".
In addition it would be nice to have always the first option in the 2nd dropdown selected and disabled with empty value (like in dropdown 1).
Much appreciate your help

When constructing <option> by using javascript object syntax.
var myOpt = new Option(lbl,val);
The first parameter is the label that user sees it having the second parameter is the value that will be used for this <option> internally.So just modify the constructor line a bit
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
For second requirement add a condition for i===0 when it's true pass additional third parameter (wiz. selected) and make disabled property true
for(var i=0; i<my_variable[idx].length; i++) {
if(i===0){
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i],"selected");
f.drop_nr_2.options[i].disabled= true;
} else{
f.drop_nr_2.options[i]=new Option(my_variable[idx][i], my_variable[idx][i]);
}
}

Related

Javascript Div onchange Grab Values from Two Select Boxes

I'm trying to make it so when a select box within a div changes, it will grab values from both that select box and one other one that I've yet to add, but I don't know how to go about it.
I currently have this code
<select id='selMag' onchange='getSelMag(this)'>
<option value='0.0>Select Minimum Magnitude</option>
<option value='1.0'>1.0</option>
<option value='2.0'>2.0</option>
<option value='3.0'>3.0</option>
<option value='4.0'>4.0</option>
<option value='5.0'>5.0</option>
<option value='6.0'>6.0</option>
<option value='7.0'>7.0</option>
<option value='8.0'>8.0</option>
<option value='9.0'>9.0</option>
<option value='10.0'>10.0</option>
</select>
function getSelMag(sel) {
value = Number(sel.value);
console.log(window.value);
}
This, as it is right now, works fine from grabbing it from the , but I would like to add another one and put them inside a container div, and make it so when either one changes it will grab the values from both of them, add both strings together, and convert them into a number. I plan to make it so the select box above will not have the decimal values and just be 1, 2, etc. and have the second box be .1, .2, etc. so when they are added together, it will show 1.1, 1.2, etc.
Presumably, the select is in a form. To be successful, form controls must have a name, so:
<select id='selMag' name='selMag' onchange='getSelMag(this)'>
Adding a name nearly always obviates the requirement for an ID. If the other select also has a name:
<select name='selMag2'>
and it belongs to the same form as the first, you can reference it from the getSelMag function via the form:
function getSelMag(sel) {
// Always declare variables
var value = Number(sel.value);
// Access them from the appropriate scope
console.log(value);
// Reference the other select using named properties of the form
var otherSelect = sel.form.selMag2;
// Do stuff with it
var otherValue = otherSelect.value;
}
Note that all form controls have a form property that references their parent form, and that the controls belonging to a form can be accessed via the form's elements collection.
Those with names (and in some browsers those with IDs) can be accessed as named properties of the form and of the elements collection, and also by index in the collection.
It seems that you want to concatenate the values with a period between, so the function might look like:
function getSelMag(sel) {
var value0 = sel.form.selMag.value;
var value1 = sel.form.selMag2.value;
console.log(value0 + '.' + value1);
}
and the HTML:
<form>
<select name="selMag" onchange="getSelMag(this);">
<option value="0" selected>0
<option value="1">1
<option value="2">2
</select>
<select name="selMag2" onchange="getSelMag(this);">
<option value="0" selected>0
<option value="1">1
<option value="2">2
</select>
</form>
Use the answer from this link to get the value of other select box in getSelMag() function
Get selected value in dropdown list using JavaScript?
as follows:
function getSelMag(sel) {
value = Number(sel.value);
console.log(window.value);
var e = document.getElementById("selMag2");
var option2 = e.options[e.selectedIndex].text;
//do whatever u want
}
You can make another function say x() that will be called for other select box you make and access the value of first select box from that
<select id='selMag2' onchange='x(this)'>
as
function getSelMag2(sel) {
value = Number(sel.value);
console.log(window.value);
var e = document.getElementById("selMag");
var option1 = e.options[e.selectedIndex].text;
//do whatever u want
}
Hope this helps

Get the values of all select options on change event javascript

I want to know all the values of a select element once the change event is recorded on it.
Code is like this:
PHP
<select name='variant' class='variantsselect' onchange='on(this.value)'>
<option value='a'>a</option>
<option value='a'>a</option>
</select>
JAVASCRIPT
function on(value){
alert(value); //This gives me selected value
};
I need values a & b when change event is recorded on select element. Can someone help?
<select name='variant' class='variantsselect' onchange="javascript:valueselect(this)">
function valueselect(sel) {
var value = sel.options[sel.selectedIndex].value;
alert(value)
}
EDIT:
<select name='variant' id='variant' class='variantsselect' onchange="javascript:displayResult()">
function displayResult() {
var x = document.getElementById("variant");
var i;
var txt = "Text: ";
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].text;
}
alert(txt);
}
You can store the last selected value in a variable and overwrite the variable with the new selected value at the end of your function. When the function is called the variable will = to the last option selected (If you don't set a default value the variable will be empty on the first call)
Click Here For Demo
OR
This will work for a simple hide/show select without having to remember the previous selection.
The hide/show content have a class name of HideShow, this class name css display is set to none. When you change the option it will loop through all elements using the class name HideShow to compare the selected value with the id of the element, if they match it will set the style display to block }else{ set style display to none.
Demo
function HideShow(Selection){
var HScontent=document.getElementsByClassName('HideShow');
for(var i=0; i<HScontent.length; i++){
if(HScontent[i].id==Selection){
HScontent[i].style.display="block";
}else{
HScontent[i].style.display="none";
}
}
}
.HideShow{display:none;}
<select onchange="HideShow(this.value);">
<option value="cars">Cars</option>
<option value="bikes">Bikes</option>
<option value="buses">Buses</option>
</select>
<div id="cars" class="HideShow">Cars content.....</div>
<div id="bikes" class="HideShow">Bikes content....</div>
<div id="buses" class="HideShow">Buses content....</div>
If you don't understand something in the demo, leave a comment below and I will try get back to you as soon as possible.
I hope this helps. Happy coding!

jQuery - Each loop to select all items by data attribute, but also dependent on select (option) values

I am in the process of building an e-Commerce shop and have hit a small bump in the road for my actual product page. Based on any product options set that would add to the price if selected, I would like to be able to update the price on the page live when these options have been added. I have managed to iterate through every element with a "data-price-effect" attribute attached to them, HOWEVER, when it comes to a select element, I would need to check if the item is selected as an option, each option has their respective price change attribute of course, but the value would only update to the actual select element.
Here is my code upto now:
function updatePrice(){
$('[data-price-effect]').each(function( index ) {
// do something
});
}
Basic HTML set-up to explain further:
<form>
<input type="text" name="foo" onchange="updatePrice();" data-price-effect="10.00" />
<select name="bar" onchange="updatePrice();">
<option selected value="Item1" data-price-effect="5.00">Item 1</option>
<option selected value="Item2" data-price-effect="8.00">Item 2</option>
<option selected value="Item3" data-price-effect="10.00">Item 3</option>
</select>
</form>
I have NO idea how to even logically do this, not even with some huge messy code. Any pointers here from someone more experienced with Javascript?
Instead of having "updatePrice()" on each element, you could have a listener for all form elements for the function:
var EffectElements = $('form input[data-price-effect], form select');
EffectElements.on('change', function() {
var PriceEffect = 0;
EffectElements.each(function() { // Loop through elements
if ($(this).is('select')) { //if this element is a select
$(this).children().each(function() { //Loop through the child elements (options)
if ($(this).is(':selected')) { //if this option is selected
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
} else {
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
});
You could then use the PriceEffect variable to update your price on the website.
Ultimately it's the IS function doing the dirty work you needed ~_o
Working Example

Set option of the Select box according to JSON result

I actually have some questions but I will start with the main one. I want to set the value of Select box on the basis of JSON.
Here's the HTML in question,
<label class="lbl">Office: </label>
<select tab-index="6" class="required" name="office" class="off">
<option value="">---------</option>
<option value="U">London</option>
<option selected="selected" value="R">Delhi</option>
<option value="W">Lisbon</option>
</select>
JSON sends it like this, I can't show the full JSON since it's too big, but I will show a part, Location: "U".
Here's the JS part:
if (data.Office === "R") {
$('select option[value="Delhi"]').prop('selected', true);
}
if (data.Office === "U") {
console.log('here');
$('.off option[value="London"]').attr('selected', 'selected');
}
if (data.Office === "W") {
$('select option[value="Lisbon"]').prop('selected', true);
}
But it's not working? Can any one point out why?
Moreover, I have a list of managers say and I am also getting that in JSON. So I am doing this,
for (var i = 0; i < data.Managers.length; i++) {
find_input = $('input[name="project_manager[]"').length;
if (find_input != data.Managers.length) {
$('<input type="text" name="project_manager[]" class="" value="" />').appendTo('#managers');
}
console.log(data.Managers[i].Manager);
$('input[name="project_manager[]"').each(function() {
$(this).val(data.Managers[i].Manager);
});
}
No of textboxes depend on the number of managers, but it only sets the value of last item from the array of managers in text boxes that are appended. Why?
Moreover I am not able to set value of textarea in Firefox like this:
$('textarea#some_id').val(data.Description);
It works in Chrome though.
First you need to add the character "<" in the beginning of the 3rd option of the select box:
<option selected="selected" value="R">Delhi</option>
Now, in the JS code, your problem is that you're using the wrong value. Instead of:
$('select option[value="Lisbon"]').prop('selected', true);
You must use:
$('select option[value="W"]').prop('selected', true);
I hope it help.
I think your selectors should be of the form:
$('select option[value="R"]').prop('selected', true);
Note the value is the same as the value in the HTML, not the displayed string (i.e. 'R' instead of 'Delhi').
Also, you should be using prop() consistently for selected flag, as described here by John Resig.

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

Categories

Resources