I need to figure out how to make my javascript take in the select names dynamically. How should I go about this?
I've tried Tried var i = getElementsByName() and then if (i == "x) ... else .... with no results
My Javascript:
function displayResult()
{
var m=document.getElementsByName("x");
document.getElementById('divid').innerHTML = m[0].value;
}
My Html:
<form>
<select name = x>
<option> a </option>
<option> b </option>
<option> c </option>
</select>
<select name = y>
<option> 2 </option>
<option> 3 </option>
<option> 4 </option>
</select>
</form>
The simplest solution would be with jQuery http://jquery.com
var myx = "x";
var elems = $("select[name=" + myx + "]");
Also with new browser APIs using pure Javascript:
var elems = document.querySelectorAll("select[name=x]")
https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll
So you need that x to be 'dynamic'. I don't really understand what you mean with that but I guess you want to specify another name every time you call the function. That's what function parameters are for.
Change your function to this:
function displayResult(name)
{
var m=document.getElementsByName(name);
document.getElementById('divid').innerHTML = m[0].value;
}
Now you can call the function with:
displayResult("x");
I think that what you are actually looking for is this:
var nodes = document.getElementsByTagName('select');
var names = new Array();
for(i=0,c=nodes.length;i<c;i++){
names.push(nodes[i].name);
}
this code will produce an array names
containing the names of selects presented on the page
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.