jquery not getting value from select statement on change - javascript

This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value.
onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen.
my html is:
<select onChange= "getDrop2()" id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
My Javascript is:
function getDrop2(){
var choice = $("#drop1").val()
alert(choice);
}
The output of the alert statement is just blank.

In jQuery, you're better off doing something like:
<select id = "drop1" >
<option value="0">All</option>
<option value="1">Alphabetical</option>
<option value="2">Brewery</option>
<option value="3">Style</option>
</select>
With the following JavaScript:
$(function(){
$('#drop1').change(function() {
var choice = $(this).val();
alert(choice);
}
});
The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.

Although what others have selected is a better approach. My answer is just to tell you why your code is not working
Try this
var choice = $('#drop1 option:selected').val()
Instead of
var choice = $("#drop1").val()

Related

Dropdown in HTML is empty at initialization due to Javascript

I've created in an html webpage a dropdown with four options. It worked well but I realized that when the page was refreshed, the value would reset itself to the first option. Since I wanted the user's choice to be kept in memory, I added a javascript code snippet that I found somewhere.
It works very well, except that at the initialization the default value of the dropdown is an empty field.
I would need the first option to be displayed at initialization.
I guess it's easy but I don't know JavaScript at all. Could you please help?
Here is what the code looks like:
<select name="options" id='dropdown'>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
<!-- The script below helps to keep in memory the dropdown value after the page has been refreshed -->
<script type="text/javascript">
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
</script>
I think you should check if SessionStorage Key exists or not.
I have created working example of your code : https://jsfiddle.net/vieckys/Lwv1n8p7/7/
Here is HTML Markup:
<select name="options" id='dropdown'>
<option value="0" selected>--- select here ---</option>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
and JS Code
let selectedItem = sessionStorage.getItem("SelectedItem");
if (selectedItem) {
$('#dropdown').val(selectedItem);
} else {
$('#dropdown').val(0);
}
$('#dropdown').change(function() {
let dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
Let me know if you face any issue with this.
Based on your scenario, you can explicitly trigger the change event after the value is set for the dropdown using trigger('change') on the select dropdown. This will run the change function and will save the initial value in the sessionStorage. So, add this line of code, $('#dropdown').trigger('change') something like:
<script type = "text/javascript" >
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
$('#dropdown').trigger('change'); // trigger the change explicitly
</script>

make a select dependent with js

I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach

Set HTML attribute value using java Script

I have html drop down list,which has country list. Now I want to set current country as a default value of list. I found the JavaScript code for get country using Geolocation.
My code:
function getCountry(var name) {
if(name==geoip_country_name()) {
return "selected";
}
}
Then I need to set the selected attribute of the option list.
I tried this:
<option value="Sri Lanka" selected="getCountry('sri Lanka')">Sri Lanka</option>
But this is not correct.
Basically I want to set selected attribute value using JavaScript function
How do I do that?
Use the window.onload event, and just set the dropdown's value. Keep in mind that your hard coded country names may differ from the geo service.
<script>
window.onload = function(){
document.getElementById("country").value = geoip_country_name();
}
</script>
<select id="country" name="country">
<option value="Sri Lanka">Sri Lanka</option>
<option value="UK">UK</option>
<option value="USA">USA</option>
<select>
Basically you can do it like this:
<html>
<body>
<select id="country">
<option id="germany" value="Germany">DE</option>
<option id="uk" value="UK">UK</option>
<option id="usa" value="USA">USA</option>
</select>
<script>
var selectedCountry = 'uk'; //getCountry
var index = document.getElementById(selectedCountry).index;
document.getElementById("country").selectedIndex=index;
</script>
Start the script after your select is rendered.
Note, that this example might not be best practice. I'm also not sure if it works in all browsers (Opera works). You might use an appropriate framework like JQuery, Mootools, ...
The selected attribute is not automatically evaluated as JS code. Assuming you have stored the desired country name in the variable country, could try this instead:
var country = "Sri Lanka";
var select = document.getElementById('myselect'); //Change to the ID of your select element
for (var i = 0; i < select.options.length; i++){
if(select.options[i].value == country)
select.selectedIndex = i;
}
If you are using JQuery following line should solve your problem:
$('select').val(geoip_country_name());
If geoip_country_name returns names in lower case, While initializing the select list, value for each option be in lower case.

HTML/JS: Validating value in <selected>-list

I'm really new to this and working on a JavaScript code and I want to see if a dropdownlist has any choosen value. How do i do that?
I tried:
var selectObj = form.document.getElementById('myListId');
var selectInd = selectObj.selectedInd;
and tried:
if(selectInd == "")
to check if it was empty.
What do I need to change to make it work?
Thanks in advance!
A drop-down, by design, always has a value selected. If you just want to leave an empty value first to not choose something for the user, you can simply check if it's value is empty.
document.getElementById("validate").onclick = function() {
if (document.getElementById("foo").value == "")
alert("invalid");
else
alert("valid");
};
Live example
According to comments, this might not work in older versions of IE. Be sure to test it there if you need to support those browsers.
HTML
<select id="myListId">
<option value="">- Select an option-</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Javascript
function checkvalue(){
var selectObj = form.document.getElementById('myListId');
if (selectObj.value != "") {/* DO something */}
}
Now you can execute this function on change of the select box, or when you submit the form, it is up to you.
Try to read this example.
You are trying compare a number (selectObj.selectedIndex) with a string (""), you should write something like this:
var selectObj = document.getElementById('myListId'),
selectInd = selectObj.selectedIndex,
selectedVal = selectObj.options[selectInd].value;
if(selectedVal== "") {
/* do your stuff*/
}
Only to notice: This only would work (detect a value equal to "") with an html like this:
<select id="myListId">
<option value="" selected="selected">Empty value</option>
<option value="1">Non empty value</option>
</select>
Or when the user has been selected the option "Empty value".
EDIT:
Try with this demo. This demo also works in IE7.

javascript function not getting dropdown text

i am using javascript to get the text of selected item from dropdown list.
but i am not getting the text.
i am traversing the dropdown list by name..
my html dropdownlist is as:
<select name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
and my javascript is as:
function div1() {
var select = document.getElementsByName("SomeName");
var result = select.options[select.selectedIndex].text;
alert(result);
}
can you please help me out..
Option 1 - If you're just looking for the value of the selected item, pass it.
<select name="SomeName" onchange="div1(this.value);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(val)
{
alert(val);
}
Option 2 - You could also use the ID as suggested.
<select id="someID" name="SomeName" onchange="div1();">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1()
{
var ddl = document.getElementById("someID");
var selectedText = ddl.options[ddl.selectedIndex].value;
alert(selectedText);
}
Option 3 - You could also pass the object itself...
<select name="SomeName" onchange="div1(this);">
<option value="someVal">A</option>
<option value="someOtherVal">B</option>
<option value="someThirdVal">C</option>
</select>
function div1(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
getElementsByName returns an array of items, so you'd need:
var select = document.getElementsByName("SomeName");
var text = select[0].options[select[0].selectedIndex].text;
alert(text);
Or something along those lines.
Edit: instead of the "[0]" bit of code, you probably want either (a) to loop all items in the "select" if you expect many selects with that name, or (b) give the select an id and use document.getElementById() which returns just 1 item.
The problem with the original snippet posted is that document.getElementsByName() returns an array and not a single element.
To fix the original snippet, instead of:
document.getElementsByName("SomeName"); // returns an array
try:
document.getElementsByName("SomeName")[0]; // returns first element in array
EDIT: While that will get you up and running, please note the other great alternative answers here that avoid getElementsByName().

Categories

Resources