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
Related
I am trying to store images in an array using javascript. I also want to assign each image from that array to an option from a drop down list. The images are on different servers.
My function doesn’t work no matter what I try. Can someone please help me with this?
P.S – In this case I am only allowed to use javascript (homework :/) and I must use arrays to store the images.
HTML code:
<form action="#" method="get" accept charset="utf-8">
<select id="car">
<option> BMW </option>
<option> Mercedes </option>
<option> Audi </option>
<option> VW </option>
</select>
<input type="button" value="select" onclick="myFunction();">
</form>
Javascript code:
function myFunction() {
var pictures = new Array();
pictures[0] = "https://pixabay.com/p-848904/?no_redirect";
pictures[1] = "http://www.pruebas.pieldetoro.net/web/MERCEDES/DOSSIERES/w115/8-1.jpg";
pictures[2] = "https://pixabay.com/p-1203738/?no_redirect";
pictures[3] = "https://cdn.pixabay.com/photo/2015/11/13/13/45/vw-beetle-1042002_960_720.jpg";
var index = document.getElementById('car').selectedIndex;
document.images[0].src="https://pixabay.com/p-848904/?no_redirect" + pictures[index] + ".jpg";
}
Thank you for your answers!
That code should work :
function myFunction()
{
var pictures = [
"https://pixabay.com/p-848904/?no_redirect",
"http://www.pruebas.pieldetoro.net/web/MERCEDES/DOSSIERES/w115/8-1.jpg",
"https://pixabay.com/p-1203738/?no_redirect",
"https://cdn.pixabay.com/photo/2015/11/13/13/45/vw-beetle-1042002_960_720.jpg"
];
var index = document.getElementById('car').selectedIndex;
document.getElementById('img1').src = pictures[index];
<select id="myList" onchange="favBrowser()">
<option> var x</option>
<option> var y</option>
</select>
<script>
var x="google"; var y="firefox";
</script>
my question is , how to take the option's values from javascript
i think he ment he want to fill the options by Script
this can be done by
<select id="myDropdown">
</select>
<script type="text/javascript">
function fillDropDown() {
var ddl = document.getElementById('myDropdown');
for (var i = 1; i < 50; i++) {
var myNewOption = new Option();
myNewOption.value = i;
myNewOption.text = "my " + i.toString() + " option...";
ddl.options.add(myNewOption);
}
}
fillDropDown();
</script>
Cheers.
You can get it by writing
function favBrowser(){
var sel = document.getElementById("myList");
var value =sel.options[sel.selectedIndex].value;
window.alert(value);
}
You need to supply more information about what it is you really want to do. If what you want is to take the selected value, then take a look at this question
Get selected value in dropdown list using JavaScript?
I'm wondering if it's possible to store the selected values from a <select>in a JS array.
What I finally need to do is calculate the highest 6 values out of around 10 dropdowns, which I think I can do by using the JS Math.max() function.
Help is greatly appreciated.
Here is some sample code:
<? while($subjects = mysql_fetch_array($query)) { ?>
<select class="points">
<optgroup label="<?=$subjects['name']?>">
<option value="100">A1</option>
<option value="90">A2</option>
<option value="85">B1</option>
<option value="80">B2</option>
<option value="75">B3</option>
</optgroup>
</select>
<? } ?>
<script>....
Do something like this (JQuery):
var selected = new Array();
$('.points option:selected').each(function() {
selected.push($(this).val());
});
var selects = [].slice.apply(document.getElementsByTagName('select'));
selects.forEach(function (elem, i){
var value = elem.options[elem.selectedIndex].value;
//Do something with this value. Push it to an array, perhaps.
});
This assumes that all the selects on the page should be included. If that isn't the case, then you should use document.getElementsByClassName or a similar, more appropriate selector instead.
Demo
Try this:
var selectValues = [];
var selectNodeList = document.getElementsByClassName("points");
for (var i = 0; i < selectNodeList.length; i++) {
selectValues.push(selectNodeList[i].value)
}
// selectValues array now stores values of all <select> lists with class "points"
How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California
I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});