Dynamically set the value of select dropdown using query string paramater - javascript

To begin with, I'm new to Javascript.
I have a form with a select element with various options and I do not have access to change the form. There are no id's to the options, but just the values as shown in the code below.
<form>
<select class="country" name="country" id="countryid">
<option value="usa" selected="selected">USA</option>
<option value="canada">Canada</option>
<option value="japan">Japan</option>
<option value="china">China</option>
</select>
</form>
My goal is to populate the field in the above form automatically based on the url parameters.
For example, www.example.com?country=china should populate China in the form field. The following is the javascript code:
<script>
var param1var = getQueryVariable("country");
function displayresult(){
//document.getElementById(param1var).selected=true; //if there was id given in the form field
//cannot use document.getElementByValue(param1var).selected=true;
//document.querySelectorAll('input[value=' + param1var + ']').selected=true; does not work
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
</script>
I cannot use document.getElementById(param1var) because there is no id.
Javascript does not support document.getElementByValue(param1var).
document.querySelectorAll is not working.
Is there a way that I can reference the element using the option value?
Thanks!

You can just do it this way by setting the value of the select element. Also note that value is case sensitive, plus make sure that the function displayresult runs on onload or after the element appeared in the html.
document.getElementById("countryid").value=param1var;
Demo

Related

Do dependent dropdown in html using javascript with value and text

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]);
}
}

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!

Set HTML attribute value using java Script

I have html drop down list,which has country list. Now I want to set current country as a default value of list. I found the JavaScript code for get country using Geolocation.
My code:
function getCountry(var name) {
if(name==geoip_country_name()) {
return "selected";
}
}
Then I need to set the selected attribute of the option list.
I tried this:
<option value="Sri Lanka" selected="getCountry('sri Lanka')">Sri Lanka</option>
But this is not correct.
Basically I want to set selected attribute value using JavaScript function
How do I do that?
Use the window.onload event, and just set the dropdown's value. Keep in mind that your hard coded country names may differ from the geo service.
<script>
window.onload = function(){
document.getElementById("country").value = geoip_country_name();
}
</script>
<select id="country" name="country">
<option value="Sri Lanka">Sri Lanka</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<select>
Basically you can do it like this:
<html>
<body>
<select id="country">
<option id="germany" value="Germany">DE</option>
<option id="uk" value="UK">UK</option>
<option id="usa" value="USA">USA</option>
</select>
<script>
var selectedCountry = 'uk'; //getCountry
var index = document.getElementById(selectedCountry).index;
document.getElementById("country").selectedIndex=index;
</script>
Start the script after your select is rendered.
Note, that this example might not be best practice. I'm also not sure if it works in all browsers (Opera works). You might use an appropriate framework like JQuery, Mootools, ...
The selected attribute is not automatically evaluated as JS code. Assuming you have stored the desired country name in the variable country, could try this instead:
var country = "Sri Lanka";
var select = document.getElementById('myselect'); //Change to the ID of your select element
for (var i = 0; i < select.options.length; i++){
if(select.options[i].value == country)
select.selectedIndex = i;
}
If you are using JQuery following line should solve your problem:
$('select').val(geoip_country_name());
If geoip_country_name returns names in lower case, While initializing the select list, value for each option be in lower case.

<Select> with onChange working only once, and setting values with getElementsByName

I have various forms on a page, and a PHP-generated select on the top of the page.
What I want to do is:
The user selects an option from the form.
The value of the option is put into all of the inputs with a specific name.
The user can select another option, and the value of that option would replace the old value of the input.
The code I have so far (that doesn't work):
It doesn't work as in the onChange only fires the first time you select an option, and the values of the inputs aren't updated to the chosen option's value.
The select: (It can have more or less than three options, depending on the user.)
<select name="example" onchange="setexample()" id="exampleID">
<option value="1">Default Example</option>
<option value="12">User-created Example #2</option>
<option value="8">User-created Example #1</option>
</select>
This is part of one of the forms around the page:
<form action="[URL]" method="get">
<input type="hidden" name="exampleform" id="example1" value="">
// Other inputs //
</form>
JavaScript:
<script>
function setexample(){
setexample = document.getElementById("exampleID").options[document.getElementById("exampleID").selectedIndex].value;
document.getElementsByName("exampleform").value = setexample;
}
</script>
I don't want to use jQuery. This is just JavaScript.
Thank you in advance.
In your code:
> function setexample(){
> setexample = document...
The assignment to setexample overwrites the existing value (which is the function setexample). Declare the variable inside the function:
var setexample = document...
For the rest, see nnnnnn's answer.
The getElementsByName() method returns a list of elements, so you can't just directly set the value property that belongs to the individual elements in the list. You need to loop through the list (it's an HTMLCollection but for this purpose you can treat it like an array):
var els = document.getElementsByName("exampleform");
for(var i = 0; i < els.length; i++)
els[i].value = setexample;
For the rest, see RobG's answer.
You have these issues:
You're overwriting the name of your function and should use a local variable of a different name.
You're reference a single element form getElementsByName when it returns an array.
Try this:
<script>
function setexample(){
var item = document.getElementById("exampleID");
var val = item.options[item.selectedIndex].value;
var list = document.getElementsByName("exampleform");
for (var i = 0; i < list.lenth; i++) {
list[i].value = val;
}
}
</script>

Categories

Resources