Change css based in Select option value selected - javascript

I have in one form, one selects with one question that if determined value selected I need to display none the next question. How can I make a jquery code that detects that the user selected a determinated option in select and change the CSS of the page?
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

So as far as I understand with your short description you need to do something based on the value selected by user in select box which we call an event onchange.I am writing a code example for you
<select onchange="somefunction($(this).val())">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script>
function somefunction(value){
if(value == 1){
$("body").css("background-color","red");
}
if(value == 2){
$("body").css("background-color","yellow");
}
}
</script>

Your question is a bit vague, but i think this is what your after:
const value = $('#selectID option[value=""]').prop("selected", true);
if (value....") {
// do css stuff
}
Additionally you can get the value / text like so:
<select id="car_manufacturer">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<script>
const element = document.getElementById("car_manufacturer");
const value = element.options[element.selectedIndex].value;
const text = element.options[element.selectedIndex].text;
</script>
You could extend on the above with a on onchange event on the select element.
<select id="car_manufacturer" onchange="selectManufacturer(this)">
Manipulate CSS:
JavaScript:
document.body.style.backgroundColor = "red";
jQuery:
$("body").css("background-color","red");
Fiddle
onchange example with css manipulation:
http://jsfiddle.net/9L0czmeq/

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 use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

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 - show TextField when select choice is

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.

Using JQuery "select option:first-child" just for an element with a given id?

This code looks at if dropdownlist with 'townid' has an option of Central and then puts Central after the first option at all dropdownlists.
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('select option:first-child');
}
My problem is that:
How can I add it just after dropdownlist that has id of townid? I mean something like:
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('#townid select option:first-child');
}
For example:
<select id=townid>
<option value="5000">AL</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5204">Central</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
After that process they should be seem like:
<select id=townid>
<option value="5000">AL</option>
<option value="5204">Central</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
How can I add it just after dropdownlist that has id of townid?
Okay, I’m gonna assume your HTML looks something like this:
<select id="townid">
<option>
…
</option>
</select>
In that case, you could use:
$('#townid option:contains("Central")').appendTo('#townid option');
If there are multiple option elements inside #townid and you only want to select the first, just change the selector:
$('#townid option:contains("Central")').appendTo('#townid option:first');
In your example, don’t use if (central), use if (central.length) instead.
You just messed up the selector, because #townid IS the select tag.
var central = $('#townid option:contains("Central")');
if(central.length === 1){
central.insertAfter('#townid option:first-child');
}

Categories

Resources