Think I'm making this harder than it need to be. here is my jsfiddle http://jsfiddle.net/justmelat/pArU7/2/
straight html:
<form>
.
<input type="radio" name="sex" value="House">House
<input type="radio" name="sex" value="Cars">Cars
<hr>
<select name="cars">
<option value="0">--Select--</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="wood">Wood</option>
<option value="audi">Audi</option>
<option value="brick">Brick</option>
</select>
</form>
when user selects house, i only want the select, wood and brick options to appear in the dropdown
of course if cars is selected then wood and brick should disappear.
How can I easily do this in javascript?
Demo: http://jsfiddle.net/33tJR/
Just a quick mockup I made, nothing too fancy using jQuery or anything
function createOption(value) {
el = document.createElement('option');
el.value = value;
el.innerHTML = value;
el.id = value;
document.getElementById('select').appendChild(el);
}
document.getElementById('house').addEventListener('click', function() {
document.getElementById('select').innerHTML = '';
createOption('Volvo');
createOption('Saab');
createOption('Fiat');
});
document.getElementById('cars').addEventListener('click', function() {
document.getElementById('select').innerHTML = '';
createOption('Wood');
createOption('Brick')
});
Use the onchange event of radio button and if the value matches to male , call a javascript which will create the option list and clear the exisiting list and append the new one. All these used jquery
$(document).ready(function(){
$("input[name='sex']").change(function() {
if($(this).value === "male") { loadDLLWithOption1(); }
else { loadDLLWithOption2(); }
}
});
function loadDLLWithOption1()
{
var optionList = '<option>option1</option><option>option2</option>';
$("#cars").html(optionList);
}
Related
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>
I have a form with two select fields. The first select field will list items, the second select field will start empty but be populated by selecting an item from the first and pressing the add button. You would also be able to do the same. You can select an item from the second select field and hit the remove to add it back to the first select field. In the end, I want all the values of the second select field to be in a hidden form box separated by commas.
I've come across examples of this with javascript in the past, but now that I need them I can't seem to find them. Does anyone know of any sources that could show me how to accomplish something like this? At first, I was thinking of doing it using ajax but I would rather do it without loading another page. Any help in pointing me in the right direction would be greatly appreciated! Thanks in advance!
<form name="SelectItem">
<select name="SelectItem">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button>Add =></button>
<button><= Remove</button>
<select name="SelectedItems">
<option value=""></option>
</select>
</form>
You can use jquery append() to do it:
$(document).ready(function(){
$('.add').click(function(){
$('#select1').find('option:selected').appendTo('#select2');
});
$('.remove').click(function(){
$('#select2').find('option:selected').appendTo('#select1');
});
});
Working pen
You can use the add() and remove() methods on the select element:
const select1 = document.getElementById('select1')
const select2 = document.getElementById('select2')
const addItem = () => {
event.preventDefault();
if(select1.length === 0) return;
let itemIndex = select1.selectedIndex;
let item = select1.options[itemIndex];
select1.remove(itemIndex)
select2.add(item);
}
const removeItem = () => {
event.preventDefault();
if(select2.length === 0) return;
let itemIndex = select2.selectedIndex;
let item = select2.options[itemIndex];
select2.remove(itemIndex)
select1.add(item);
}
document.getElementById('addButton').addEventListener('click', addItem);
document.getElementById('removeButton').addEventListener('click', removeItem);
<form name="SelectItem">
<select name="SelectItem" id="select1">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="addButton">Add =></button>
<button id="removeButton"><= Remove</button>
<select name="SelectedItems" id="select2">
</select>
</form>
Below is one relatively simple approach you can take that takes advantage of event delegation technique:
const inSelectEl = document.querySelector('#in-item-list');
const outSelectEl = document.querySelector('#out-item-list');
const optionQuantity = inSelectEl.options.length;
const onClick = e => {
if (e.target.tagName !== 'BUTTON') {
return;
}
let a, b;
if (e.target.id === 'add') {
a = inSelectEl;
b = outSelectEl;
} else {
a = outSelectEl;
b = inSelectEl;
}
const selectedOption = a.options[a.selectedIndex];
b.options[b.options.length] = selectedOption;
}
document.querySelector('#container').addEventListener('click', onClick);
<!-- Added container to enable event delegation -->
<div id="container">
<select name="SelectItem" id="in-item-list">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="add">Add =></button>
<button id="remove"><= Remove</button>
<select name="SelectedItems" id="out-item-list" />
</div>
So, I have 2 events attached to several select elements. A click event and a change event. When the user selects an option, I keep track of previously selected options on a JS object to tell the user that the option is already used and can't be reused and reset that select to the default value. If the select had a previous value that is not default, I remove the property from the object. Now, on each click event, I would have a JS variable give me the value of that select before the change happens. But, because of the difference in order of events been trigger (Firefox and Chrome) for example, in one I get the default which was when it reset, and the other I get the value right before the reset.
HTML:
<html>
<head>
<title>Objects test on Browsers</title>
</head>
<body>
<div class="container">
<select name="dd1">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd2">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd3">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
</div>
</body>
</html>
JavaScript:
var alreadyUsed = {};
var prevField = "";
$(function() {
// Events for drop downs
$("select[name^='dd']").on("focus", function(event) {
prevField = $(this).val();
console.log(prevField);
}).on("change", function(event) {
var fieldInUsed = checkNotUsedAlready("fields", $(this).val());
if (fieldInUsed === true) {
delete alreadyUsed[prevField];
$(this).val(0);
} else {
var selectField = $("select[name='" + event.target.name + "']" + " option:selected");
if (selectField.html() != "-Select-") {
alreadyUsed[selectField.html()] = $(this).val();
} else {
delete alreadyUsed[prevField];
}
}
});
});
function checkNotUsedAlready(type, value) {
var fieldColInUse = false;
if (type == "fields") {
for (var prop in alreadyUsed) {
if (alreadyUsed.hasOwnProperty(prop)) {
if (prop == value) {
fieldColInUse = true;
alert("Field is already in use.\nPlease, select a different field.");
break;
}
}
}
} else if (type == "columns") {
for (var prop in alreadyUsed) {
if (alreadyUsed.hasOwnProperty(prop)) {
if (alreadyUsed[prop] == value) {
fieldColInUse = true;
alert("Column is already in use.\nPlease, select a different column or custom.");
break;
}
}
}
}
return fieldColInUse;
}
I select cat on first drop down. Object now is Object{cat:"cat"}
I select dog on second drop down. Object is now Object {cat:"cat", dog:"dog"}
I select cat on second drop down.
At this point, firefox returns me dog as the previous value, which is what I want, but Chrome returns me zero because of the reset and when it set the value because of the events triggering order. Any ideas how can I deal with this in a different way?
One of the reasons for the JS object is that I need to have a list of which values are used to submit later and which are not used yet. A value needs to be unique.
NOTE: Choose cat for Drop down 1, dog for Drop down 2 and bear for Drop Down 3. Then, choose dog from Drop Down 1. On chrome, it will delete bear but on Firefox, it will delete cat.
Thanks in advance.
Maybe it would help to simplify things a bit. This works for me in Chrome, IE 9+, and Firefox:
var alreadyUsed = [];
$(document).ready( function() {
$("select[name^='dd']").data("previous","0");
$("select[name^='dd']").on("change", function(event) {
var newValue = $(this).val();
var prevValue = $(this).data("previous");
if(alreadyUsed.indexOf(newValue) == -1){
if(prevValue != "0") alreadyUsed.splice( alreadyUsed.indexOf(prevValue), 1 );
alreadyUsed.push(newValue);
$(this).data("previous",newValue);
}else{
alert("Field is already in use.\nPlease, select a different field.");
$(this).val(prevValue);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<select name="dd1">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd2">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
<select name="dd3">
<option value="0">-Select-</option>
<option value="cat">cat</option>
<option value="dog">dog</option>
<option value="bear">bear</option>
</select>
<br />
<br />
</div>
You code is a bit more complicated, and obviously does other things, but perhaps this simple working version will help.
I'm trying to make a simple form page have some localstorage functionality to restore settings/input after the page has been closed/reloaded.
I've attempted to make a start but I am still learning so there are mistakes and I can't get it to work.
If a change is made to the name input field it should update the localstorage with the new name.
If a change is made to any of the dropdown (selector? option?) fields it should update the localstorage with the new value.
On page load it should automatically restore all of the values.
The "Clear" button should ONLY reset the dropdown (selector? option?) fields to blank, it should NOT reset the name field.
Example: https://jsfiddle.net/5gam3b6f/
$(document).ready(function () {
$.each($("select"), function (index, value)) {
localStorage.getItem($(this).attr(“id”));
};
});
$("select").on("change", function () {
localStorage.setItem($(this).attr(“id”), $(this));
});
I haven't managed to start on the name input field or the clear function yet because I can't even get the first one to work.
I would rather not use external libraries as this is as complicated as it will get, nothing else needed.
The below will work for you:
Here is a working jsFiddle
jQuery
$('.useLocalSelect').change(function () {
var key = $(this).attr('id');
var value = $(this).val();
localStorage.setItem(key, value)
});
// use a timer for text fields and the like so that localsotrage is set 2 seconds after the user stops typing instead of after each keystroke
var t = '';
$('.useLocalInput').keyup(function () {
clearTimeout(t);
var key = $(this).attr('id');
var value = $(this).val();
t = setTimeout(function () {
localStorage.setItem(key, value)
}, 2000);
});
$('.useLocal').each(function () {
var key = $(this).attr('id');
if (localStorage.getItem(key)) {
$(this).val(localStorage.getItem(key));
}
});
$('.clearLocalSelect').click(function () {
$('.useLocalSelect').each(function () {
$(this).val('');
var key = $(this).attr('id');
localStorage.removeItem(key);
});
});
html
<label style="color: #01ACEE; font: bold 14px Tahoma;">Input
<input class="useLocal useLocalInput" id="testInput" size="40" type="text" name="website" value="" required/>
</label>
<br/>
<br/>
<label style="color: #01ACEE; font: bold 14px Tahoma;">Select</label>
<select class="useLocal useLocalSelect" id="testSelect" name="start_date">
<option value="">Select one...</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">Noember</option>
<option value="December">December</option>
</select>
<br/>
<br/>
<input type="button" class="clearLocalSelect" value="Clear Selects"/>
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.