Send select value to JS function - javascript

I have the next menu in HTML:
<select name="p1">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
Now, I want to send it to my JS function:
function myFunc(menuValue){
//do something
}
How can I do it?

Something like this :
Javascript :
var selectObj = document.querySelector("#selectID"),
displayObj = document.querySelector(".display");
selectObj.onchange = function(evt){
myFunc(this.value);
}
function myFunc(menuValue){
displayObj.innerHTML = menuValue;
}
HTML :
<select id = "selectID" name="p1">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<div class='display'></div>
http://jsfiddle.net/NeekGerd/4H5aq/

So you want to get the value of the selected option onchange of option value right? You can try this way:-
http://jsfiddle.net/T8CKU/
<select name="p1" onchange="myfunc(this.value);">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
function myFunc(menuValue){
alert(menuValue)
}
Here inside myFunc the context of `this would be the window. If you want to get the context inside the window as the dropdown itself you can use apply or call.
<select name="p1" onchange="myFunc.call(this);">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
function myFunc(){
alert(this.value); //This will give the value again.
}

The select element in HTML offers an onchange event that fires if you select a new value (new = an option that was not selected).
<select name="p1" onchange="myFunc(option);">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
function myFunc(option) {
// whatever you need to do
};

Related

How to modify javascript code to keep values from multiple html drop down menus

I have 3 html drop down menu's and I try to keep the values selected after submitting the form
<select name="select_zone" id="select_zone">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
this is the javascript:
<script>
document.getElementById("select_zone").onchange = function() {
localStorage['select_zone'] = document.getElementById("select_zone").value;
}
window.onload= function(){
if(localStorage['select_zone'])
document.getElementById("select_zone").value = localStorage['select_zone'];
}
</script>
This works, but the problem is that if I copy the code 2 more times for the other drop down menus, only 1 menu at a time keep the values.
How would you change the js code so that all menu's keep the values?
You have to give 3 different ids, something like that (not tested):
<select name="select_zone_1" id="select_zone_1">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select name="select_zone_2" id="select_zone_2">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select name="select_zone_3" id="select_zone_3">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
Javascript:
for (let i = 1; i <= 3; i++) {
let id = `select_zone_${i}`;
document.getElementById(id).onchange = function() {
localStorage[id] = document.getElementById(id).value;
}
window.onload = function() {
if (localStorage[id]) {
document.getElementById(id).value = localStorage[id];
}
}
}
You can remove the name attribute if you don't need it elsewhere.
EDIT
In order to be more reliable, you can try this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<select class="storable" id="select_zone_1">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select class="storable" id="select_zone_2">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select class="storable" id="select_zone_3">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<script>
function getStorableElements() {
return document.querySelectorAll('.storable');
}
for (const element of getStorableElements()) {
element.onchange = () => localStorage[element.id] = element.value;
}
window.onload = () => {
for (const element of getStorableElements()) {
const id = element.id;
if (localStorage[id]) {
element.value = localStorage[id];
}
}
}
</script>
</body>
</html>

Get pre-selected value of an HTML select element

Or through example, how can one retrieve "c" via JavaScript or jQuery no matter if the user changed it?
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
I tried the following, however, it returns the value of the currently selected menu. I suppose I can take a similar approach which runs upon page load and save the value, but expect there is a more "proper" way to do so.
$('#select-menu > option').each(function(i){
if(this.selected) {
console.log(this.value)
$("#submit").val(this.value);
return false;
}
})
Use jQuery .attr() to get initial value:
function get_initial(){
$('#select-menu > option').each(function(i){
if($(this).attr('selected')) {
console.log('initial: ' + this.value)
}
if(this.selected) {
console.log('current: ' + this.value)
}
})
}
$('.initial').on('click', get_initial);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
<button class="initial">check initial</button>
There is no better way. A select is meant to be user-modifiable.
If you want to retain the original value you could save it on load:
$(document).ready(function() {
var initialValue = $("#select-menu").val();
});
You could also write it in a hidden input:
<input type="hidden" name="initial-select-menu" value="c">
This way has the benefit that the value will be submitted along with the rest of the form. Might be preferable in some cases.
Or you could stuff that initial value in a data attribute:
<select id="select-menu" data-initial="c">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
You could save the value on an html5 data-* attribute:
<select id="select-menu" data-default="c">
And get it with
$("#select-menu").attr("data-default");
The following code exhibits various examples related to getting of values from select fields using JavaScript.
Working Snippet
const selectMenu = document.getElementById("select-menu");
var selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
/*Option 1*/
selectMenu.onchange = function() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}
/*Option 2*/
/*selectMenu.addEventListener("change", function(){
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
})*/
/*Option 3*/
/*function updateSelectedIndex() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}*/
document.writeln(selectedIndex);
<!-- Option 3 -->
<!-- <select id="select-menu" onchange="updateSelectedIndex"> -->
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
Try this for the appropriate cases:
let preselectedOption = $(targetDropDown).find('option[selected]');
let currentOption = $(targetDropDown).find('option:selected');

How to use if statement if you have three drop down selected values using javascript and html

I have three drop down selected values as you can see below.
How can I say for example if car = volvo and color = Black and name = Jone // do something or alert (cool) in JavaScript?
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<select>
<option value="red">red</option>
<option value="blue">blue</option>
<option value="black">black</option>
<option value="green">green</option>
</select>
<select>
<option value="'mark">'mark</option>
<option value="jones">jones</option>
<option value="james">james</option>
<option value="Vardy">Vardy</option>
</select>
It would have been very easy with angular js by two way binding and applying same valuechange listener on all the three dropdowns.
However, here also you can provide 3 different ids to your dropdowns and bind them with same value-change listener using onchange attribute.
In the value-change listener function , get the value of all the 3 drop down value by document.getElementById , comapre them and display alert accordingly. You can find below the sample solution for it which I prepared:
<head>
<script>
function dropdownChange() {
var car=document.getElementById("car").value;
var color=document.getElementById("color").value;
var owner=document.getElementById("owner").value;
if(car==="volvo" && color==="red" && owner ==="james") {
alert("Cool");
}
}
</script>
</head>
<body>
<select id ="car" onchange="dropdownChange();">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<select id="color" onchange="dropdownChange();">
<option value="red">red</option>
<option value="blue">blue</option>
<option value="black">black</option>
<option value="green">green</option>
</select>
<select id="owner" onchange="dropdownChange();">
<option value="'mark">'mark</option>
<option value="jones">jones</option>
<option value="james">james</option>
<option value="Vardy">Vardy</option>
</select>
</body>

combobox jquery onchange event

How i update combobox based on another combobox, i have this code but its not work, can someone help me. Thanks
<select name="marca" id="marca" onchange="javascript:carregaModelos(this.value)" >
<option th:each="marca : ${marcas}"
th:value="${marca.idmarca}"
th:text="${marca.nomemarca}">Marca</option>
</select>
<select name="modelo" id="modelo">
<option th:each="modelo : ${modelos}"
th:value="${idmodelo}"
th:text="${nomemodelo}">Modelo</option>
</select>
<script type="text/javascript">
function carregaModelos(marca) {
var opcao = $(this).('#marca option')
console.log(opcao);
jQuery("#modelo").load( "pesquisa/" + opcao);
return false;
}
and this
#RequestMapping("/pesquisa/{idmarca}")
public String pesquisa(ModelMap model, #PathVariable Long idmarca) {
model.addAttribute("modelo", service.obterModelosByMarcas(idmarca));
return "index";
Add an attribute with value to target element.
data-target-sync="#targetElementId"
The value is jQuery selector so # included with ID of target element
$(document).ready(function() {
$('[data-target-sync]').change(function() {
var cur = $(this);
$(cur.attr('data-target-sync')).val(cur.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="marca" id="marca" data-target-sync="#modelo">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select name="modelo" data-target-sync="#marca" id="modelo">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>

How can I get the value select name

I´m now beginning with programming and I need to know what text would be the value of this code. The JS code would be an "on click" event from this unfoldable list. Thanks you in advance!!
<select name="select1" data-dojo-type="dijit/form/Select">
<option value="Artesania">Artesania</option>
<option value="Banco" selected="selected">Banco</option>
<option value="Bar">Bar</option>
<option value="Bodega">Bodega</option>
<option value="Boutique">Boutique</option>
<option value="Discoteca">Discoteca</option>
var selectbox = document.getElementById('select');
selectbox.addEventListener('change', function(){
console.log(this.value);
//do whatever you want with the value
});
<select name="select1" data-dojo-type="dijit/form/Select" id='select'>
<option value="Artesania">Artesania</option>
<option value="Banco" selected="selected">Banco</option>
<option value="Bar">Bar</option>
<option value="Bodega">Bodega</option>
<option value="Boutique">Boutique</option>
<option value="Discoteca">Discoteca</option>
</select>

Categories

Resources