I've got a page im trying to develop which will take user input and then add it to an array and then take that array and make a select and option list out of it as such.
<!DOCTYPE>
<html>
<head>
<script>
var option_list = [];
// for loop at thats option_list to select select tag
for (var i = 0; i < option_list.length; i++){
var opt = option_list[i];
var option = document.createElement("option");
var select = document.getElementById("select");
option.setAttribute("id", opt); //Adding ID to the option list
option.setAttribute("class", "intersect-option"); // adds classes to option
option.value(opt); // adds value to option list
select.appendChild(option); // Adds option to the list.
}
function add_option(name){
var name = document.getElementById("name").value;
name.push(option_list());
}
</script>
</head>
<body>
<input type="text" id="name" value="">
<input type="button" onclick="add_option()" value="add person">
<select id="select">
</select>
</body>
</html>
The issue i am having is that it says when i try and input the information i get back-
Uncaught TypeError: option_list is not a function
at add_option (selectTest.html:19)
at HTMLInputElement.onclick (selectTest.html:25)
I am unsure what i am doing wrong and any help would be greatly appreciated.
You should push name into option_list array. The correct syntax is option_list.push(name);
function add_option(){
var name = document.getElementById("name").value;
option_list.push(name);
}
Pushing elements into array works the other way:
option_list.push(name);
http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
name.push(option_list());
As it says, option_list is not a function, and balanced parentheses after an identifier designate a function call in C family languages, so option_list() is not a valid expression.
Additionally, did you really intend to loop from zero up to the length of an empty array (which is equally zero)?
<!DOCTYPE>
<html>
<head>
</head>
<body>
<input type="text" id="name" value="">
<input type="button" onclick="add_option()" value="add person">
<select id="select">
</select>
<script>
var option_list = [];
// for loop at thats option_list to select select tag
var select = document.getElementById("select");
function add_option(name){
var name = document.getElementById("name").value;
var option = document.createElement("option");
var label = document.createTextNode(name);
option.setAttribute("id", name); //Adding ID to the option list
option.setAttribute("class", "intersect-option"); // adds classes to option
option.value = name; // adds value to option list
option.appendChild(label);
select.appendChild(option); // Adds option to the list.
}
</script>
</body>
</html>
Related
I have copied several examples from this and other sites about how to add options to an HTML drop down list, but yet nothing happens. Here is my script:
<!DOCTYPE html>
<html><head></head>
<body>
<form>
<select name="p1customer" id="p1customer" onclick="addPC()">
<option>Apple</option>
</select>
<button type="button" onclick="addPC()">Insert option</button>
</form>
<script>
function addPC(){
let x = document.getElementById("p1customer");
let option1 = document.createElement("pc1");
option1.text = "myCustomer";
x.add(option1);
}
</script>
</body>
</html>
Whether I click on my drop-down or the button the option never gets added. I have placed alert functions after each line of code and have verified that the objects exist, but the x.add method does nothing. It doesn't add the option to my list.
What am I missing?
You have two mistakes in your code:
pc1 is not a tag name. so you cannot use it in the createElement function.
For adding an option you should use x.appendChild instead of x.add.
function addPC() {
let x = document.getElementById("p1customer");
let option1 = document.createElement("option");
option1.text = "myCustomer";
x.appendChild(option1);
I merely had to assign a value to the option as seen below and everything works.
function addPC(){
let x = document.getElementById("p1customer");
let option1 = document.createElement("pc1");
option1.text = "myCustomer";
option1.value = "myC";
x.add(option1);
}
I have this HTML with the following Input SearchBox and the Following Label that contains this Select Option.
I want to place the searchBox inside the Option so If I have 10000 This in that Select. To use the searchBox and select what option I want from there.
searchBox = document.querySelector("#searchBox");
countries = document.querySelector("#btd1");
var when = "keyup"; //You can change this to keydown, keypress or change
searchBox.addEventListener("keyup", function(e) {
var text = e.target.value;
var options = countries.options;
for (var i = 0; i < options.length; i++) {
var option = options[i];
var optionText = option.text;
var lowerOptionText = optionText.toLowerCase();
var lowerText = text.toLowerCase();
var regex = new RegExp("^" + text, "i");
var match = optionText.match(regex);
var contains = lowerOptionText.indexOf(lowerText) != -1;
if (match || contains) {
option.selected = true;
return;
}
searchBox.selectedIndex = 0;
}
});
<!DOCTYPE html>
<html>
<head>
</head>
<body style="margin:0;">
<input id="searchBox" placeholder="Seach Project..." type="search">
<select id="btd1" name="Project">
<option disabled hidden="" selected value="">
Select Project *
</option>
</select>
</body>
</html>
The Option Box don't contain nothing cuz In my index it has a JS that Adds options with a add button.
Can anyone tell me please how can I make this work ?
Thanks a lot :)
yeap, Here is your DEMO. What I have done is this; Get the value of the searchbox dynamicly onkeyup then count the number of options included. then get into a for loop to get the best macth and write it into the select. Of course then break when there is a match to prevent the loop go and check other matches and come with a result with less match but a match.
I'm working on an assignment and one of the requirements is that I use the form tag to create a list of all countries and their country code, the file was provided as an external Javascript file in an object array, I've never used an external javascript file before so I'm not sure how to access the array and put it into the form.
Currently this is how I my form looks:
https://jsfiddle.net/so0z3m0v/
<head>
<script src="myscripts.js"></script>
</head>
<body>
<form id="register" action="http://formpost.azurewebsites.net/home/test" method="post">
Country * <select name="country" form="register">
<option value="CA">Canada</option><br><br>
</select><br><br>
<input type="submit" value="submit">
</body>
You can easily access the array of external javascript like an internal one.
And this is how you access and populate it to your select tag.
// To clear the select options
var select = document.getElementById("country");
var length = select.options.length;
for (i = 0; i < length; i++) {
select.options[i] = null;
}
// Iterate your array and set it as new option in the select
countries.forEach(function(elem, index){
select.options[index] = new Option(elem.name, elem.code);
});
Fiddle: https://jsfiddle.net/so0z3m0v/1/
What you have is an array of objects. To access an item (object) in the array, use its index. Then you can access a property of that object with dot notation
var x= countries[0].name; //Andorra
Below is a loop that will access every piece of info and place it into a select.
Note I have given your select element and id attribute.
var ddlCountry = document.getElementById('ddlCountry');
for(var i=0;i<countries.length;i++)
{
var country = countries[i];
var name=country.name;
var node = document.createElement("OPTION");
var textnode = document.createTextNode(name);
node.appendChild(textnode);
ddlCountry.appendChild(node);
}
Working Example here https://jsfiddle.net/so0z3m0v/2/
Aaaand to put it all together
<head>
<script src="myscripts.js"></script>
</head>
<body>
<form id="register" action="http://formpost.azurewebsites.net/home/test" method="post">
Country * <select name="country" form="register">
<option value="CA">Canada</option><br><br>
</select><br><br>
<input type="submit" value="submit">
<script type="text/javascript">
// put it down here because the HTML must be loaded completely
// make a generic option node
var option = document.createElement("option");
// find the "select" element by it's name
var select = document.getElementsByName("country")[0];
// over the whole countries array
for(var i = 0; i < countries.length;i++){
// make a copy of the generic option element build above
// and append it to the end of the select element
select.appendChild(option.cloneNode());
// set the value of the option element to the code
select.lastChild.value = countries[i].code;
// set the text to the name of the country
select.lastChild.textContent = countries[i].name;
}
</script>
</body>
I have 2 Selectbox
Countrynames
Airports
And as I select a countryname in first selectbox an Ajax request will be sent and it returns a list of Airposts as options like
"
<option value='1'>abc
<option value='3'>lmn
<option value='2'>xyz
"
now i have to replace only the options of select tag.
i am trying to do something like
var country_select = document.getElementById("country_select");
country_select.options.length = 0;
country_select.options = response.responseText
but this assignment is not working how may i get it done!
Try
var country_select = document.getElementById("country_select");
country_select.innerHTML = response.responseText;
This is a little bit more tricky, you won't be able to do it using innerHTML or anything like that.
You will have to change the way your ajax is returning airport names. Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example || : abc||def||xyz . then explode the string into an array in JS, create an option elements from every element in array, and add it to dropdown. check that:
<html>
<head>
<script>
var ajaxResponse = "abs||def||xyz||test||blah";
function updateOptions( optionsString )
{
var options = optionsString.split("||");
for( var i=0; i< options.length; i++ )
{
AddItem( options[i], options[i] );
}
}
function AddItem(Text,Value)
{
var opt = document.createElement("option");
opt.text = Text;
opt.value = Value;
document.getElementById("mydropdown").options.add(opt);
}
function removeOptions()
{
document.getElementById('mydropdown').length = 0;
}
</script>
</head>
<body>
<input type="button" onclick="updateOptions(ajaxResponse)" value="update"></input>
<input type="button" onclick="removeOptions()" value="remove"></input>
<select id="mydropdown">
</select>
</body>
</html>
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