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;
}
}
Related
<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.
Hello how can I select the value of Business by using the emplStatus2 GORM object?
<select name="emplStatus2" onchange="swapFieldsets(this.value, '#sa-email', '#sa-password')" class="form-control" id="emplStatus2">
<option value="Home">Send via Home Email</option>
<option value="Business">Send via Business Email</option>
<option value="Password">Set a password now,provide access information offline</option>
If you use jquery you can do it like this
$("#emplStatus2").val("Business")
if you only want javascript i think its something like this:
document.getElementById("emplStatus2").options.value = "Business"
please describe detail what you need.
You can check value
function swapFieldsets(elem) {
if (elem.value.toLowerCase() === 'business') {
alert(elem.value)
}
}
On fiddle https://jsfiddle.net/xw0pLmod/
If you want to select an item using pure javascript, you can use :
SelectOption3();
function SelectOption3() {
var sel = document.getElementById('select1');
var val = 'option3';
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].getAttribute("value") === val) {
sel.selectedIndex = i;
break;
}
}
}
<select id="select1">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
You need something like this:
var test = '';
for (var i = 0; i < document.getElementById("emplStatus2").options.length; i++) {
if (document.getElementById("emplStatus2").options[i].value === 'Business') {
test = document.getElementById("emplStatus2").options[i].innerText;
}
}
alert(test);
Here is JsFiddle of your example: https://jsfiddle.net/p457utLL/
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>
So I found this fiddle and I want to sort of merge it with this one. So when you click the button 3 times, they each have id 0, 1, 2 respectively. I then want to be able to hide the values of selected options from the other select elements. I tried to dynamically create the function from the working example but didn't manage to do it. Any help would be appreciated!
First fiddle;
JavaScript
$("#first").change(function() {
if($("#first").val() != "none") {
$("#second option[value!="+$("#first").val()+"]").show();
$("#second option[value="+$("#first").val()+"]").hide();
} else {
$("#second option[value!="+$("#first").val()+"]").show();
}
});
$("#second").change(function() {
if($("#second").val() != "none") {
$("#first option[value!="+$("#second").val()+"]").show();
$("#first option[value="+$("#second").val()+"]").hide();
} else {
$("#first option[value!="+$("#second").val()+"]").show();
}
});
HTML
<select id="first">
<option value="none">None</option>
<option value="one">Toyota</option>
<option value="two">Nissan</option>
<option value="three">Dodge</option>
</select>
<select id="second">
<option value="none">None</option>
<option value="one">Toyota</option>
<option value="two">Nissan</option>
<option value="three">Dodge</option>
</select>
Second fiddle;
JavaScript
arrSelects = [];
function generateSelect() {
var para = document.createElement("select");
$(para).attr('class', 'selectClass');
$(para).attr('id', arrSelects.length);
document.getElementById("createHere").appendChild(para);
arrSelects.push(' ');
fillSelect();
}
function fillSelect() {
$( ".selectClass").each( function () {
if ($(this).has('option').length < 1) {
for (var i = 0; i < 5; i++){
$(this).append('<option value='+i+'>'+i+'</option> ');
}
}
})
}
HTML
<button onclick="generateSelect()" onclick="generateFunction()">Click Me!</button>
<div id="createHere"></div>
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.