options is null or not an object - javascript

I am trying to select dropdown automatically based on values from another dropdown. Second dropdown will have more values than first one. If I select the first dropdown, then the second should be selected automatically. I tried the below code and getting error: Options is null or not an object. ???
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.options.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data').value;
for(var i=0; i<del.options.length; i++);
{
if(values[i] == del.options[i])
{
del.options[i].selected;
}
}
}
</script>
<select multiple="multiple" onchange="showState(this);">
<option value="1">Test1</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>
<select name="data" id="data" multiple="multiple">
<option value="1">Test1</option>
<option value="2">Test2</option>
<option value="3">Test3</option>
<option value="4">Test4</option>
</select>

I think you should make some correction in your code as below :
<script type="text/javascript">
function showState(me){
var values = ''; //populate selected options
for (var i=0; i<me.length; i++)
if (me.options[i].selected)
values += me.options[i].value + ',';
values = values.substring(0, values.length-1);
var selected=[values];
var del = document.getElementById('data');
for(var i=0; i<del.length; i++)
{
for(var j=0;j<values.length;j++)
{
if(values[j] == del.options[i].value)
{
del.options[i].selected = true;
}
}
}
}
</script>
for more details on Select and Option objects in javascript you may refer this link !

I think your problem is here var del = document.getElementById('data').value;. If you want to access the select options, you should use var del = document.getElementById('data');, without the .value. This way the variable del should have the .options array.

Related

JS select option based on previous option

I have a form and I wish that second select option depends on first. It means if I select DEV_1_OLD otption it wont be showed in the second select list. How to do it with JS?
I started something like that but it doesnt work as I expected
<select id="s11" name="source" onchange="preapreSelectOptions()">
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
</select>
Target Environment:
<select id="s12" name="target" required>
</select>
<script>
function preapreSelectOptions () {
var op = document.getElementById("s11").getElementsByTagName("option");
console.log(op.length);
var opClone = op;
for (var i = 0; i < op.length; i++) {
opClone[i] = document.createElement('option');
// opClone[i].textContent = op[i].value;
// opClone[i].value = op[i].value;
document.getElementById('s12').appendChild(opClone[i]);
}
}
</script>
you need to add a condition to check if the option you appending is the selected one
<select id="s11" name="source" onchange="preapreSelectOptions()">
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
</select>
Target Environment:
<select id="s12" name="target" required>
</select>
<script>
function preapreSelectOptions () {
var op = document.getElementById("s11").getElementsByTagName("option");
var selected = document.getElementById("s11")
for (var i = 0; i < op.length; i++) {
// check if option is not selected
if(op[i].value != selected.options[selected.selectedIndex].value) {
o = document.createElement('option')
o.value = op[i].value
o.text = op[i].text
document.getElementById('s12').appendChild(o);
}
}
}
</script>
A little improvement for your code so you can dynamically generate the next option list:
Add conditional checking if value not selected
Make the function preapreSelectOptions accept argument so you can automatically generate new list for next select element based on current selection.
When call the preapreSelectOptions function, pass the current element id and next element id.
//Make it accept argument so you can automatically generate new list for next select
function preapreSelectOptions(currentSelectedElement, nextSelectElementId){
let selectedValue = document.getElementById(currentSelectedElement).value
//list the remain value in case you need it for other logic
let remainValue = function(){
let selectOptionList = document.getElementById(currentSelectedElement).children
let arr = []
for(var i = 0; i < selectOptionList.length; i++){
if(selectOptionList[i]["value"] !== selectedValue){
arr.push(selectOptionList[i]["value"])
}
}
return arr
}()
//generate option
for(var i = 0; i < remainValue.length; i++){
let newOption = document.createElement("option")
newOption.value = remainValue[i]
newOption.textContent = remainValue[i]
document.getElementById(nextSelectElementId).appendChild(newOption)
}
}
s11<br>
<select id="s11" name="source" onchange="preapreSelectOptions('s11','s12')" value="">
<option value=""></option>
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
<option value="PROD_NEW">PROD_NEW</option>
<option value="PROD_LATEST">PROD_LATEST</option>
</select>
<br>
s12<br>
<select id="s12" name="source" onchange="preapreSelectOptions('s12','s13')">
</select>
<br>
s13<br>
<select id="s13" name="source">
</select>

Javascript get specific values from array list

<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
I have the above List on my HTML select field.
I want to be able to get only the values --Product--, --Software--, --Services--
So I created an loop to go throw the list of products and used the method startwith to pickup the values starting with "--".
function loadFilter() {
var x = document.getElementById('List');
var i;
var n;
for (i = 0; i < x.length; i++) {
str = x[i].text
var n = str.startsWith('--');
flag = true;
if (n == true) {
alert(x[i].text); // list --Product--, --Software--, --Services--
alert(x[3].text); // prints from the LIST <product1> and not <--Services-->
}
}
}
So when the flag is true, the alert(x[i].text); list correctly the values (--Product--, --Software--, --Services--).
But when I try to get them by their values(index), E.G ..I need to get only (--Services--), so I use x[3].text), but this returns me the whole List values >> and not <--Services-->.
You can use the below code to populate array arr with the list of options having "--".
Then you can use arr[2] to get --Services--.
var arr = [];
[].slice.call(document.querySelectorAll("#List option")).map(function(el){
if (el.text.indexOf("--") === 0) arr.push(el.text);
});
console.log(arr)
console.log(arr[2])
<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
Here you go:
function loadFilter() {
var element = document.getElementById('List');
var children = element.children;
var filtered = [];
for (var i = 0; i < children.length; i++) {
if (children[i].textContent.startsWith('--')) {
filtered.push(children[i].textContent);
}
}
return filtered;
}
To recap what the function did:
Get the element "List"
Get the children of "List"
Create an array to hold elements that pass the filter
Go through each element and add those with match the specified regex
Return the elements that pass the filter
I'm still not entirely sure what you're trying to do. --Services-- is index 9, not 3. To get --Services-- you need x[9].text
If you want to rearrange the three --xx-- into their own index, you need to push them into a new array, like so:
var output = []
if (n === true) output.push(x[i].text)
console.log(output[2]) // --Services--
You can use simple forEach loop to loop through elements like here, but first you need to create Array from your DOM Node list:
var list = Array.from(x);
list.forEach((value,index)=>{
if (value.text.startsWith('--')){
alert(value.text);
}
});
I've put it up on fiddle so you can check:
https://jsfiddle.net/pegla/qokwarcy/
First of all, you don't seen to be using your flag at all.
If I understood it correctly, you are trying to get --Services-- using x[3].text, but if you count your whole list the element at index [3] is the . You can verify that with the code bellow:
f (n == true) {
alert('index '+ i + ': ' + x[i].text); // list --Product--, --Software--, --Services--
}
You could create a new array containing the filtered options and then access the with the known index:
var filteredArray = [];
f (n == true) {
filteredArray.push(x[i]); //insert the element in the new array.
}
alert(filteredArray[2].text) //print --Service--, the third element of filtered array.
Remember that javascript has zero indexed array, so the first element has index 0, so, in order to acces the third element you'll need the index 2.
May be you want to try using optgroups?
Something like this:
<select name="List" id="List">
<option value="">-Select-</option>
<optgroup label="--Product--">
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
</optgroup>
<optgroup label="--Software--">
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
</optgroup>
<optgroup label="--Services--">
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</optgroup>
</select>
Then,
var select = document.getElementById('List');
var optgroups = select.getElementsByTagName('optgroup');
console.log(optgroups[2].label);
Will show:
--Services--
try:
function load() {
list = document.getElementById('List');
var data = document.getElementsByTagName('option');
currentCatagory=null;//the current selected catagory
currentvalue=null;
listdata=[];
//for all the options
for(cnt = 0; cnt < data.length; cnt++){
var e = data[cnt].innerHTML;//get option text
if(e.startsWith('-')){//test to make a catagory out of it
if(currentCatagory!=null)//do not concat is listdata is null
listdata=listdata.concat(currentCatagory);
currentCatagory = {"this":e,"listOfItems":[]};//create the catagory
}else if(currentCatagory!=null){//make sure currentCatagory is not null
var l=currentCatagory.listOfItems;//get the Catagory's list
currentCatagory.listOfItems = l.concat(e);//and add e
}
}
listdata=listdata.concat(currentCatagory);//add last catagory
//sets the list to show only catagories
var inner='';
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
list.innerHTML=inner;
}
function update(){
//check to make sure everything is loaded
if(typeof list=='undefined'){
load();
}
var inner='';//the new options
var value=list.options[list.selectedIndex].innerHTML;
if(value==currentvalue) return;
if(value.startsWith('-')){//if catagory
if(value.startsWith('--')){//if not -Select-
for (i = 0; i < listdata.length; i++) {//for all catagories
if(value==listdata[i].this){//if it is the current selected catagory then...
currentCatagory=listdata[i];//update the currentCatagory object
inner+=parseOp(listdata[i].this);//parse as option and append
//then append catagory's items
for(item in listdata[i].listOfItems){
inner+=parseOp(listdata[i].listOfItems[item]);
}
}else{//appends the other catagories
inner+=parseOp(listdata[i].this);
}
}
}else{//if it is '-select-' then just append the catagories
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
}
//set the new options
list.innerHTML=inner;
}
}
function parseOp(str){
//parse the options
return '<option value="">'+str+'</option>';
}
<select name="List" id="List" onchange="update();">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
and to set the dropdown box you will have to run load() otherwise load() will only be called after the first change event occurs.

Get all values from drop down except selected one in JavaScript

I have drop down menu with some random values. When I select the value onchange event triggers and I want to add new drop down under it, but the new one should have all values except selected one in first drop down.
Now when I change value of second one, I need third one that has only non selected values from previous two drop downs.
What is the easiest way to do this in javaScript?
What I have for now is mechanism for adding new dropdowns, but for now I am filling it with some dummy data.
I need to implement function which I can call instead of dateGenerate()
I have to solve this without using jQuery :(
This is HTML:
Test:<br>
<select id="ddlTest" onchange="addNewTestDrop('newTest');">
<option value=""></option>
<option value="Raven">Raven</option>
<option value="PPA">PPA</option>
<option value="PPA+">PPA+</option>
<option value="Basic Knowledge">Basic Knowledge</option>
<option value="PCT">PCT</option>
</select>
<div id="newTest">
</div>
And this is javaScript I have:
function dateGenerate() {
var date = new Date(), dateArray = new Array(), i;
curYear = date.getFullYear();
for(i = 0; i<5; i++) {
dateArray[i] = curYear+i;
}
return dateArray;
}
function addNewTestDrop(divname) {
var newDiv=document.createElement('div');
var html = '<select>', dates = dateGenerate(), i;
for(i = 0; i < dates.length; i++) {
html += "<option value='"+dates[i]+"'>"+dates[i]+"</option>";
}
html += '</select>';
newDiv.innerHTML= html;
document.getElementById(divname).appendChild(newDiv);
}
Get all options except the one that has the same value as the select (as it's selected), clone them, and append to the new select
document.getElementById('ddlTest').addEventListener('change', function() {
var newSelect = document.createElement('select');
var options = [].slice.call(this.querySelectorAll('option')).forEach(function(elem) {
if (this.value !== elem.value) newSelect.appendChild(elem.cloneNode(true))
}.bind(this));
document.getElementById('newTest').appendChild(newSelect);
}, false);
FIDDLE
You can modify this code as you need.
$(document).ready(function() {
var selectWrapper = $('#select-boxes');
$(document).on('change', '.dynamic-select', function() {
var element = $(this);
var optionsLength = (element.find('option').length) - 1; // because we have an empty option
if(optionsLength === 1) {
return true;
}
var newSelect = $(this).clone();
newSelect.find("option[value='" + element.val() + "']").remove();
newSelect.appendTo(selectWrapper)
});
});
.dynamic-select{
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="select-boxes">
<select class="dynamic-select">
<option value=""></option>
<option value="Raven">Raven</option>
<option value="PPA">PPA</option>
<option value="PPA+">PPA+</option>
<option value="Basic Knowledge">Basic Knowledge</option>
<option value="PCT">PCT</option>
</select>
</div>

Output to multiple divs using getElementsByClassName?

I want to output to multiple elements using JavaScript. The following example may show what i want.
<select id="leave" onchange="leaveChange()">
<option value="">Select</option>
<option value="150">EMS</option>
<option value="350">DHL</option>
<option value="200">UPS</option>
<option value="75">Ethiopia Postal</option>
</select>
<script>
function leaveChange() {
if (document.getElementById("leave").value == document.getElementById("leave").value){
document.getElementsByClassName("item_shipping")[0].innerHTML = document.getElementById("leave").value;
}
else{
document.getElementById("item_shipping").innerHTML = 0;
}
}
</script>
<div class="item_shipping"></div> //this is getting value
<div class="item_shipping"></div> //this i empty i want the same value?
The first div show the result but the second one is empty. How do I update both?
function leaveChange() {
var leaveValue = document.getElementById("leave").value;
var shippingItems = document.getElementsByClassName("item_shipping");
for (var i = 0; i < shippingItems.length; i++) {
if (leaveValue == leaveValue) // ??
shippingItems[i].innerHTML = leaveValue;
else
shippingItems[i].innerHTML = 0;
}
}

Get all select/option lists start by something

In an HTML page i have severals list.
<select name="salut-1358937506000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
<select name="salut-1358937582000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
...
In javascript, I want to get all select/option list which started by "salut-".
For theses list, i want to compare his name and his selected value.
I know it is possible in jQuery but can't use jquery, only javascript (JSNI with GWT exactly).
Have you an idea?
Thanks!
var selects = document.getElementsByTagName('select');
var sel;
var relevantSelects = [];
for(var z=0; z<selects.length; z++){
sel = selects[z];
if(sel.name.indexOf('salut-') === 0){
relevantSelects.push(sel);
}
}
console.log(relevantSelects);
You can use the getElementsByTagName function to get each SELECT name, for example:
var e = document.getElementsByTagName("select");
for (var i = 0; i < e.length; i++){
var name = e[i].getAttribute("name");
}
Then you can use the following code to get each OPTION for the SELECT, to do any necessary comparisons:
var options = e[i].getElementsByTagName("option")

Categories

Resources