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>
Related
I can't use Jquery or anything else, just Vanilla Javascript.
My initial approach was to have an array in global scope storing every registered item and then using a foreach to append an <option> child to the <select>, but apparently this only creates one option and renames it
HTML
<label for="productList">Show Products</label>
<select name="products" id="productList">
</select>
JS
let productArray = [];
let dropdown = document.getElementById("productList");
dropdown.addEventListener("click", initializeList());
function initializeList(){
//initializing with an example
productArray.push("PROD1");
productArray.push("PROD2");
productArray.push("PROD3");
productArray.forEach( item => {
option = document.createElement("option");
option.text = item;
dropdown.appendChild(option)
});
}
Unfortunately, this is not a very efficient approach since I'd have to manually create a variable every time I want to add something. I am going to create a method where you just pass an option name and it gets added to the dropdown options. It seems that even though it's a forEach, every option being added is the same. How can I avoid this?
When you setup the addEventListener, you need to send the function itself, not the return value.
You also need to test whether the select list has already been created before running the initializeList function. That way you only initialize it once.
let productArray = [];
let dropdown = document.getElementById("productList");
dropdown.addEventListener("click", initializeList); // send initializeList not initializeList()
function initializeList() {
if (productArray.length != 0) { // Don't initialize more than once
return;
}
//initializing with an example
productArray.push("PROD1");
productArray.push("PROD2");
productArray.push("PROD3");
productArray.forEach(item => {
option = document.createElement("option");
option.text = item;
dropdown.appendChild(option)
});
}
<label for="productList">Show Products</label>
<select name="products" id="productList">
</select>
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]);
}
}
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!
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
I have a list of names in a box that I want to filter through based on a user input and filter out names that don't match. Much like this example :http://www.somacon.com/p241.php. I am new to Javascript and this is how my names are displayed in the box:
<select id="authorSelectId" multiple="multiple" class="accordionSelect">
<c:forEach var="author" items="${dropDownValues.authorDisplayList}">
<option value="${author}">${author}</option>
</c:forEach>
</select>
And this is my input box for the user:
<input onKeyUp="handleKeyUp(20);" type="text" id='functioninput' name="functioninput" VALUE="" style="font-size:10pt;width:34ex;">
My code correctly calls my "handleKeyUp(20)" method. But I am unsure how to link to the "authorSelectId" list of names and filter through those based on "functionInput" text. If more code is needed, I can provide. Any help is appreciated.
You get a reference to authorSelectId using:
var asi= document.getElementById("authorSelectId");
Then, you can iterate over the options like this:
for (var i= 0; i < asi.options.length; ++i) {
var opt= asi.options[i];
if (opt.selected) {
// do something...
}
}