Reputation: 1301
I am basically a newbie with javascript. I want to populate a div in my webpage from a select form found on the same page, when the user selects the book and chapter he wants to view and presses the submit button. Here the code:
<script type="text/javascript" charset="utf-8">
var setArray = newArray(
bk1, 001, "this is my chapter content for the <div>",
bk1, 002, "this is my chapter content for the <div>",
bk1, 003, "this is my chapter content for the <div>",
bk2, 001, "this is my chapter content for the <div>",
bk2, 002, "this is my chapter content for the <div>"
etc....
);
</script>
<form>
<select id="book">
<option value="">Select Book</option>
<option value="bk1">Book 1</option>
<option value="bk2">Book 2</option>
<option value="bk3">Book 3</option>
</select>
<select id="chapter">
<option value="">Select Chapter</option>
<option value="001">1</option>
<option value="002">2</option>
<option value="003">3</option>
</select>
<button id="button" type="submit">View</button>
</form>
<div id="content">
I want the content from the js array for the selected book and chapter to be placed here without reloading the page.
</div>
Note: I have simplified the code to make it a little easier to follow. I am sure my js array is incorrect and needs fixing for my purpose. Also, I don't want the page to refresh, only the div to update. Thanks for any help.
Upvotes: 1
Views: 3699
Reputation: 1205
As has been suggested, you should seriously consider using ajax to retrieve this data, it would not make the page refresh, and would allow you to keep this data semi-private, and more easily manageable on the backend.
If/when you do this with ajax, you'll still need something like the following:
var booksData = {
book1: [
"chapter 1 content",
"chapter 2 content",
"..."
],
book2: [
"chapter 1 content",
"chapter 2 content",
"..."
]
}
function whenButtonClicked() {
var book = "book1" // get the actual book name from the select input
var chapter = 0 // get the selectedIndex of chapter input
var content = booksData[book][chapter];
var div = document.getElementById("content");
div.innerHTML = content;
}
And use an onclick handler on the button. Something like
<button id="button" onclick="whenButtonClicked()">
I'd recommend looking at a library like jQuery that would make life easier, and clean a lot of this up.
Upvotes: 1
Reputation: 6092
If you can format your array into multidimensional array like this
var setArray = ["book1":["chap1":"content","chap2":"content"], "book2":["chap1":"content","chap2":"content"]]
then it is easy to parse the array if you call setArray["book1"]["chap1"]
will get the content of that
Upvotes: 1
Reputation: 1483
If this is a big website you need to learn how to use jQuery and Ajax (to not refresh all element). How many books ? and chapters ?
Upvotes: 0