How to save select dropdown menu option in HTML/pure JS? - javascript

Let's say I have this code:
<select id = dropdown-list>
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
The user can select yes or no from a dropdown list. How can I use pure JS/HTML to figure out what the user has selected (and is currently showing in the dropdown list box when the list isn't expanded) so I can use that data elsewhere? The only way I can figure out is if I add an eventListener on each option but I feel there is a better way. I am quite new to JS so I'm not sure. Thank you.

You can use onchange attribute from select element.
<select id="dropdown-list" onchange="onChange(this.value)">
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
and in JS:
function onChange(val) {
// `val` is the value
}

Execute a JavaScript function changeResult when a user changes the selected option of a element:
Flow:
We bind changeRegult using onchange event listener.
When we change the dropdown menu, it calls changeResult function.
Inside the function, we select our dropdown menu using its id property.
After getting the element by id, we can now access all properties.
Here we want to show the value property, so we use document.getElementById("dropdown-list").value.
For more check this link.
function changeResult() {
var x = document.getElementById("dropdown-list").value;
document.getElementById("result").innerHTML = "You selected: " + x;
}
<select id = "dropdown-list" onchange="changeResult()">
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
<p id="result"></p>

You may want to use on change event.
Since you use each I suppose you are using Jquery.
If you have any question just let me know.
$(document).ready(function(){
$('#dropdown-list').on('change',function(){
alert($(this).children('option:selected').val());
})
});
https://jsfiddle.net/u4dz162o/

Related

javascript Trying to copy database generated text in selectbox to textbox

I'm trying to make a chained dropdown that contain continent, region,country, province,city,district, and village, but i'm stuck at country.
my dropdown require me to use the id from database to chain all the dropdown, so to get the text name i usually using this method :
Country :
<select name="loc_country" class="loc_country loc5" id="loc_country" onchange="javacript: var valor2 = this.options[selectedIndex].text; document.getElementById('loc_country_real').value = valor2;">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
However this method doesn't work this time so i try another approach with :
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
and js :
$("#continent").change(function () {
$("#loc_country_real").val($('#loc_country').text());
});
and hoping when my select box with id="continent" changing, the value will update.
And that method also failed because the value given in "loc_country_real" doesn't match with selectbox "loc_country" (e.g.:when i selected europe on the continent selectbox, the loc_country select box will give me a list of european countries but the value in "loc_country_real" will be asian from country)
i need to make the text in "loc_country" and "loc_country_real" match but i have no idea how to do it, please help.
Try this:
Change your select's to have a VALUE matching the text you want E.G:
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">--Select--</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
You can then use document.getElementById('loc_country').value to get the selected option value
// Change `loc_country_real`'s value to match `loc_country` selected option
document.getElementById('loc_country_real').value = document.getElementById('loc_country').value;
Or the jQuery way:
$('#loc_country').change(function(){
$('#loc_country_real').val($('#loc_country').val());
});
Edit since you mentioned you cannot use value:
$('#loc_country').change(function(){
var textOfSelectedOption = $("#loc_country option:selected").text();
$('#loc_country_real').val(textOfSelectedOption);
});

How to build image name/path from two select/option id by Javascript

I'm trying to bulid an image path from two select fields. I have to use the "id"s because "value"s are used already. Unfortunatedly only the second select works. Does anyone have a hint? As you might see I'm not a coder. Could anyone be so kind and help to make the code more elegant/slim?
I use onchange to update the "result1" and "result2" allways when the user alters his selection.
Thanks in advance, Georg
Here is my code:
<script>
function showOptions1(s) {
document.getElementById("result1").innerHTML = "<img src='img/preview/" + s[s.selectedIndex].id;
}
</script>
<script>
function showOptions2(s) {
document.getElementById("result2").innerHTML = s[s.selectedIndex].id + ".jpg'>";
}
</script>
<select onchange="showOptions1(this)" id="my_select1">
<option value="werta" id="1">Text Item 1a</option>
<option value="wertb" id="2">Text Item 1b</option>
</select>
<select onchange="showOptions2(this)" id="my_select2">
<option value="wertc" id="3">Text Item 1c</option>
<option value="wertd" id="4">Text Item 1d</option>
</select>
<span id="result1"></span><span id="result2"></span>
I wouldn't use the onchange event because you want the user to select two things before building the path. So, put another button on the screen called "save image" or something like that. The onclick of this button gets the "value" of each select input and concats them together. You can easily get a handle to the select inputs using jquery by name
var select1 = $("#my_select1");
Now your problem is that you don't want the value. That would be easy. Instead you want the select option and then you want to get the id. You can do that as follows
var my1id = $("#my_select1 option:selected" ).id;
Thanks a lot for your support. Cheers Georg
Finaly I use this code (and stick to onchange because I dont want another button because there are allready three of them):
<script>
var selection01, selection02;
showOptions1 = function(s) {
selection01 = "<img src='img/preview/" + s[ s.selectedIndex ].id;
getResult();
};
showOptions2 = function(s) {
selection02 = s[ s.selectedIndex ].id + ".jpg' width='200px;'>";
getResult();
};
function getResult() {
var total = selection01 + selection02;
console.log( total );
document.getElementById("Image").innerHTML = total;
};
</script>
<select id="select1" onchange="showOptions1(this)">
<option value="" id="01" selected>...</option>
<option value="werta" id="10">Text Item 1a</option>
<option value="wertb" id="20">Text Item 1b</option>
</select>
<select id="select2" onchange="showOptions2(this)">
<option value="" id="02" selected>...</option>
<option value="wertc" id="30">Text Item 1c</option>
<option value="wertd" id="40">Text Item 1d</option>
</select>
<hr><span id="Image"></span>

How pass value of variable from javascript to jsp on same page

I created two combo boxes. when i choose any value from first combo box respectively the values from second combo box should be changed.
i am using String xyz=request.getParameter("combo1") ;
where combo1 is the name or id of the combo box.
thanks in advance
Please frame your question in a way others can understand. And put the code also what you have tried.
Anyways seems like you want to set some value from change event of others, with the simple js function we can do please see the code
<script>
function doChange()
{
var val = document.getElementById("mydropdown").value;
var e = document.getElementById("mydropdown2");
e.innerHTML="";
e.options[e.options.length] = new Option(val, val);
}
</script>
<form>
<select name="mydropdown" id="mydropdown" onchange="doChange()">
<option value="Sample1">Sample1</option>
<option value="Sample2">Sample2</option>
<option value="Sample3">Sample3</option>
</select>
<br/>
<select name="mydropdown2" id="mydropdown2" >
</select>

Hierarchical Select List using jQuery

I have two select list,
Select list 1 contains the Mobile phone brands names
<select name="mobile-phone" class="mobile-phone">
<option value="Select">Select</option>
<option value="Nokia">Nokia</option>
<option value="Samsung">Samsung</option>
<option value="HTC">HTC</option>
<option value="Apple">Apple</option>
</select>
Select list 2 contains the phone type like
<select name="mobile-model" class="mobile-model">
<option value="Select">Select</option>
<option value="Nokia--Lumia-520">Lumia 520</option>
<option value="Nokia--Lumia-620">Lumia 620</option>
<option value="Samsung--Galaxy-s3">Galaxy S3</option>
<option value="Samsung--Galaxy-s4">Galaxy S4</option>
<option value="HTC--hero">Hero</option>
<option value="HTC--one">One</option>
<option value="Apple--iphone4">iPhone 4</option>
<option value="Apple--iphone5">iPhone 5</option>
</select>
My quest is I want to display Select list 2 according to the value users select in Select List 1.
If a user selects Nokia in first selection, then only Lumia phones should be shown in second select list. Like so, for other phones.
When None is selected in First select list, then second select list should not show anything, but still visible without any option (like disabled button).
How can I accomplish this using jQuery?
The JSFiddle I have made from above select list.
I'd suggest:
/* select the select element whose name is "mobile-phone",
assign an event-handler for the 'change' event:
*/
$('select[name="mobile-phone"]').change(function () {
// get the relevant/selected brand-name:
var brand = this.value;
/* find the option elements inside of the select element with
name="mobile-model", enable them all:
*/
$('select[name="mobile-model"] option').prop('disabled', false)
// show them all:
.show()
// filter the collection, to find only those whose value does not start with the brand-name:
.filter(function () {
return !(this.value.indexOf(brand) === 0);
})
// disable those elements:
.prop('disabled', true)
// hide them:
.hide();
});
JS Fiddle demo.
References:
Attribute-starts-with ([attribute^="value"]) selector.
filter().
hide().
prop().
show().
I think you are looking for:
$("#sel2").prop("disabled", true);
$( "#sel1" ).change(function() {
var value = $(this).val();
$("#sel2").prop("disabled", false);
$("#sel2 > option").hide();
$("#sel2 > option[value*='" + value +"']").show();
});
Only I put to selects Id for do the selection by Jquery more easy. Before I disabled the control wating for any selection, and when the first select change only I keep the option that macth with option[value*='" + value +"']".
Live demo here
There is a jQuery plugin that handles this exact case very nicely: http://www.appelsiini.net/projects/chained .
You should consider having two MySQL tables: brand, model. The brand table would just be a list of brands with IDs. The model table would contain a brand column where you input those IDs.
Then you should do a JSON query for the brand selected, and return a select list accordingly.
By doing it this way, you'll have an in depth database that you can call and manipulate in numerous ways.
Alternatively, you could do something like:
$(".mobile-phone").on("change", function(){
var brand = $(this).val();
$("[data-brand]").hide();
$("[data-brand="+brand+"]").show();
});
And do this:
<option data-brand="Nokia" value="...

How to get the id dropdown list on click event

This is my jspPage.
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>
<option id="2">Supervisor</option>
</select>
And here is javascript
function Class(str)
{
alert(str);
}
i want to get the id of Option on onchange Event. Thanks :)
You can do this if you are trying to get the id of the option which has been selected
function Class(str)
{
var select = document.getElementById("class_Teacher");
var option = select.options[select.selectedIndex];
alert(option.id);
}
Your onchange event will look like this. Just remove the .id as that will return the id of the select box itself not the option
onchange="myFunction(this)"
and your javascript function like this, which will alert the ID of the selected option
function myFunction(ele){
alert(ele.options[ele.selectedIndex].id);
}
Broken down ele represents the select box (a dom object). .options accesses the options within the select box. the [] brackets are a way of accessing a specific option. Like an array myArr[1] etc. and ele.selectedIndex returns a number representing the selected option i.e if the first option is chosen - ele.selectedIndex will be equivalent to 0.
HTML (you should use "value" attribute instead of "id")
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
<option id="1" value="ID1">Manager</option>
<option id="2" value="ID2">Supervisor</option>
</select>
JS
var selectElement = document.getElementById("class_Teacher");
selectElement.onchange=function(){
alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
alert(selectElement.selectedIndex); // index starting from 0
alert(selectElement.value); // value of the selected element
};
Fiddle
Use selsectedIndex Property of GetElementByID
<script>
function val() {
d = document.getElementById("select_id").selectedIndex;
alert(d);
}
</script>
<select onchange="val()" id="select_id">

Categories