Fill options of select tag - javascript

In my HTML file I have a select tag in which when I select the first one, another select tag should fill out with some options, and when select the other option, some others options will fill out in the other select tag.
I did that in my HTML :
<script type="text/javascript">
function fillWirelessChannel(){
var index;
var selectTag= document.getElementById('wirelessChannel'); selectTag.options.length = 0; // wireless should
selectTag.options.length = 0;
var auto = document.createElement("option");
auto.value= 'auto';
auto.innerHTML = 'auto';
if (document.getElementById('country').selected="1") {
for(index=4920; index<=5825; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
} else if(document.getElementById('country').selected="2"){
for(index=4920; index<=6075; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
}
}
</script>
The wirelessChanne is the select tag must fill.
The country tag is in the if statement and the selected one is our condition.
Now when I run the code, the second if does not work.( It does not display till 6075 in the second statement ) and also does not add auto option to the select tag.( I want to display auto in the first option of the wirelessChannel without conditions, I mean at the first index it should be displayed auto)
Where I am doing wrong?

to test if a value is equal to something you need to use a double equal sign - to set a value to something you would use a single equal sign.
function fillWirelessChannel(){
var index;
var selectTag= document.getElementById('wirelessChannel');
selectTag.options.length = 0;
var auto = document.createElement('option');
auto.value= 'auto';
auto.text = 'auto';
selectTag.appendChild( auto );
var oCountry=document.getElementById('country');
if ( oCountry.value==1 ) {
for( index=4920; index <= 5825; index+=5 ){
var opt = document.createElement('option');
opt.value= index;
opt.text = index;
selectTag.appendChild( opt );
}
} else if( oCountry.value=='2' ){
for( index=4920; index <= 6075; index+=5 ){
var opt = document.createElement('option');
opt.value= index;
opt.text = index;
selectTag.appendChild( opt );
}
}
}

In the If statement Use == instead of =. For adding an option auto to the select append that before your for loop.You have created the option but forgot to append the option.Use selectTag.appendChild(auto); befor the for loop
fillWirelessChannel();
function fillWirelessChannel(){
var index;
var selectTag= document.getElementById('wirelessChannel'); selectTag.options.length = 0; /* wireless should */
selectTag.options.length = 0;
var auto = document.createElement("option");
auto.value= 'auto';
auto.innerHTML = 'auto';
selectTag.appendChild(auto);
console.log(document.getElementById('country').value);
if (document.getElementById('country').value=="1") {
for(index=4920; index<=5825; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
} else if(document.getElementById('country').value=="2"){
for(index=4920; index<=6075; index+=5){
var opt = document.createElement("option");
opt.value= index;
opt.innerHTML = index;
selectTag.appendChild(opt);
}
}
}
<select id="wirelessChannel">
</select>
<select id="country" onchange="fillWirelessChannel()">
<option value="1">1</option>
<option value="2">2</option>
</select>

Related

How can I load this select input field with options passed using JS?

When loading an HTML table, there is this select input field, which should make available some options.
Right after the HTML table row is built, I'm calling a function, which should populate this input field, getting it by its class.
Here is the HTML piece and the function:
function loadTelaOptions(telaOptions) {
telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
document.querySelector('tableBodySelect').value = '';
let selectList = document.querySelector('tableBodySelect');
let options = selectList.getElementsByTagName('option');
for (let i = options.length; i--;) {
selectList.removeChild(options[i]);
}
let option = document.createElement("option");
option.value = "";
option.text = "";
selectList.appendChild(option);
telaOptions.forEach(function(item, index) {
let option = document.createElement("option");
option.value = item.toLowerCase();
option.text = item;
selectList.appendChild(option)
});
}
<td>
<select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
</select>
</td>
Appreciate any help!
Your selectors for .querySelector('tableBodySelect') doesn't match your desired elements. You try to match the classes, therefore you need to prepend a . to your selector .querySelector('.tableBodySelect')
This does already resolve your issue.
function loadTelaOptions(telaOptions) {
telaOptions = ["09-Black", "11-LT Jaspe"]; //Here for tests
document.querySelector('.tableBodySelect').value = '';
let selectList = document.querySelector('.tableBodySelect');
let options = selectList.getElementsByTagName('option');
for (let i = options.length; i--;) {
selectList.removeChild(options[i]);
}
let option = document.createElement("option");
option.value = "";
option.text = "";
selectList.appendChild(option);
telaOptions.forEach(function(item, index) {
let option = document.createElement("option");
option.value = item.toLowerCase();
option.text = item;
selectList.appendChild(option)
});
}
loadTelaOptions();
<td>
<select name='tableselect' required='required' class='tableBodySelect' value='Trying'>
</select>
</td>

Prevent duplicate values being added from a text box to a list box

I have a textbox where a user scans a barcode then selects an 'add to list' button which adds them to a listbox. I'm trying to modify it to prevent duplicates being added but can't seem to find a way that works.
function addToList(barcode) {
var barcode = document.getElementById("barcode").value.toUpperCase();
var opt = document.createElement("option");
document.getElementById("lstBox1").options.add(opt);
opt.text = barcode;
opt.value = barcode;
//$('barcode').val('');
document.getElementById("barcode").value='';
return false;
}
What would be the best way?
One possible solution is to keep track of the values entered in an Array
Then by checking if the value exists in the array or not, you can add the value to the dropdown
var allValues = [];
function addToList(){
var barcodeInput = document.getElementById("barcode");
var barcode = barcodeInput.value.toUpperCase();
barcodeInput.value='';
//if this value is already in the array, do nothing
if( -1 !== allValues.indexOf(barcode) ){
return;
}
allValues.push(barcode);
var opt = document.createElement("option");
document.getElementById("lstBox1").options.add(opt);
opt.text = barcode;
opt.value = barcode;
return false;
}
select{
min-width:100px;
}
<input id="barcode" />
<br/>
<select id="lstBox1"></select>
<br/>
<button onclick="addToList()">Add</button>
Check the value is not exist in the list before adding into the list.
You can try this
var listbox=document.getElementById("lstBox1")
for(var i; i<listbox.options.length; i++)
{
if(listbox.options[i].value!=barcode)
{
var opt = document.createElement("option");
opt.text = barcode;
opt.value = barcode;
listbox.options.add(opt);
}
}
Check whether inputted value already exist in the optionlist. If not present then add the value, else do nothing.
let found;
const submitBtn = document.querySelector('button');
submitBtn.addEventListener('click', function(e) {
e.preventDefault();
const val = document.querySelector('input').value.toLowerCase();
if(val.length > 0) {
const optionsArr = document.querySelectorAll('select > option');
found = [...optionsArr].filter((option) => option.value.toLowerCase() === val);
if(found.length == 0) {
addToList(val);
}
}
});
function addToList(val) {
const option = document.createElement('option');
option.value = val;
option.textContent = val;
document.querySelector('select').appendChild(option);
}
<input type="text">
<button>Add</button>
<select name="" id="">
<option value="usa">USA</option>
<option value="Japan">Japan </option>
</select>
This is an example you can use keeping some of the elements in memory and using Array.filter as validation strategy. Also you can seen for the filter I am showing an example of Arrow Functions to filter the duplicates.
let list = document.getElementById('lstBox1');
let input = document.getElementById('barcode');
let button = document.getElementById('addOption');
function addToList() {
let currentOptions = Array.from(list.options);
let barcode = input.value.toUpperCase();
let filter = currentOptions.filter(option => option.value == barcode);
if (filter.length == 0) {
let opt = document.createElement("option");
opt.text = barcode;
opt.value = barcode;
list.options.add(opt);
input.value = '';
} else {
alert('The value is duplicated');
}
};
button.addEventListener('click', addToList);
<input type="text" id="barcode">
<select name="" id="lstBox1">
<option value="TEST">TEST</option>
</select>
<button id="addOption">Add Option</button>
This is kind of bruteforce method but it will work. Using jQuery it
will be much simple.
1.This function will get all the list text
function getOptTxt() {
var x = document.getElementById("lstBox1").options.length;
var txt = [];
var i;
for (i = 0; i < x; i++) {
txt[i] += x.options[i].text;
}
}
2. You can check the barcode value ,If it is present in txt array or not if the value is not present in txt array then u can actually add the new option element
var flag =0
for (x in txt){
if(barcode == x.toUpperCase()){
flag =1
break;
}
}
if(flag == 0){
var opt = document.createElement("option");
document.getElementById("lstBox1").options.add(opt);
}

Replacing option in select field (not adding)

I have a select field as follows:
<select id="field">
I add options based on values found in another div (OtherDiv) on my page like this:
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}
However, I would like to set up some alternative value for the field to show, if there are no matches to the regex. How would I best achieve that?
Use if condition
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
if(result.length){
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}else{
//add alternative options here
var option = document.createElement("option");
option.innerHTML = "No records found"; //whatever text you want to show
select.add(option);
}
}

Auto populate option tag not working java script

I'm trying to populate number in select - option tag .But my script fills number at only one select tag
HTML :
<div class="form_row">
<label>Week Num</label>
<select class="form_select1" id="weeknum"></select>
<b class="bold1">&nbsp TO &nbsp</b>
<select class="form_select1" id="weeknum1"></select>
</div>
Javascript :
<script>
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
select1.add(option, 0);
}
</script>
How do i achieve that ?
You can add an element only once to a parent node, so you need to create another option element:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}
Here's the JSFIddle.
Try this ...
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option1, 0);
var option2 = document.createElement('option');
option2.text = option2.value = i;
select1.add(option2, 0);
... creating a distinct "option" for each select list. The created elements cannot be reused.
You need to create a distinct option element for each list. A given DOM element can only be in one place in the DOM.
edit: I see it's already answered... well, my first answer :)
try this:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
var option1 = document.createElement('option');
option.text = option.value = option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}

Add item to dropdown list in HTML using JavaScript

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load
<!DOCTYPE html>
<html>
<head>
<script>
function addList(){
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
}
</script>
</head>
<body>
<select id="year" name="year"></select>
</body>
</html>
Since your script is in <head>, you need to wrap it in window.onload:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
For higher performance, I recommend this:
var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');
//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
//var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
option.text = option.value = i;
options.push(option.outerHTML);
}
select.insertAdjacentHTML('beforeEnd', options.join('\n'));
This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.
Optional for generating the string by hand:
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:
var docfrag = document.createDocumentFragment();
for (var i = 1900; i < 2012; ++i)
{
docfrag.appendChild(new Option(i, i));
}
var select = document.getElementById("year");
select.appendChild(docfrag);
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to use appendChild method:
select.appendChild(option);
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle

Categories

Resources