Reputation:
I try to load in content to a div in Intex based on choice in a select box. It dont work so something is wrong. I made an example of four pages to show basicly how it is:
Index.html
one.html
two.html
three.html
In Index I have a select element with ID "selectchoice":
<select id="selectchoice>
<option>Select a choice</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
I also have a div in Index with id "get_content":
<div id="get_content"></div>
When I change the select element to option 1 or 2 or 3 I want to load one.html or two.html or three.html into the div get_content.
Then I place this code in the header if Index.html, after the jQuery-file link.
<script>
$("#selectchoice").change(function(){
$("#get_content").load("");
$("#get_content").load("one.html");
$("#get_content").load("two.html");
$("#get_content").load("three.html");
});
And then I run the site (on a server with other load-scripts thats works on the same site), but its not working. What is wrong? :/
Kinda new to scrips and programming so do not be suprised if there is any standard error.
Anybody finding the error?
Upvotes: 2
Views: 1036
Reputation: 7618
Your select
tag is not closed properly. Add "
after your id to close the id attribute.
It'll then look like this:
<select id="selectchoice">
...
Try replacing your javascript with this:
$(document).ready(function (){
$("#selectchoice").change(function(){
var selectedOption = $('#selectchoice :selected').val();
$containerDiv = $('#get_content');
$containerDiv.html("");
switch (selectedOption)
{
case "1":
$containerDiv.load( "one.html" );
break;
case "2":
$containerDiv.load( "two.html" );
break;
case "3":
$containerDiv.load( "three.html" );
break;
default:
$containerDiv.load( "whatever.html" );
break;
}
return true;
});
});
$(document).ready(...)
makes the code execute once the page is loaded, which means it'll bind the function to the onChange event right when you will load the page, while before it wouldn't execute the script since it wasn't called anywhere.
This code respects most of the Object Calisthenics practices. I cut myself some loose since it is only a small snippet.
Upvotes: 0
Reputation: 15220
first the select tag's id attribute should be closed, and the your javascript function should be optiomized. Something like
<script>
$("#selectchoice").change(function(){
var page = this.selectedIndex;
if(page == 1) {
$("#get_content").load("one.html");
return;
}
else if(page == 2) {
$("#get_content").load("two.html");
return;
}
....
});
Upvotes: 3
Reputation: 752
$(function(){ // do it after page load
$("#selectchoice").change(function(e){
if(e.target.value=="select a choice"){ // you can use switch instead of if
$("#get_content").load("");
}else if(e.target.value=="1"){
$("#get_content").load("one.html");
}
//....
});
Upvotes: 0