Javascript - show TextField when select choice is - javascript

I'm new in JavaScript and I have following issue.
In my HTML code is ordinary SELECT
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
I need to show TextFied under the SELECT only when user select choice Audi.
<input type="text" name="something">
What is the best way to do that?

Start using JQuery (JQuery).
Here is the javascript:
$(document).ready(function(){
// On Select option changed
$("#someId").change(function(){
// Check if current value is "audi"
if($(this).val() === "audi"){
// Show input field
$("#textInputId").show(); //This changes display to block
}else{
// Hide input field
$("#textInputId").hide();
}
});
});
Here is the HTML
<select id="someId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="text" style="display:none;" id="textInputId" name="someName"/>
Here is the example on JSFiddle:
EXAMPLE

Do this:
<select id="select">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="hidden" id="txt" name="something">
And do something like this:
select.onchange=function(){
if(select.value=="audi"){
txt.type="text";
}
}
Demo:http://jsfiddle.net/943xQ/

you can achieve it easily using jquery like this:
here is the Html:
<select id="cars">
<option value="-1">Select One</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
and text field:
<input type="text" name="something" id="txtCar" style="display:none;">
$('select#cars').change(function(){
if($(this).val() == "audi")
{
$('input#txtCar').show();
}
});
Here is the DEMO

Place this at the bottom of the page (provided you already have included jquery into this page):
<script>
$('select').change(function () {
if ($(this).val() == 'audi') {
$(this).parent().append('<input type="hidden" name="something">');
}
});
</script>

You can attach the onchange event at select tag and can perform the action you want. Something like
HTML
<div id="result">
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
JS
var select = document.getElementById("mySelect");
select.addEventListener("change", function() {
if(this.options[this.selectedIndex].value == 'audi'){
var input = document.createElement('input');
input.type="text";
input.id="txt";
input.name="something";
document.getElementById('result').appendChild(input);
}
});
DEMO

Given the posted HTML, in which you use no specific identifiers (class or id) to identify the relevant elements, and given that you've not specified the availability of any JavaScript library, I'd suggest the following 'plain' JavaScript solution:
function showInputWhen(evt,val){
var el = evt.target;
el.nextElementSibling.style.display = el.value.toLowerCase() == val.toLowerCase() ? 'inline-block' : 'none';
};
var selectEl = document.querySelector('select');
selectEl.addEventListener('change', function(e){
showInputWhen(e,'audi');
});
JS Fiddle demo.
References:
ChildNode.nextElementSibling compatibility.
document.querySelector() compatibility.
EventTarget.addEventListener() compatibility.

Related

How to force a select to keep always the same selected value

Let's say we have multiple forms, each form has 40 selects, the ids of each select have the following structure:
#id_form-X-{field_name}
Let's say for example, of those 40 selects, we want 3 of them to be unmodifiable for each form when we change the value of the select, so it will always show the same selected value.
The 3 selects we want to change have the following field_name: ps2_0, ps2_1 and ps2_3.
So I'm looking for a generic solution that works for:
id_form-0-ps2_0
id_form-0-ps2_1
id_form-0-ps2_3
id_form-1-ps2_0
id_form-1-ps2_1
id_form-1-ps2_3
id_form-N-ps2_0
id_form-N-ps2_1
id_form-N-ps2_3
...
...
...
Dummy example:
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
If, for example, the user clicks on the select and selects, for example Saab, the select will show again the value selected by default: Volvo.
I cannot use the 'readonly' or 'disabled' properties for the selects.
What I've tried so far:
$(document).ready(function() {
var previous = "initial prev value";
$("select").on('click', function () {
previous = $(this).val();
}).change(function() {
$(this).val() = previous;
});
});
I'm trying to 'force' the changed select to keep the previous value but didn't work.
Simple Solution
Reset the value of select with initial value on change.
const selectDD = document.getElementById('cars');
const selectedNode = selectDD.value;
selectDD.onchange = (e) => {
selectDD.value = selectedNode;
}
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Much Generic Solution
There should be some unique identifier to differentiate between nodes that can be changed and those to be kept unchanged. Here I have added an unchanged custom attribute to select. Pick thode nodes with that custom attribute and on change of that select, reset its value to initial value.
Example
const selectDD = document.querySelectorAll('[unchanged]');
selectDD.forEach((node) => {
node.attributes.initialValue = node.value;
node.onchange = (e) => {
e.target.value = node.attributes.initialValue;
}
})
You cant change this
<select name="cars" id="cars" unchanged>
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
You cant change this
<select name="gender" id="gender" unchanged>
<option selected value="male">Male</option>
<option value="female">female</option>
</select>
<br/>
You can change this
<select name="age" id="age">
<option selected value="10">10</option>
<option value="15">15</option>
</select>
If you use querySelectorAll to generate a nodelist of all the select menus you could assign a default attribute( using dataset here for instance) and set the value within an event listener so that this default attribute is always selected
document.querySelectorAll('form select').forEach( sel => {
sel.dataset.def=sel.options[sel.selectedIndex].value;
sel.addEventListener('change',function(e){
this.value=this.dataset.def
})
})
<form>
<select name='cars'>
<option selected value='volvo'>Volvo
<option value='saab'>Saab
<option value='mercedes'>Mercedes
<option value='audi'>Audi
</select>
<select name='fruit'>
<option selected value='apple'>Apple
<option value='banana'>Banana
<option value='mango'>Mango
<option value='plum'>Plum
</select>
</form>
Maintain an object which specifies the restricted Select items and the indexes they should always defaults to
let allowedIndexes = {
cars: 0,
bikes: 1
}
function preventChange(e) {
if (Object.keys(allowedIndexes).includes(e.currentTarget.id)) {
let fixedIndex = allowedIndexes[e.currentTarget.id];
e.currentTarget.selectedIndex = fixedIndex;
}
}
<select name="cars" id="cars" onChange="preventChange(event)">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select name="bikes" id="bikes" onChange="preventChange(event)">
<option value="honda">honda</option>
<option selected value="kavasaki">kavasaki</option>
<option value="suzuki">suzuki</option>
<option value="yamaha">yamaha</option>
</select>
It's somewhat uncomfortable when one's answer is copied.

How to unselect options in select using jquery

Below is my HTML. I have given multiple option elements in the select tag.
<select class="car" multiple size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I am able to multi-select by holding the CTRL key. I am able to retrieve the selected values using the following jQuery
$.each($(".car option:selected"), function() {
countries.push($(this).val());
});
How can I unselect the value using jQuery? The selected value will be highlighted as shown:
Thanks in advance
Set the selected property to false: $(selector).prop('selected', false).
I have added a button and attached a click event to be able to demonstrate.
var countries = [];
function unselect() {
$.each($(".car option:selected"), function () {
countries.push($(this).val());
$(this).prop('selected', false); // <-- HERE
});
}
$("#unselect").click(unselect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="car" multiple size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input type="button" value="unselect" id="unselect" />
You can use $('.car').val([]); for unselect all options in multi-select dropdown.
For multi select value you can pass empty array for unselect all
options.
$(document).ready(function(){
$("#select").click(function(){
var values= [];
$(".car > option").each(function(){
values.push($(this).attr('value'));
});
$('.car').val(values);
});
$("#unselect").click(function(){
$('.car').val([]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select class="car" multiple size="3">
<option value="volvo" selected>Volvo</option>
<option value="saab" selected>Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button id="select">Select All</button>
<button id="unselect">Unselect All</button>
</button>

iterate through select dropdowns with same class name to find selection of specific option [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to search through a select boxes with same class name, to discover if anyone has selected a specific option...
<select class='myclass' id='instance1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance2'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance3'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<script>
$('.myclass').each(function(i, obj) {
// if anyone wants an audi, let me know
if (something == 'audi')
alert("found!");
});
Simply take all selected options with :selected pseudo, and filter them by value. This is cool and clean one liner.
$('.myclass option:selected').filter("[value=audi]")
Afterwards, you can grab this in a variable, and check if length > 0. (so you have a selected audi option).
This way:
$('.myclass').each(function(i, obj) {
// if anyone wants an audi, let me know
if (obj.value() == 'audi')
alert("found!");
});
you may need to use the JS code in a function though :)
$('#check').click(function(){
$('.myclass').each(function(i, obj) {
// if anyone wants an audi, let me know
if (obj.value== 'audi'){
alert("found!");
}else{
alert('Not found');
}
});});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="check">Check</button>
<select class='myclass' id='instance1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance2'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select class='myclass' id='instance3'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You will need a button to handle the detection or alternatively you can bind to the select change event handler and handle the newly selected option.
To achieve it via a button click, add the following to your HTML.
<button id="checkSelected">Check for Audi</button>
And then in your JavaScript/jQuery code:
$("#checkSelected").on("click", function() {
$("select[class='myclass'] option:selected").each(function() {
var element = $(this);
if (element.val() === "audi") {
alert('The user has selected an Audi in combobox ' + element.parent().attr("id"));
}
});
});
This will transverse the DOM and select all selected elements for the comboboxes with the class myclass and check if the value is equal to audi and alert the user which box they selected it from.
http://jsfiddle.net/0w0v06et/

Javascript code is not working

How can I amend the code so that when I select a option from the first drop down menu the second drop down menu becomes editable otherwise the second drop-down menu should be read only, and if the option in the first drop down menu is "default" then the second drop down menu should be read only.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function mySecondFunction() {
document.getElementById("mySelection").disabled = false;
}
</script>
</head>
<body>
<form action="">
<select name="cars" onload="mySecondFunction()">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<select disabled name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
</body>
</html>
Look at the capitals:
document.getElementById("MySelection").disabled = false;
<select disabled name="cars" id="mySelection">
The first is with "M" and the seccond with "m"
You have misspelled MySelection with mySelection
In the JS you have document.getElementById("MySelection") // notice the uppercase M
and in the HTML you have id="mySelection"
Also set the second select to false when the window loads and add a onChange event to the first select that will set the second event to enabled/true... it this what you want?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function(){
document.getElementById("mySelection").disabled = true;
};
function mySecondFunction() {
document.getElementById("mySelection").disabled = false;
}
</script>
</head>
<body>
<form action="">
<select name="cars" onchange="mySecondFunction()">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<select name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
</body>
</html>
You may want to set the second select back to disabled if the user selects 'default' in the first menu after changing the value
JavaScript selectors are case sensitive. Your mistake is at mySelection id:
document.getElementById("MySelection").disabled = false;
<select disabled name="cars" id="mySelection">
You must use that inside body tag .
fiddle
<head>
</head>
<body onload="mySecondFunction()">
<form action="">
<select name="cars" >
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br>
<select disabled name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
</body>
<script type="text/javascript">
function mySecondFunction() {
alert("aaa");
document.getElementById("mySelection").disabled = false;
}
</script>
</html>
As others pointed out you mispelled the id of the second <select> but also you used the wrong event, onchange is what you want instead of onload.
function mySecondFunction() {
document.getElementById('mySelection').disabled = false;
}
<form action="">
<select name="cars" onchange="mySecondFunction();">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br />
<select disabled="disabled" name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
But consider using jQuery and attach your events in javascript instead of having them stored in html.
Try this:
Replace
document.getElementById("mySelection").disabled = false;
with this
document.getElementById("mySelection").removeAttribute('disabled');
Also, you may want to change
onload="mySecondFunction()"
with this:
onchange="mySecondFunction()"
Hope this helps.
Change onload to onchange.
<select name="cars" onchange="mySecondFunction();">
if you want to remove the disable in a specific value like (Saab)
See fiddle
note: put the script in b4 the head tag
function mySecondFunction()
{
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "saab")
{
document.getElementById("mySelection").disabled = false;
}else {
document.getElementById("mySelection").disabled = true;
}
}
<form action="">
<select id="1" name="cars" onchange="mySecondFunction()">
<option value="default">default</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br />
<select disabled="disabled" name="cars" id="mySelection">
<option value="Action1">Volvo</option>
<option value="Action2">Saab</option>
<option value="Action3">Fiat</option>
<option value="Action4">Audi</option>
</select>
</form>
UPDATE
See fiddle
function mySecondFunction()
{
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "default")
{
document.getElementById("mySelection").disabled = true;
}else {
document.getElementById("mySelection").disabled = false;
}
}

jQuery fire event on all dropdowns with specific class

I've got a load of dropdowns on a html page and I want to fire events when they change (eventually it'll be updating all of the dropdowns with content through ajax) - but for now i'm just trying to make it alert out the data element i've selected. I don't want it to fire on every drop down on the page, just the ones with the corresponding css class. I.e. group1 group2. The groups will have to be dynamic too as I don't know how many there could be.
http://jsfiddle.net/6BakA/
Theres a js fiddle above with how it is at the moment. I expect it to only alert 4 times the when you change one of the first 4 dropdowns and only twice when you do the second. But clearly i'm doing something wrong!
My html is:
<select id="test1" class="group1" data-type="Select Box 1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group1" data-type="Select Box 4">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group2" data-type="Select Box 5">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="test1" class="group2" data-type="Select Box 6">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
My JS is:
$(document).ready(function() {
$('select').change(function() {
$('.group1').each(function() {
alert($(this).data('type'));
});
$('.group2').each(function() {
alert($(this).data('type'));
});
});
});
You can do it like this
$(document).ready(function() {
$('select').change(function() { // <-- bind events to all selects
$('.'+$(this).attr('class')).each(function(){ // <-- iterate through each element that has same class
// you don't need to know the class - just use the current element's class that triggered the event
alert($(this).data('type'));
// do what you need to here
});
});
});​
http://jsfiddle.net/wirey00/6BakA/4/
Or even better since you don't know how many selects there'll be, delegating the event will be more efficient since the parent element will be listening and handling the event. You can replace body with any parent element of the select boxes that's available when the dom is loaded
$('body').on('change','select',function(){
$('.'+$(this).attr('class')).each(function(){
alert($(this).data('type'));
// do what you need to here
});
});
http://jsfiddle.net/wirey00/6BakA/5/
You should do it like this:
$(document).ready(function() {
$('select.group1').change(function() {
$('.group1').each(function() {
alert($(this).data('type'));
});
});
$('select.group2').change(function() {
$('.group2').each(function() {
alert($(this).data('type'));
});
});
});

Categories

Resources