how to display selected value from dropdownlist to label using javascript - javascript

I have 3 drop-down lists in my form. I want to display the selected value from each dropdown list to my label. The problem is that only one dropbox list will display, while the other two won't.
Here is my code:
<script>
window.onload = function()
{
document.getElementsByName('mydropdown')[0].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
</script>
this is my html
<td><select name="mydropdown" id="mydrop" onchange="">
<option value="none" selected="selected"></option>
<option value="17.50">6M</option>
<option value="25.00">12M</option>
</select>
</td>
<td><label id="mylabel"></label></td>
<td><select name="mydropdown" id="mydrop">
<option value="none" selected="selected">Length </option>
<option value="0.0455">DS516HO</option>
<option value="0.0559">DS520HO</option>
<option value="0.0780">DS516HWR</option>
<option value="0.0200">DS312WH</option>
<option value="0.0624">DS520WH</option>
<option value="0.0361">DS525FH</option>
<option value="0.1170">DS620HW</option>
<option value="0.1340">DS550HW</option>
<option value="0.1340">TD525HW</option>
<option value="0.1820">DS650HW</option>
<option value="0.2340">TD665HWR</option>
</select>
<td><label id="mylabel"></label></td>

You're only binding the zeroth element (the one you selet) with [0]. You need to bind to all of them, possibly like so:
Array.prototype.forEach.call(document.getElementsByName('mydropdown'),
function (elem) {
elem.addEventListener('change', function() {
document.getElementById('mylabel').innerHTML = this.value;
});
});
http://jsfiddle.net/UNLnx/
By the way you are reusing the same ID on multiple elements which is invalid.

Update: Working example: http://jsfiddle.net/x8Rdd/1/
That's because you are only setting the onchange event for the first element in your "mydropdown" group.
<script>
window.onload = function()
{
var dd = document.getElementsByName('mydropdown');
for (var i = 0; i < dd.length; i++) {
dd[i].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
}
</script>
Or something like that. If you're using jQuery then you can set the onchange property for all of them without the loop.

Related

How to refresh a select list in html

I have a drop-down list where depending on the selected value, the next drop-down list shows specific values. when changing the value of the first list and then going back to the old value, the second list does not update. keeps the same value selected before. How can I make the second list update to the value I marked as selected by default whenever I change the value of the first list?
I hope you guys were able to understand me, and I thank you for your time.
Here's the code:
<select onchange="showprd('hidevalue', this), showprd2('hidevalue2', this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="hidevalue">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="hidevalue2">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
</body>
<script>
function showprd(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 0 ? 'block' : 'none';
}
function showprd2(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 1 ? 'block' : 'none';
}
</script>
TL;DR. Control the input value changes in one place.
Please see the updated snippet below. html structure hasn't been changed, but I've removed the inline js call and updated the id names. JavaScript blocks are commented in details.
In a nut-shell, this code listens for any change to the parent select dropdown. Whenever a change occurs, its child dropdowns will reset their values and toggle their visibility accordingly.
// Assign each dom element to a variable
const primarySelect = document.querySelector('#primary');
const childSelect1 = document.querySelector('#child1');
const childSelect2 = document.querySelector('#child2');
const defaultValues = document.querySelectorAll('.default');
function resetInputs() {
// Reset the child select options to default
defaultValues.forEach(option => option.selected = true);
}
function handlePrimary(e) {
// Reset the child select values whenever the parent value changes
resetInputs();
// `input` value is always a string. Here we're converting it to a number
const val = parseFloat(e.target.value);
// Toggle visibility of child select dropdowns
[childSelect1, childSelect2].
forEach((select, i) => select.style.display = val === i ? 'block' : 'none');
}
primarySelect.addEventListener('change', handlePrimary);
<select id="primary">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="child1">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="child2">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
If I understood correctly, the expected behavior is when the second or third <select> is hidden, the <select> should go back to default (the first <option>?). If so, then remove disabled and hidden from the first <option> of the second and third <select> then add the following:
selectObj.hidden = true;
selectObj.selectedIndex = 0;
The example below has a <form> wrapped around everything (always use a form if you have more than one form control. By using HTMLFormElement interface I rewrote the code and can reference all form controls with very little code. Inline event handlers are garbage so don't do this:
<select id='sel' onchange="lame(this)">
Instead do this:
selObj.onchange = good;
OR
selObj.addEventListener('change', better)
Read about events and event delegation
const UI = document.forms.UI;
UI.onchange = showSelect;
function showSelect(e) {
const sel = e.target;
const IO = this.elements;
if (sel.id === "A") {
if (sel.value === '0') {
IO.B.hidden = false;
IO.C.hidden = true;
IO.C.selectedIndex = 0;
} else {
IO.B.hidden = true;
IO.B.selectedIndex = 0;
IO.C.hidden = false;
}
}
}
<form id='UI'>
<select id='A'>
<option disabled selected hidden>Pick</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<br>
<br>
<select id="B" hidden>
<option selected>Pick B</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<select id="C" hidden>
<option selected>Pick C</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
</form>
I give you an example for your reference:
let secondList = [
[{
value: "pleno",
text: "Pleno"
},
{
value: "integrado",
text: "Integrado"
}
],
[
{
value: "junior",
text: "Junior"
},
{
value: "senior",
text: "Senior"
}
]
]
function update(v){
let secondSelectBox=document.getElementById("second");
secondSelectBox.style.display="none";
let optionList=secondList[v.value];
if (optionList){
let defaultOption=new Option("Selecione o produto","");
secondSelectBox.innerHTML="";
secondSelectBox.options.add(defaultOption);
optionList.forEach(o=>{
let vv=new Option(o.text,o.value);
secondSelectBox.options.add(vv);
})
secondSelectBox.style.display="block";
}
}
<select onchange="update(this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<select hidden id="second">
</select>

Add removed select options

Currently I have a function I created that removes some options from a select menu based on a value passed from another select. I want to revert back to normal each time the function is called (add all the original options back)
HTML
<select id="Current-Tier" onchange="removetier();" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500">Diamond</option>
</select>
<select id="Desired-Tier" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500">Diamond</option>
</select>
JS
function removetier(){
var currentTierValue = document.getElementById("Current-Tier");
var current = currentTierValue.options[currentTierValue.selectedIndex].value;
var desiredDivisionValue = document.getElementById("Desired-Tier");
for(var i=0;i<desiredDivisionValue.length;i++){
if(desiredDivisionValue[i].value < current){
desiredDivisionValue.remove(desiredDivisionValue[i]);
}
}
Update_Desired_Rank_image();
}
Have you considered adding the hidden attribute rather than deleting them?
Then the next time you receive a request, you can go through the list programmatically and remove the hidden attribute from each option.
An example of the hidden label, BTW, is
<select id="Desired-Tier" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500" hidden>Diamond</option>
</select>
If you run it you will see that Diamond is hidden. This way you always have access to all your options.
You can easily iterate over the select input and either store the removed items in an array or leverage the hidden attribute on the option tag:
Fiddle: https://jsfiddle.net/gLwwmh82/2/
HTML
<select id="mySelect">
<option value="">Select...</option>
<option value="test1">Test1</option>
<option value="test2">Test2</option>
<option value="test3">Test3</option>
<option value="test4">Test4</option>
<option value="test5">Test5</option>
<option value="test6">Test6</option>
</select>
<button id="btnRemove" onclick="remove()">Remove Half of Entries</button>
<button id="btnReset" onclick="reset()">Reset</button>
JS
function reset() {
var select = document.getElementById('mySelect');
var options = select.querySelectorAll('option');
for (var i = 0; i < options.length; i++) {
options[i].removeAttribute('hidden');
}
}
function remove() {
var select = document.getElementById('mySelect');
select.value = "";
var entries = select.querySelectorAll('option');
for (var i = 1; i < 5; i++) {
// Wrap the below line in your logic to know what to delete/not to delete
entries[i].setAttribute('hidden', true);
}
}

How to select multiple options if check option from a different select?

I want select multiple option from second select depending on check option from first select.
For example:
adiunkt -> mikroklimat, RTG
agent celny -> zapylenie
First select:
<select name="form[stanowisko][]" id="stanowisko">
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
</select>
Second select:
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option value="mikroklimat">mikroklimat</option>
<option value="RTG">RTG</option>
<option value="zapylenie">zapylenie</option>
</select>
I tried this but it not working (select all options after first check):
function tes(){
if (document.getElementById('stanowisko').value ="agent celny") {
document.getElementById('czynniki_szkodliwe').options[2].selected = true;
document.getElementById('czynniki_szkodliwe').options[0].selected = true;
}
if ( document.getElementById('stanowisko').value="adiunkt") {
document.getElementById('czynniki_szkodliwe').options[1].selected = true;
}
}
Pure js solution.
let elem1 = document.getElementById('stanowisko'),
elem2 = document.getElementById('czynniki_szkodliwe');
elem1.addEventListener('change', (e) => {
Array.from(elem2.children).forEach(v => {
return v.disabled = v.getAttribute('data-attr') !== e.target.value;
})
});
<select name="form[stanowisko][]" id="stanowisko">
<option value="">-</option>
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
</select>
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option value="mikroklimat" disabled data-attr='adiunkt'>mikroklimat</option>
<option value="RTG" disabled data-attr='adiunkt'>RTG</option>
<option value="zapylenie" disabled data-attr='agent celny'>zapylenie</option>
</select>
You should use a data attribute to mark the options linked to the first select like this:
$(document).ready(function(){
$("#stanowisko").on("change", function(event){
var $options = $("#czynniki_szkodliwe option");
//Unselect all
$options.prop("selected", false);
var val = $("#stanowisko").val();
$options.each(function(idx, item) {
if($(item).data("stanowisko").indexOf(val) >= 0) {
$(item).prop("selected", true);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="form[stanowisko][]" id="stanowisko">
<option value="">Choose</option>
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
<option vlaue="lekarz">lekarz</option>
</select>
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option data-stanowisko='["adiunkt"]' value="mikroklimat">mikroklimat</option>
<option data-stanowisko='["adiunkt","lekarz"]' value="RTG">RTG</option>
<option data-stanowisko='["agent celny"]' value="zapylenie">zapylenie</option>
</select>
Edit: If several options, from the first select, refers to the same options in the second select, you can "store" an array in the data attribute in JSON format.
I updated the JS code to handle JSON array in the data attributes instead of a simple string.

jQuery select option last doesn't work

I've got a button and list of options. The idea is that when user clicks the button the default option changes from disabled to max value. And oposite - if the input is not checked, the default is again disabled.
But the value returns undefined. If I change the first and thelast to numeric values, everything works fine. What's wrong?
<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected> -- choose -- </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
jQuery(function(){
jQuery(".input").click(function(){
var thefirst = jQuery(this).next('#select option:first').val();
var thelast = jQuery(this).next('#select option:last').val();
if( jQuery(this).is(':checked') )
jQuery(this).next('#select').val(thelast);
else
jQuery(this).next('#select').val(thefirst);
});
});
.next() gets the next sibling, so you need to get the select and use .find() or .children() afterwards:
var thefirst = jQuery(this).next('#select').find('option:first').val();
var thelast = jQuery(this).next('#select').find('option:last').val();
Since IDs must be unique, there's no point in doing something like:
jQuery(this).next('#select option:first')
when
jQuery('#select option:first')
would suffice, plus .next() would fail here since it evaluates the siblings of an element and filters on anything you pass, but your filter is what would cause it to not match anything.
Instead, use:
jQuery(".input").click(function () {
var thefirst = jQuery('#select option:first').val();
var thelast = jQuery('#select option:last').val();
if (jQuery(this).is(':checked')) jQuery('#select').val(thelast);
else jQuery('#select').val(thefirst);
});
jsFiddle example
The vanilla javascript alternative for future viewers
(function () {
"use strict";
var inputs = document.getElementsByClassName('input'), input;
for (var i = 0; input = inputs[i]; i++) {
input.addEventListener('click', function (e) {
e.target.nextElementSibling.lastElementChild.selected = e.target.checked;
e.target.nextElementSibling.firstElementChild.selected = !e.target.checked;
}, false);
}
})();
<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected>-- choose --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>

Setting index of select elements across a class

I am making a form that has various select elements like this
<select class="nace">
<option value="no" selected="selected">No</option>
<option value="yes">Yes</option>
</select>
I am trying to write a jQuery snippet that will change the selection of all these selects of the class "nace", so the slected values are all in unison. But I am struggling a bit with the functionality.
So far I have an event bound to a the changes on selects but cant quite get it right. Can anyone help me?
$('.nace').change(function() {
var selected = $(this).val();
$('.nace option:selected="selected"' ).each(function(){
$(this+' option[value='+$(this).value+']').attr('selected', 'selected');
});
});
I would have said just this:
$(document).ready(function() {
$('.nace').change(function() {
var selected = $(this).val();
$('.nace' ).val(selected);
});
});
Try this
JAVACSRIPT
$('.nace').change(function() {
var selected = $(this).val();
$('.nace' ).each(function(){
$(this).val(selected);
});
});
HTML
<select class="nace">
<option value="no" selected="selected">No</option>
<option value="yes">Yes</option>
</select>
<select class="nace">
<option value="no" selected="selected">No</option>
<option value="yes">Yes</option>
</select>
<select class="nace">
<option value="no" selected="selected">No</option>
<option value="yes">Yes</option>
</select>
Example here
http://jsfiddle.net/FwYmf/
This should be sufficient:
var $nace = $('.nace').change(function() {
$nace.val($(this).val());
// or (but not necessary) $nace.not(this).val($(this).val());
});
OT: If your select field has only two options, consider using radio buttons.

Categories