I want to push a selected value into a select/option dropdown - javascript

I want to select a value in a select/option dropdown using javascript only.
Revised
sorry for confusion. Here is revised code.
document.getElementById("sel_activity").value = activity;
This will also work, but is a bit longer..
<select id='sel_activity'>
<option value='CYC'>Cycle Count</option>
<option value='INV'>Inventory Count</option>
<option value='INVDROP'>Inventory Drop off</option>
<option value='INVPICK'>Inventory Pick up</option>
<option value='TRAIN'>Training</option>
</select>
<script type="text/javascript">
var select = 'CYC';
var myselect=document.getElementById("sel_activity")
for (var i=0; i<myselect.options.length; i++){
if (myselect.options[i].value == select)
{
myselect.options[i].selected = true;
}
else
{
myselect.options[i].selected = false;
}
}
</script>

var myselect=document.getElementById("sel_activity")
myselect.options[myselect.options.length]=new Option("text","value");
http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/option.html

using jQuery
$("#sel_activity").val("CYC")
jQuery is a lightweight javasscript library which is very helpful in DOm traveral,event handling and ajax intearactions.
http://jquery.com/
Adding jQuery to your page is simple as adding one line of code in the head section to include the jQuery library
<head>
<script type="text/javascript" src="h ttp://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>

Related

Cannot read property 'selectedIndex' of undefined [duplicate]

I'm a little bit confused about how to get an index of a selected option from a HTML <select> item.
On this page there are two methods described. However, both are always returning -1. Here is my jQuery code:
$(document).ready(function(){
$("#dropDownMenuKategorie").change(function(){
alert($("#dropDownMenuKategorie option:selected").index());
alert($("select[name='dropDownMenuKategorie'] option:selected").index());
});
});
and in html
(...)
<select id="dropDownMenuKategorie">
<option value="gastronomie">Gastronomie</option>
<option value="finanzen">Finanzen</option>
<option value="lebensmittel">Lebensmittel</option>
<option value="gewerbe">Gewerbe</option>
<option value="shopping">Shopping</option>
<option value="bildung">Bildung</option>
</select>
(...)
Why this behavior? Is there any chance that the select is not "ready" at the moment of assigning its change() method? Additionally, changing .index() to .val() is returning the right value, so that's what confuses me even more.
The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.
Just use the selectedIndex property of the DOM element:
alert($("#dropDownMenuKategorie")[0].selectedIndex);
Update:
Since version 1.6 jQuery has the prop method that can be used to read properties:
alert($("#dropDownMenuKategorie").prop('selectedIndex'));
Good way to solve this in Jquery manner
$("#dropDownMenuKategorie option:selected").index()
You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.
var savedIndex = $(selectElement).prop('selectedIndex');
This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:
$(selectElement).prop('selectedIndex', savedIndex);
I have a slightly different solution based on the answer by user167517. In my function I'm using a variable for the id of the select box I'm targeting.
var vOptionSelect = "#productcodeSelect1";
The index is returned with:
$(vOptionSelect).find(":selected").index();
try this
alert(document.getElementById("dropDownMenuKategorie").selectedIndex);
selectedIndex is a JavaScript Select Property. For jQuery you can use this code:
jQuery(document).ready(function($) {
$("#dropDownMenuKategorie").change(function() {
// I personally prefer using console.log(), but if you want you can still go with the alert().
console.log($(this).children('option:selected').index());
});
});
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
Actually just reiterating what has already been stated a little differently:
$("#dropDownMenuKategorie").change(function() {
var Selection = $("#dropDownMenuKategorie option:selected");
alert(Selection.index());
alert(Selection.val());
});
Assume You have jquery loaded. So
HTML :
<select id="dropDownMenuKategorie">
<option value="gastronomie">Gastronomie</option>
<option value="finanzen">Finanzen</option>
<option value="lebensmittel">Lebensmittel</option>
<option value="gewerbe">Gewerbe</option>
<option value="shopping">Shopping</option>
<option value="bildung">Bildung</option>
</select>
JS:
$(document).ready(function(){
$("#dropDownMenuKategorie").change(function(){
var selIndex = $(this).prop('selectedIndex');
var selVal = $("#dropDownMenuKategorie option:selected").val();
var selText = $("#dropDownMenuKategorie option:selected").text();
console.log(selIndex + selVal + selText );
});
});

Javascript onchange not working anymore after upload on public_html

What I want to do
Auto populate a form text field based on what is selected in a form select field.
What I have done so far
The code below is working perfectly fine during development:
STEP 1: I populate array of data
<script type="text/javascript">
var carcolorData = new Array();
carcolorData['Ford'] = 'Blue';
carcolorData['BMW'] = 'Green';
carcolorData['Fiat'] = 'Red';
carcolorData[''] = 'Hello';
</script>
STEP 2: I create a typical html form with a text and select field:
<form>
<select name="cartype" id="cartype" >
<option selected="selected"></option>
<option>Ford</option>
<option>BMW</option>
<option>Fiat</option>
</select>
<input name="carcolor" type="text" id="carcolor" />
</form>
STEP 3: I create a little javascript function to autopopulate onchange:
<script type="text/javascript">
document.form.cartype.onchange = showColor;
function showColor()
{
var obj_sel = document.form.cartype;
document.form.carcolor.value = carcolorData[obj_sel.value];
}
</script>
The problem
Doesn't work anymore after upload on public_html. Whatever I select it displays 'Hello' which is the color corresponding to blank in my example. I am totally lost... The code is correct since it works fine during development phase. Why is it not working anymore after upload on public_html?
Possible reasons
I am thinking of this but I may be far from the truth...
Different versions of IE (?)
Different development parameters (?)
Conflict with other javascript on the same page (?)
The javascript is not positioned correctly in the script (?)
I think it should be
document.forms
not document.form
To get the select "cartype", assume you got only one form, use:
document.forms[0].cartype
Also, are you missing the <form tag before the <select?
Change this
<script type="text/javascript">
document.form.cartype.onchange = showColor;
function showColor()
{
var obj_sel = document.form.cartype;
document.form.carcolor.value = carcolorData[obj_sel.value];
}
</script>
To this :
<script type="text/javascript">
var showColor = function ()
{
var myform = document.form; //maybe change this to match form with an id.
var selected_cartype = myform.cartype.options[myform.cartype.selectedIndex].value; //better do this to get a select value
myform.carcolor.value = carcolorData[selected_cartype];
}
document.form.cartype.onchange = showColor;
</script>
And there is another problem in the HTML : select's options have no value attribute.
<select name="cartype" id="cartype" >
<option selected="selected"></option>
<option>Ford</option>
<option>BMW</option>
<option>Fiat</option>
</select>
To
<select name="cartype" id="cartype" >
<option value="" selected="selected"></option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
<option value="Fiat">Fiat</option>
</select>

Select onchange not calling function in rails 3

I am trying to use a select box to display a number of items. My select tag contains is written like this:
<%= select_tag "number_of_pets", options_for_select(allowed_pets_options, #pet_number_storage), onchange:"show_pet_forms(this.value, #{RecordsHelper::ALLOWED_PETS})" %>
and parses into HTML like this:
<select id="number_of_pets" name="number_of_pets" onchange="show_pet_forms(this.value, 4)">
<option value="1" selected="selected">1 Pet</option>
<option value="2">2 Pets</option>
<option value="3">3 Pets</option>
<option value="4">4 Pets</option>
</select>
In my application.html.erb file, in the head area, I have this javascript:
<script type="text/javascript">
function show_pet_forms(pets_selected, pets_allowed) {
for (var i=1;i<=pets_selected;i++)
{
element_id = "pet-" + i;
document.getElementById(element_id).style.visibility = "visible";
document.getElementById(element_id).style.display = "block";
}
for (var i=(pets_selected+1);i<=pets_allowed;i++)
{
element_id = "pet-" + i;
document.getElementById(element_id).style.visibility = "hidden";
document.getElementById(element_id).style.display = "none";
}
}
</script>
(Originally the javascript was in the coffeescript file, but I moved it while I was trying to figure out what the problem was.
The elements that I am trying to show and hide are these:
<div id="pet-1">
SOME STUFF HERE
</div>
...
<div id="pet-4">
SOME STUFF HERE
</div>
Unfortunately, I dont see any changes when I select one of the options in my select box, and I can't figure out if it is not triggering the event correctly, or if there is something wrong with my javascript (most likely). Where could the error be?
Thanks!
The second for is not hiding the other divs.
for (var i=(pets_selected+1);i<=pets_allowed;i++)
In the above condition you are trying to add pets_selected + 1 which will concatenate than add.
You need to parse it into an integer first, then add.
for (var i=(parseInt(pets_selected)+1);i<=pets_allowed;i++)
See fiddle

Javascript IE innerHTML of <select>

I'm trying to change the innerHTML of a element based on the value of the previous element.
I have the javascript correctly grabbing the current value and everything works correctly in Firefox, Safari, Chrome and Opera. IE is a pain.
sample code:
<form action="soap.php" method="post">
<select name="circuitproduct" id="circuitproduct" onchange="bandwidthfunction();">
<option>Dedicated Voice</option>
<option>Frame Relay</option>
<option>ATM</option>
<option>Dedicated Internet</option>
<option>IP Solutions Private Port</option>
<option>IP Solutions Enhanced Port</option>
<option>Private Line – Domestic</option>
<option>Int’l Private Line</option>
<option>Qwest Metro Private Line (QMPL)</option>
<option>Qwest Metro Ethernet Private Line (QMEPL)</option>
</select><br />
<select name="term" id="term">
<option value="1-Year">1-Year</option>
<option value="2-Year">2-Year</option>
<option value="3-Year">3-Year</option>
</select>
<select id="bandwidth">
</select>
<select id="sublooptype">
</select>
</form>
sample javascript:
function bandwidthfunction() {
var product = document.getElementById('circuitproduct').value;
if (product == 'Dedicated Voice') {
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
}
else if (product == 'Frame Relay') {
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
document.getElementById('sublooptype').innerHTML = ('<option value="Special Access">Special Access</option><option>CO MtPt - Special Access</option><option>CPA Special Access</option>');
}
Well, first of all you have a closing tag for the select that you try to put inside the select element, which makes the code invalid.
Then there might be a problem with how the select element treats it's content. When the HTML code is parsed, the select element doesn't have any child elements, like a regular element does. Instead the options are items in it's options collection.
If you want to change the items in the select element, change the content of it's option collection. I.e. to add items, create option objects using the document.createElement method and add to the collection. Example:
var opt = document.createElement('OPTION');
opt.text = 'Choose me';
opt.value = 42;
document.getElementById('bandwidth').options.add(opt);
You have to remove the "select"-Element and the end of setting the innerHTML-Property. This is not a part of innerHTML. Its the end-tag of the element 'bandwith' itself.
document.getElementById('bandwidth').innerHTML = ('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');
Here's a handy hack I came across that works in both FF and IE as a workaround to the inability to change innerHTML on select elements.
document.getElementById('bandwidth').outerHTML = document.getElementById('bandwidth').outerHTML.replace( document.getElementById('bandwidth').innerHTML + '</select>' , '<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>' + '</select>' );
or as a function for readability:
function swapInnerHTML(objID,newHTML) {
var el=document.getElementById(objID);
el.outerHTML=el.outerHTML.replace(el.innerHTML+'</select>',newHTML+'</select>');
}
I recently came across this problem with IE. I came up with a turnkey solution that works with the following things in mind:
You don't want to use jQuery
Need it to work in IE < 9
You want to append ( not replace the existing options ) string options into an existing select element
The select must be a type of "select-one"
Must wrap selects in their own parent element
We have many landing pages requesting the same information (age, products, country, state etc... ) but with different select options. The implementation I use appends new select options. This was done to allow a custom default option per lading page. One page may have the first option as "select item" another may have "choose one" and so forth.
Select format:
<div> <!-- you MUST wrap the select in a tag without any siblings -->
<select name="age" id="form-age">
<option value="">Choose Age</option>
</select>
</div> <!-- you MUST wrap the select in a tag without any siblings -->
Here is the function to APPEND/ADD values:
function addOptions(el, options){
// checks to make sure element exists and is a select
if(el && el.type === "select-one"){
el.innerHTML = el.innerHTML + options;
el.parentNode.innerHTML = el.outerHTML; // needed for IE
}
}
Now to execute the function pass in the select object and string values:
addOptions(
document.getElementById("form-age"),
'<option value="1">18-25</option><option value="2">26-35</option><option value="3">36-45</option><option value="4">46-55</option><option value="5">56-65</option><option value="6">66-75</option><option value="7">76-85</option><option value="8">86+</option>'
);
This will generate a select with the options passed, even in IE!
<div> <!-- you MUST wrap the select in a tag without any siblings -->
<select name="age" id="form-age">
<option value="">Choose Age</option>
<option value="1">18-25</option><option value="2">26-35</option><option value="3">36-45</option><option value="4">46-55</option><option value="5">56-65</option><option value="6">66-75</option><option value="7">76-85</option><option value="8">86+</option>
</select>
</div> <!-- you MUST wrap the select in a tag without any siblings -->
If you needed the script to REPLACE the values use the following:
function replaceOptions(el, options){
if(el && el.type === "select-one"){
el.innerHTML = options;
el.parentNode.innerHTML = el.outerHTML; // needed for IE
}
}
I hope this helps someone else!
A quick search shows this has been a known bug in IE since at least IE5. You could try to use createElement and make options and append to the select object, or use a library like jQuery and append the html to the node (which must take care of the magic necessary to work in IE).
The real cause of the problem is that due to a DOM parsing/updating problem, IE will not insert child option elements into a select element. Even IE9 still has this problem (later versions not checked).
You have to put the select in a div or span and replace the whole select. Below you will find an example that shows that then IE will play ball as well. Because this innerHTML problem generally occurs when dynamically generating selects, I made an AJAX & PHP example.
The html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chain(ed) select with AJAX and PHP</title>
<style>
select {
min-width: 170px;
}
option.toSelect {
background: yellow;
}
</style>
</head>
<body>
<form action="whatever.php">
<span>
<select id="cities" onchange="getOptions(this.value,'airlinesContainer')">
<option value="">Select a city:</option>
<option value="boston_airlines">Boston</option>
<option value="chicago_airlines" class="toSelect">Chicago</option>
<option value="newyork_airlines">New York</option>
</select>
</span>
<span id="airlinesContainer">
<select>
</select>
</span>
<span id="classesContainer">
<select>
</select>
</span>
</form>
<script>
function getOptions(qValue,containerId) {
var ajaxRequest = new XMLHttpRequest();
if ((qValue == "") || (containerId == "")) {
alert('Invalid selection.');
return;
}
ajaxRequest.onreadystatechange = function() {
if ((ajaxRequest.readyState == 4) && (ajaxRequest.status == 200)) {
document.getElementById(containerId).innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET","getoptions.php?q="+qValue,true);
ajaxRequest.send();
}
</script>
</body>
</html>
.
And the php file, which should be named 'getoptions.php' and should be put in the same folder:
<?php
$q = $_GET['q'];
$chicago_airlines ='
<select id="airlines" onchange="getOptions(this.value,\'classesContainer\')">
<option value="">Select an airline:</option>
<option value="delta_classes">Delta</option>
<option value="klm_classes" class="toSelect">KLM</option>
<option value="united_classes">United Airlines</option>
</select>';
$klm_classes ='
<select id="classes">
<option value="business">World Business Class</option>
<option value="comfort">Economy Comfort</option>
<option value="economy">Economy</option>
</select>';
if ($q == 'chicago_airlines') {
echo $chicago_airlines;
}
elseif ($q == 'klm_classes') {
echo $klm_classes;
}
else {
echo '<select>
<option>Invalid selection</option>
</select>';
}
?>
.
Be sure to select only the options with a yellow background, in this demo.
use Jquery
$('#bandwidth').html('<option value="DS-1">DS-1</option><option value="DS-3">DS-3</option><option value="OC-3">OC-3</option><option value="OC-12">OC-12</option>');

Javascript - onchange within <option>

I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information.
With the help of a few online tutorials, I've managed to get the Javascript to display a hidden div just fine. My problem is I can't seem to localise the event to the Option tag, only the Select tag which is no use really.
At the moment the code looks like (code simplified to aid clarity!):
<select id="transfer_reason" name="transfer_reason onChange="javascript:showDiv('otherdetail');">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
What I would like is if they choose "Other Reason" it then displays the div. Not sure how I achieve this if onChange can't be used with the Option tag!
Any assistance much appreciated :)
Note: Complete beginner when it comes to Javascript, I apologise if this is stupidly simple to achieve!
Setup the onchange event handler for the select box to look at the currently selected index. If the selected index is that of the 'Other Reason' option, then display the message; otherwise, hide the division.
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 2) {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</body>
</html>
Personally, I'd take it a step further and move the JavaScript into an external file and just include it in the header of the page; however, for all intents and purposes, this should help answer your question.
After reading Tom's great response, I realised that if I ever added other options to my form it would break. In my example this is quite likely, because the options can be added/deleted using a php admin panel.
I did a little reading and altered it ever so slightly so that rather than using selectedIndex it uses value instead.
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.value === "Other") {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
Hope this helps someone else in the future!
Tom's answer is elegant, and neatly puts the JS away from the HTML markup. As mentioned, it could be even moved to an external file. However it adds quite much "nonsense" to the code, like multiple anonymous function assignments etc.
If you want quick solution, you can put it all in the onchange() inside the select tag as well. Pick the one you see more fit.
<select id="transfer_reason" name="transfer_reason" onchange="document.getElementById('otherdetail').style.display = (this.selectedIndex === 2) ? 'block' : 'none';">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>

Categories