Get all values from drop down except selected one in JavaScript - 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>

Related

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.

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;
}
}

options is null or not an object

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.

How can we arrange the three select box into one sequence through Jquery

I would like to know how can we arrange the three select box, with having some options, it will be configured according to the previous select box value.
Please look at the code which we applied for our program.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var rtype = $("#rtype").val();
var rarray = rtype.split(' ');
var max_adults = rarray[1];
var min_adults = rarray[0];
//var max_adults = 3;
//var min_adults = 2;
$('#rooms').change(function(){
var room_num = $(this).val();
var options = '';
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) { options += '<option value="'+i+'">'+i+'</option>' } $('#person').html(options); }); $('#rooms').change(); });
</script>
</head>
<body>Room Type <select name="rtype" id="rtype"><option Selected value="">Select</option><option value="2 3">Room 2-3</option> <option value="3 4">Room 3-4</option></select> Category: <select name="rooms" id="rooms"> <option Selected value="">Select</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option> </select>Persons<select name="person" id="person"> </select></body>
Above this code is working fine if we remove the code for "rtype" ID, and entered the hard coded value to the query like this.
var max_adults = 3;
var min_adults = 2;
but we likt to update this value when we change the "rtype" id, the value for the an option is ( 2 3), we just have to split these value in to two part, the higher one will put into " var max_adults", and lower one will go to "var min_adult".
Please give me the proper solution, how can we arrange the codes accordingly.
You need to put the rtype code inside the change event handler tof the #rooms element:
$(function () {
$('#rooms').change(function(){
//get the `#rtype` value
var rtype = $("#rtype").val();
//check to make sure the `#rtype` value isn't an empty string
if (rtype != '') {
var room_num = $(this).val(),
rarray = rtype.split(' '),
options = '',
max_adults = rarray[1],
min_adults = rarray[0];
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) {
options += '<option value="'+i+'">'+i+'</option>';
}
$('#person').html(options);
} else {
//since no `#rtype` value was found alert the user
alert('Please Select a Room Type');
}
//trigger the change event by chaining rather than re-selecting the same element
}).change();
});
Update
To make one element appear when the other changes, add this to the document.ready event handler:
$('#rtype').change(function () {
//if a value has not been selected then hide the `#rooms` element, otherwise show it
if (this.value == '') {
$('#rooms').hide();
} else {
$('#rooms').show();
}
});
You then need to add the following CSS for the #rooms element:
#rooms {
display : none;
}

How do I programmatically set the value of a select box element using JavaScript?

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

Categories

Resources