small javascript to output options to a select doesnt work - javascript

Im making a small webpage. The goal is simple. I have a select with a few options; it is planet names; and their sizes are placed in the value bracket of each option. What i want to do is upon selecting an option ( a planet ), a javascript code will take the choice's size, and give new options to another select bracket. So depending on the first select , the second select bracket will be given new options.
The code is simple and ive overwatched it but theres no error.
I just dont get what's not working. Here's the code:
<select id="selectedplanet" name="selectedplanet" onchange="jcab3();">
<?php
while($fetch28a3=mysqli_fetch_array($query28a3)){
echo('<option value="'.$fetch28a3[1].'">'.$fetch28a3[0].'</option>');
}?>
</select><br/>
<p>Location: </p><br/><br/><p>X:</p><select id="locationx" name="locationX"></select><br/><p>Y:</p><select id="locationy" name="locationY"></select>
This is the html/php side. As you can see , I summon a php that fetch some datas from a mysql table. It assign new options on a select bracket. The select has an 'onchange' , which summon the javascript function 'jcab3' upon changing the select . Then here's the javascript:
function jcab3(){
var final2="";
var final3="";
var prima=parseInt(document.getElementById("selectedplanet").value);
for(i31=0;i31<prima;i31++){
final2=final2+'<option value="'+i31+'">'+i31+'</option>';
}
for(i32=0;i32<prima;i32++){
final3=final3+'<option value="'+i32+'">'+i32+'</option>';
}
document.getElementById("locationx").innerHTML=final2;
document.getElementById("locationy").innerHTML=final3;
}
basically, it takes the size of the planet, then give out new options from 0 to the planet's size , and should place these new options under 2 differents select brackets ( 'locationx' and 'locationy'). But , it just doesnt work.
can anyone help ?
thanks

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="myplanet">
<option value="4">Earth</option>
<option value="5">Mars</option>
<option value="6">JUpiter</option>
</select>
<p>X:</p>
<select id="locationx" name="locationX"></select><br/>
<p>Y:</p>
<select id="locationy" name="locationY"></select>
<script>
document.getElementById("myplanet").addEventListener('change', function(){
var e = document.getElementById("myplanet");
var value = e.options[e.selectedIndex].value;
var prima = parseInt( value )
var final2="";
var final3="";
for(i31=0;i31<prima;i31++){
final2=final2+'<option value="'+i31+'">'+i31+'</option>';
}
for(i32=0;i32<prima;i32++){
final3=final3+'<option value="'+i32+'">'+i32+'</option>';
}
document.getElementById("locationx").innerHTML = final2
document.getElementById("locationy").innerHTML = final3
})
</script>
</body>
</html>

How many new <option>s tags are you adding into your <select>s?
Consider that as saying by #Michael Bogwardt in his comment about what innerHTML is doing in javascript?:
However, DOM manipulations using innerHTML are slower and more
failure-prone than manipulations based on individual DOM objects.
Would be better to create your <option>s tags by using element.appendChild() and element.setAttribute() functions. Your code could look like this:
function jcab3(){
var prima=parseInt(document.getElementById("selectedplanet").value);
var x = document.getElementById("locationx");
var y = document.getElementById("locationy");
for(i31=0;i31<prima;i31++){
var option = x.appendChild("OPTION");
option.setAttribute("value", i31);
}
for(i32=0;i32<prima;i32++){
var option = y.appendChild("OPTION");
option.setAttribute("value", i32);
}
}

Related

JavaScript onchange only works for select 3 and "all" but not in between

Not sure why this is happening but my JavaScript to change the number of past events shown isn't working properly. Only the first select option (3) and the last option (all) seem to fire the onchange event. Please look at my code and let me know if I am doing something wrong, I'm PHP person new at js. Also I will have it live on my demo site until I accept an answer: http://aaron-schpitzer.ca/en/events
html(PHP)
echo '<tr><td><table class="invisible"><tr><td>Number Shown: <select id="select" onchange="changePast()"><option value="3">3</option><option value="10">10</option><option value="20">20</option><option value="'.count($pastEvents).'">All</option></select></td></tr></table></td></tr>';
js
<script>
var pastEvents = <?php echo json_encode($pastEvents); ?>;
function changePast(){
var e = document.getElementById("select")
var selected = e.options[e.selectedIndex].value;
var table = document.getElementById("past_events");
if(table!=null){
var innerhtml = "";
for(i=0;i<selected;i++){
innerhtml+='<table class="invisible"><tr><td><img src="/'+pastEvents[i]["banner"]+'" alt="Event Banner"></td></tr><tr><td>'+pastEvents[i]["name"]+'</td></tr></table>';
}
table.innerHTML = innerhtml;
}
}
</script>
I have figured it out, there are only 5 past test events, so if I select a number I need to check if the value is greater than the # of objects and if so then I need to use the object.length. Here is the added code before the for loop:
if(selected>pastEvents.length){
selected = pastEvents.length;
}

Automaticly setting default texts in select dropdown

I have a very simple select dropdown with urls that direct users to respective pages
<select>
<option value="url1">title1 </option>
<option value="url2">title2 </option>
<option value="url3">title3 </option>
.........
</select>
I will have this drop down in all these (url1, url2, url3...) serving for navigation. Would it be possible to set the default text in the selection box based on my urls? Say if I am currently on url2, my default text in the selection box will be title2. I know manually you can just use
<option selected="selected" value="url2">title2</option>
But is there a way I can use javascript to do because I have hundreds of pages? All the urls and titles are stored in an array that I can retrieve.
Thanks for your help!
Assuming you want to match the url in the window location (such as http://www.example.com/some/page.html) with the URL to the page found in your dropdown:
var dropdown = document.getElementById( 'dropdown' );
for ( var i = 0; i < dropdown.childElementCount; ++i ) {
if ( dropdown.children[i].value === document.location.href) {
dropdown.selectedIndex = i;
break;
}
}
Where 'dropdown' contains the ID of your <select> element. Jsfiddle: http://jsfiddle.net/RhZy6/
You should be able to use this:
var path = decodeURIComponent(window.location.pathname.replace(/\/$/, ""));
$("option").each(function () {
var url = $(this).val();
if (path.substring(0, url.length) === url) {
$(this).prop('selected', true);
}
});
Path is the end of the URL. The next block of code loops through the option elements and looks to see if the option value matches the path, and if it does, sets the selected property to true.
You can get the current URL using document.URL and on document ready you can use ,
$("#selectId option[value=" + document.URL + "]").prop('selected', true);
However document.URL contains full path , so you need to truncate the unnecessary part like http:// https:/ , if it is not present in value of select.
And , here is the working fiddle
P.S The Fiddle will work second time only. It is shwoing diffrent URL on first time. Gotta be a JSFiddle personal thing.
Say you have
<form name="MyForm">
<select name="SelectBox1">
<option>One
<option>Two
<option>Three
</select>
.. etc .. rest of form/page ..
then in your javascript code ..
var el=document.forms.MyForm.SelectBox1;
el.selectedIndex=2; // sets option to "Three" in Select box, because first option is number 0, second =1, third = 2 etc
Or to set it to a value use a function like this .. pass in the Select field name and the value it should be
function setSelect(sFieldName, sValue) {
var el=document.getElementsByName(sFieldName)[0] // returns array of all elements with that name so use [0] to get 1st one
for (var i=0;i<el.options.length;
if (el.options[i].value == sValue) { // if they match...
el.selectedIndex=i; // then this should be the default
}
}
call it usiong something like
setSelect("SelectBox1","http://ectetc")

Javascript multiple select boxes

I tried searching for an answer to this for a while, but to no avail.
I'm trying to do a simple online calculator (that calculates some photovoltaic panels energy), but I'm stuck in something simple (I'm new to Javascript although I worked with Flash's ActionScript 3.0 for a while).
What I need done is a html select that defines which other select group appears in the page. Something like this (obviously this doesn't work, just setting an example):
HTML
<html>
<body>
<select id="test1" onclick="checkField()">
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
Javascript
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
//insert code to "echo" the first optional select group
} else {
//insert code to "echo" the second optional select group
}
}
Sorry if its a bit confusing, but I cant really explain all that well.
Here is an example of what I would want, where selecting a option makes the other fields change accordingly: http://www.toshiba.eu/innovation/download_drivers_bios.jsp
you are almost there, actually javascript doesn't "echo" values directly, it does log values using console.log(your value); to a debug console, similar to AS2 trace() if my memory isn't failing.
To "output" information to the document you should have a look into document.write
When you use document.write it will directly write to the documents end.
The "correct" way would be to create a DOM element, with the elements you want inside it, and then append it to the desired element. Have a look at the comments
<!-- Be Aware to use the onchange trigger on select boxes, if you use onclick the function will run, even
if you didn't really chose any option -->
<select id="test1" onchange="checkField()">
<!-- Is good to have a first non-value option, better to trigger the onchange event, if you have
Select A Group as first option and you click on it, it didn't really "Change", you would have to
pick B Group and then A Group again to trigger the onchange event correctly. -->
<option value="">-- select an option --</option>
<!-- You can have a value attribute on the options, so it's easy to process when programming
while displaying a more detailed description to the users -->
<option value="A">Selected A Group</option>
<option value="B">Selected B Group</option>
</select>
<!-- We create an empty element where we are gonna place the new Select -->
<div id="newSelect"></div>
<!-- By Placing the Javascript on the end of <body>, we ensure that all the DOM elements loaded before running the script -->
<script>
function checkField(){
var newSelect = document.getElementById('newSelect'); //targeting container;
var temp = document.getElementById('test1').value;
//Some tasks we do always the option chose is not the first custom one, so we don't have to repeat it
//on the two If's below
if(temp !== ""){
// We remove the select if we placed one already before, so we can add the new one,
// For example if we chose B Group but changed our mind and Chose A Group later.
if(oldChild = newSelect.getElementsByTagName('select')[0]){
oldChild.remove();
}
var select = document.createElement("select");
select.setAttribute('id', 'newSelect');
}
if(temp === "A"){
//you could do JUST:
//body.innerHTML = "all the html you want in here" instead of all the code following;
//but all those code is supposed to be the "correct way" of adding elements to the HTML,
//Google a bit about that for detailed explanations
var option1 = document.createElement("option");
option1.value = 1;
option1.text = "Option 1";
var option2 = document.createElement("option");
option1.value = 2;
option2.text = "Option 2";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
} else {
var option1 = document.createElement("option");
option1.value = 3;
option1.text = "Option 3";
var option2 = document.createElement("option");
option1.value = 4;
option2.text = "Option 4";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
}
}
</script>
Of course there are ways to make this slightly shorter, using loops if your data to ouput has a pattern, but lets do it the "simple" way so you get a grasp of Javascript.
Hope all this helped you!!
Demo here:
http://jsfiddle.net/3GkrX/
Just about the same as Mevins.... changed to switch/case though
html:
<select id="test1" id="name" onchange="checkField()">
<option>----</option>
<option>Selected A Group</option>
<option>Selected B Group</option>
</select>
<div id="optional">Please select!</div>
JS:
function checkField(){
var temp = document.getElementById('test1').value;
switch(temp){
case "Selected A Group":
document.getElementById("optional").innerHTML="<select name='optionalA'><option>1</option><option>2</option></select>";
break;
case "Selected B Group":
document.getElementById("optional").innerHTML="<select name='optionalB'><option>3</option><option>4</option></select>";
break
default:
document.getElementById("optional").innerHTML="Please select!";
break;
}
}
Also added the second group as a real option, and a default as "please select". may or may not be necessary in your case
Here is the demo http://codepen.io/anon/pen/izAHo
your doing it almost right.
You should put the onclick event on the option tag to trigger changes based on the option selected.
HTML
<html>
<body>
<select id="test1">
<option onclick="checkField()">Selected A Group</option>
<option>Selected B Group</option>
</select>
<select id="test2">
<option onclick="check2Field()">Selected C Group</option>
<option>Selected D Group</option>
</select>
<script>//insert second group here</script>
</body>
</html>
JS
function checkField(){
var temp = document.getElementById('test1').value;
if(temp === "Selected A Group"){
document.getElementById('test2').innerHTML="<option>Selected halloooo Group</option>";
} else {
//insert code to "echo" the second optional select group
}
}
Check out my demo for more clarity.

jquery, get value of different select list

I have a lot of select list (hundreds) like this (they have all the same name and id (I think my problem comes from here... but I can't change it):
<select name="custom_element_grid_class" id="custom_element_grid_class" class="select-size">
<option value="normal">normal</option>
<option value="square">square</option>
<option value="wide">wide</option>
<option value="tall">tall</option>
</select>
I want to get value of each list when an user change the value. I made this script but it only works on my fist select list...
jQuery("#custom_element_grid_class").change(function(){
var element = jQuery(this);
var selected = element.find('option:selected');
var size = selected.val();
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class',sclass);
});
How can I make it works for all my select form?
EDIT: each select list comes from an ajx call, that's the reason I've got the same ID, but only in the futur DOM.
You cannot have double ID's.
So my suggestion in calling a function by inline onchange in the select.
For example:
<select name="custom_element_grid_class" id="custom_element_grid_class" onchange="func(this)" class="select-size">
And then your function:
function func(el){
var element = el;
var size = element.value;
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class', sclass);
};
Demo here
I would suggest adding a first option with no value, so that, as you say "when an user change the value" you can read in case he took the first value.
If you can help it avoid duplicate IDs in exchange for classes. If this isn't an option use an attribute selector. Modifying the above code slightly.
Document Ready
$(function()
{
$('[name=custom_element_grid_class]').change(function(){
var $element = $(this);
var size = $element.val();
var sclass = size + " element isotope-item";
$element.closest('.element').attr('class',sclass);
});
});
Fiddle

Dropdown / Select Box Navigation with JavaScript ?

I want to ask quick question, i want to make a select drop down that when i choose one of the options the values of the other select drop down change ...
let's say i have select drop down called model that has the following
- Acura
- Aston martin
- Audi
I want when i choose (let's say ) Audi, in the type select drop down i find Audi type's only
- A3
- A5
- A4
I don't want to use AJAX calls, i just want to use javascript or jquery to filter the data
thanks guys
Like Shomz said,
Assuming the dropdowns look like this:
<!-- First dropdown. Make of car -->
<select name='Manufactor' id='make'>
<option value='null'>Select a Make</option>
<option value='Audi'>Audi</option>
<option value='BMW'>BMW</option>
<option value='Volvo'>Volvo</option>
</select>
<br />
<!-- Second dropdown. Model of car -->
<select name='Model' id='model'>
</select>
The javascript would look like this:
<script type='text/javascript'>
var model = ['','audi','bmw','volvo']; //Set makes
model[1] = ['A3', 'A5', 'A4']; // Set Audi models
model[2] = ['M3', 'M5', 'M6']; // Set BMW models
model[3] = ['C30', 'C70']; // Set Volvo models
var test = model[1][1];
function setModel(index) {
var modelDropdown = document.getElementById('model');
modelDropdown.options.length = null;
for(var i = 0; i < model[index].length; i++) {
modelDropdown.options[i] = new Option(model[index][i]);
}
}
window.onload = function() {
var makeDropdown = document.getElementById('make');
makeDropdown.onchange = function() {
setModel(this.selectedIndex);
}
}
</script>
Notice that the Models start at index 1 and not 0, because the first option is a blank Select Model option.
AJAX calls would still be the best solution, but if you don't want to use them, you can always manually create arrays for each of the main options, make an onchange event on the select element which would call the selected array and create another dropdown based on the elements of that array. Hope I didn't make it sound to complicated, since it isn't.
Here's a sample how to extract values with jQuery.

Categories

Resources