Getting a Select Value after appending - javascript

This is for javascript and jquery.
I have in my body...
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<script>
$("select").change(function () {
functionLoadOpt2() }).trigger("change" );
</script>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
As we see above, the web page has 2 select boxes and a button. Depending on what you select in the first select box loads what is in the second one, using the functionLoadOpt2 function locating higher up in my code.
if (result == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
...
There is more but it follows the same code different values.
Result is the following, above the if statement(just a row up),
var result = (document.getElementById('option1_select').value);
now on the button click, the function changePage() runs,
and all I want is ...
var result = (document.getElementById('option1_select').value);
var result2= (document.getElementById('option2_select').value);
Assume they selected and option for both. Result2 doesnt work. I'd imagine because I'm appending it but how would I work around this. So that when I click changePage() I get the selected value of option1_select and option2_select.
functionLoadOpt2:
function functionLoadOpt2(){
var opt1Val = (document.getElementById('option1_select').value);
$("#option2_select").find('option').remove().end().append('<option></option>');
if (opt1Val == "Word1") {
$("#option2_select").append('<option>Letter1</option>');
$("#option2_select").append('<option>Letter2</option>');
$("#option2_select").append('<option>Letter3</option>');
$("#option2_select").append('<option>Letter4</option>');
$("#option2_select").append('<option>Letter5</option>');
}else if (opt1Val == "Word2") {
$("#option2_select").append('<option>Letter3</option>');//they have similar ones in some cases
$("#option2_select").append('<option>Letter6</option>');
$("#option2_select").append('<option>Letter7</option>');
$("#option2_select").append('<option>Letter8</option>');
$("#option2_select").append('<option>Letter9</option>');
$("#option2_select").append('<option>Letter10</option>');
$("#option2_select").append('<option>Letter11</option>');
$("#option2_select").append('<option>Letter12</option>');
$("#option2_select").append('<option>Letter13</option>');
$("#option2_select").append('<option>Letter14</option>');
$("#option2_select").append('<option>Letter15</option>');
$("#option2_select").append('<option>Letter16</option>');
$("#option2_select").append('<option>Letter17</option>');
//this works
}
}

use jQuery to get and set the value of <select> with .val()

Both your select elements have the same id, fix it the it should be fine
<select id="option1_select" name="courseCodeSelectName">
<option></option>
<option>Word1</option>
<option>Word2</option>
</select>
<select id="option2_select" name="courseNumSelectName">
<option></option>
</select>
<button onclick="changePage()">Load Textbook Page!</button>
Demo: Fiddle
Note: You can improve the script a lot by using proper jQuery constructs, like this

Related

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

customize java script function from particular page when that method is used by many pages

I have a drop down like
<select>
<option value="">Select</option>
<option value="1">ABC</option>
<option value="2">DEF</option>
</select>
I have the same select box in more than 10 places in different pages.This is populating through ajax.But when i am calling this from a particular page i need to select ABC by default.But i don't want in remaining places.
I don't want to write the code again in my page.Is there any possibility for this.
Thanks in advance...
It's going to be a very generic answer that you'll have to modify for your needs, but if the select and all other markup is the same on all pages, which is very unlikely, you have to check the URL to see if you're on a certain page.
At the bottom of the page, before </body>, you can do something like :
if ( window.location.href.indexOf('/mysite.html') != -1 ) {
document.getElementsByTagName('select')[0].value = '1';
}
This will set the default value of the first select on the page to 1, and show ABC, if the URL contains mysite.html.
FIDDLE
Here you have another example (with JQuery) taking into account the comment you did about loading your combos with options obtained with ajax: Try if yourself
JQUERY:
var options = "<option value=\"\">Select</option><option value=\"1\">ABC</option><option value=\"2\">DEF</option>";
function test() {
// Populate select with ID destiny 1 without selecting a value
populate("#destiny1", null, options);
// Populate select with ID destiny 2, selecting the value of the first index
populate("#destiny2", 1, options);
}
function populate(destiny, indexOption, options) {
$(destiny).html(options);
if (indexOption != null) {
$(destiny + " option")[indexOption].selected = true;
$(destiny).trigger("change");
}
}
HTML:
<select id="destiny1"></select>
<select id="destiny2"></select>
<input type="button" onclick="test()" value="TEST"></input>

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().

Javascript to hide select box elements not working in IE

Hey, not sure if I'm going about this the right way. I have two different select boxed. What needs to happen is when a certain item in box 1 is selected, certain items in box 2 are hidden. What I have works fine in FF but not in IE....thoughts?
<div>
<label class="form_label">Apparel</label>
<select id="Choices" size="1" style="clear: right;" onchange"changeThis();">
<option value="select">Pick Your Product</option>
<option value="1">choice 1</option>
<option value="2">choice 2/option>
<option value="3">choice 3</option>
</select>
</div>
<div>
<label class="form_label">Size</label>
<select id="Sizes" size="1" style="clear: right;">
<option value="select">Choose Your Size</option>
<option value="SC">Small Child</option>
<option value="IC">Intermediate Child</option>
<option value="MC">Medium Child</option>
</select>
</div>
...
function changeThing(choice)
{
var item = document.getElementById("Choices");
var size = document.getElementById("Sizes");
var selitem = item.options[item.selectedIndex].value;
if(selitem == '2546')
{
for(i=0; i<2; i++)
{
size[i].style.display = 'none';
//alert(size[i]);
}
}
Try using this instead:
http://www.w3schools.com/CSS/pr_class_visibility.asp
It would come out as:
size[i].style.visibility='hidden';
EDIT
Oh, welcome to StackOverflow!
I had the same problem some days ago. IE does not allow the using of visible:hidden or display:none for option element.
You can solve this problem storing the options of select1 in a variable. This variable will have all possible values, so when the value of select1 was changed you can remove all values of select2 and then get the options you need from variable to put into select2.
To summarize:
Store all possible values in a variable
When select1 was changed remove all options of select2
Filter the options(get these values from varible of step1) you need and put into select2
You cannot display:none remove will completely remove it, if you want the user not to choose it use disabled. you could do something like this
function changeThing()
{
var item = document.getElementById("Choices");
var size = document.getElementById("Sizes");
var selitem = item.options[item.selectedIndex].value;
if(selitem == '3')
{
for(i=1; i<2; i++) // filter logic here
{
size[i].disabled = true; //false - to reset
//alert(size[i]);
}
}
size.selectedIndex = 0; // reset the selection so a disabled item may not be selected. }
It depends on how you are firing off the event that calls the changeThing() function. Not sure about IE9, but IE8 and on back has issues with the onChange event. It basically avoids it in IE. You'll have to use onClick instead.
If you are using jQuery to fire the event, the onchange event should work correctly in all browser (even IE). Not sure how other Javascript libraries do it.
You need to remove this options completely to make it work in IE.
size.remove(i);
So you need to store your options in array and load it back when needed.

Select drop down html

I have a main select "main", and a list from 2 till 9, depending the situation, of more selects.
What if I want to change the value in all this secondary selects, with the same value that the main select?. So the main select will change more than 1 select at the same time:
So, I have got the main select:
<select name="main" id="main" onchange="document.getElementById('item').value = document.getElementById('main').value">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
And the next selects are made in php inside a loop, so I will have 2,3,4,5,..,9 selects depending the situation. Each of them with a different name (because I use this name in POST)
<select name=item_".$itemnumber." id="item">
<option value = p>Please Select</option>
<option value = b>BOOK</option>
<option value = d>DVD</option>
</select>
With this I want to have the possibility to select in one time the option for all the selects, but maintaining the possibility to change only some of the selects.
I made it work like that:
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].id == 'item' && theForm[z].id != 'main'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
But I dont know if thats the best way, I heard here that jQuery would be easier, so I would like to know how to make it in jQuery, please.
What I understand is, you have a <select> dropdown, and on change of the text in this one, you want to change the the selection in one or more of other dropdowns on your screen. Am I right?
If this is the case, then you have to have a javascript function and call this in the onchange of the <select>.
In this javascript function, you have to set the selected value of all the dropdowns you want.
If this is not what you want, Can you please rephrase your question and tell us what you exactly you want?
EDIT
function setElement()
{
var selectedValue = document.getElementById("main").value;
selectThisValue(document.getElementById("child1"), selectedValue);
selectThisValue (document.getElementById("child2"), selectedValue);
}
function selectThisValue(selectElement, val)
{
for ( var i = 0; i < selectElement.options.length; i++ )
{
if ( selectElement.options[i].value == val )
{
selectElement.options[i].selected = true;
return;
}
}
}
Call setElement() in your onchange of the main. This function gets the selected item from the main <select> and selects the items in the other dropdowns that have the same value.
You call the selectThisValue function once for every select you need to change.
Change the ids as per your code.
Never put the same id in all the select elements... ID is supposed to be unique for elements in a page.
change your html to look like
<select id="main" class="master">....</select>
<select id="test1" class="child">....</select>
<select id="test2" class="child">....</select>
<select id="test3" class="child">....</select>
<select id="test4" class="child">....</select>
Class attribute for multiple elements can be the same.
Your function needs to be modified to look like this
(i havent tested this, but should work..)
function changeValue(theElement) {
var theForm = theElement.form, z = 0;
for(z=0; z<theForm.length;z++){
if(theForm[z].className == 'child'){
theForm[z].selectedIndex = theElement.selectedIndex;
}
}
}
by the way, do the options inside these select boxes vary? if so, you'll have to match by value rather than index
EDIT: here's the code i wrote later.. modify it to suit your need
<html>
<head><title>select change cascade</title></head>
<body>
<select id="main" class="master"><option value="1">book</option><option value="2">cd</option></select>
<select id="test1" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test2" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test3" class="child"><option value="1">book</option><option value="2">cd</option></select>
<select id="test4" class="child"><option value="1">book</option><option value="2">cd</option></select>
<script type="text/javascript" src="./selectchange.js"></script>
</body>
</html>
and in selectChange.js
var main = document.getElementById("main");
main.onchange = function (){
sels = document.getElementsByTagName("select");
for(z=0; z<sels.length;z++){
if(sels[z].className == 'child'){
sels[z].selectedIndex = this.selectedIndex;
}
}
}
I don't see any question marks.
The only issue I see is that you should use .selectedIndex instead of .value.
jQuery solution:
$(".selectorClass").each(function(index, selectorToUpdate){
selectorToUpdate.selectedIndex = $('#main').selectedIndex;
});
Put this in a function and call that function for onchange.

Categories

Resources