Javascript event handler to update a JSON object name - javascript

I am just starting out in Javascript and was wondering if anyone would mind pointing me in the right direction with this query I have.
I have created a JSON array and now wish to update some text on the page from the array upon clicking of the button. I have an event handling function that updates an image OK but I can't work out how to have the object name (pageRef) update within the 'nextPage' function so that the text updates from the contents of the array. I appreciate that this is probably a really obvious question but a pointer in the right direct will be greatly appreciated.
var diary_1938 = {
'page_1': {
'date_0': '1st Jan','entry_0': 'This is the first line',
'date_1': '2nd Jan','entry_1': 'This is the second line',
'date_2': '4th Jan','entry_2': 'This is the third line',
'img': 'image_1.jpg'},
'page_2': {
'date_0': '12th Jan','entry_0': 'This is the first line',
'date_1': '13th Jan','entry_1': 'This is the second line',
'date_2': '14th Jan','entry_2': 'This is the third line',
'img': 'image_2.jpg'},
};
var counter = 1;
var pageRef = "page_"+counter;
function nextPage() {
counter++
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}
function prevPage() {
counter--
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}
</script>
</head>
<body>
<button type = "submit" name = "submit_prev" onClick = "prevPage()"> << </button>
<button type = "submit" name = "submit_next" onClick = "nextPage()"> >> </button>
<br/>
<script> document.write(diary_1938[pageRef].date_0 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_0 + "<br/><br/>"); </script>
<script> document.write(diary_1938[pageRef].date_1 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_1 + "<br/><br/>"); </script>
<script> document.write(diary_1938[pageRef].date_2 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_2 + "<br/><br/>"); </script>
<script>document.write("<img id = 'DiaryImage' src = 'image_1.jpg' width='370' height='790' name ='Dunford'/>"); </script>
</body>

document.write is only read once as the page is being loaded into the browser, it's not really best practice to use it for updating dynamic content.
What you could do, is wrap up your dynamic content in a div like so:
<div id="content"></div>
then write a function that populates this div from the JSON data (this could be a lot more elegant but as you're just starting out, for simplicity's sake):
function populatePageFromJson(JSONobject){
var divElement=document.getElementById("content");
divElement.innerHTML=JSONobject[pageRef].date_0+"<br/>"+
JSONobject[pageRef].entry_0+"<br/><br/>"+
JSONobject[pageRef].date_1+"<br/>"+
JSONobject[pageRef].entry_1+"<br/><br/>"+
JSONobject[pageRef].date_2+"<br/>"+
JSONobject[pageRef].entry_2+"<br/><br/>"
}
And when the page loads have this function load up:
window.onload= function() {
populatePageFromJson(diary_1938);
}
also change prevPage() and nextPage() as well (Note that in your case, you forgot to update pageRef):
function prevPage() {
counter--
pageRef = "page_"+counter;
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
populatePageFromJson(diary_1938);
}
Here is a jsFiddler example to tie it all up.
Again this is hardly the most elegant way of doing so, but hopefully it will give you some insight into Javascript.
Once you're comfortable with the understanding of basic Javascript I recommend you getting acquainted with jQuery. It will make such tasks much easier. Good luck!

Because you code in nextPage() is invoked every time when button is clicked. However, your code like :*var counter = 1;var pageRef = "page_"+counter;document.write(diary_1938[pageRef].date_0 + "");* is executed only once when initializing. so you'd better write you code as:
function nextPage() {
counter++;
pageRef = "page_"+counter;
/*clear written content before*/
document.write(diary_1938[pageRef].date_0 + "<br/>");
/*other document.write,*/
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}

Related

how to use local storage in a proper way

i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);

Dynamically change string with JS?

I'm using a form that needs to pass a hidden field:
<script type="text/javascript">
var ss_form = {'account': 'XXXXX', 'formID': 'XXXXX'};
ss_form.width = '100%';
ss_form.height = '500';
ss_form.domain = 'app-XXXXX.marketingautomation.services';
ss_form.hidden = {'field_XXXXX': 'test item, another item' };
</script>
All it needs to be is a comma separated list, but I'm trying to dynamically add comma separated items using external buttons, for example clicking:
<button>add this string</button>
would make it
ss_form.hidden = {'field_XXXXX': 'test item, another item, add this string' };
I've tried using append to a div and then using innerHTML as a variable but it's just passing the initial div content from page load rather than the dynamically added items as well. JS is not my strong suit... any help is very much appreciated. Thank you!
Looks like you want something like this:
<button id="button">add this string</button>
document.getElementById("button").onclick = function(event) {
ss_form.hidden.field_XXXXX += ' ' + this.innerHTML;
}
Have you tried to concatenate the values?
The conactenacion is a process in which two or more values are joined by an operator, commonly more (+) or two points (..).
Try this way
<button id="btn">add this string</button>
<script>
document.getElementById ("btn").onclick = function (event) {
   ss_form.hidden.field_XXXXX + = this.innerHTML + ', '; //Add separated comma values
}
</script>

Adding HTML to page based on conditional logic in JavaScript or jQuery

I have a div in which I have to fill some data in. I have to render the HTML based on conditions and I am adding data to that div using jQuery. Can someone please tell me how I can add the condition based insertion of HTML on the page?
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
$('.myDiv').after("<br/>"+data);
}
function AddData()
{
var data = "<div><h1>My data</h1>"
if(jsVariable){
data = data + "<p>The JSVariable is present on page </p>"
}
data = data + "</div>"
$('.myDiv').append("<br/>"+data);
}
function AddData(){
if(typeOf(jsVariable)!=="undefined"){
var data = "<div><h1>My data</h1>";
data += " <p>The JSVariable is present on page </p>";
data += "</div>";
$('.myDiv').after("<br/>"+data);
}
}
this should do the trick, but some element with a class of myDiv will need to already exist for this to work
<div class="myDiv"></div>
What exactly are you trying to do?
If you simply want to add some extra html content depending on the variable, you are almost done. You just need to add the <p> part to the data (data += "<p>...</p>").
If you're trying to add all of the html based on the variable, put the if statement around the $(".myDiv").after (which should be $(".myDiv").append btw).
You'r code is not valid.
Could you explain what do you want to do with
if(jsVariable){
<p>The JSVariable is present on page </p>
}
+"</div>"
If you want to add a html code at ending of a div, you should use
$('.myDiv').append('<p>Text text text text</p>');
simple usage:
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("p").click(function() {
var a = $("#div1").text();
if (a == "one") {
$("#div2").text(a);
}
});
});
</script>
</head>
<body>
<div id="div1">one</div>
<div id="div2"></div>
<p>click me</p>
</body>
</html>
function addData(to)
{
var h1 = $('<h1>').text('My Data');
var data = $('<div>').append(h1);
if (window.jsVariable) {
$('<p>').text('JS Variable is present on the page').appendTo(data);
}
to.append(data);
}
addData( $('.myDiv') );
if (condition) {
$('div#yourDivID').html('<p>The JSVariable is present on page </p>');
}
In addition to .html(which places the html inside your div), you can use other things like append, prepend etc. Check out jQuery's documentation on DOM Insertion.
Here is a JSFiddle http://jsfiddle.net/va4n8/
function addData() {
var newDiv = $('<div>');
newDiv.append($('<h1>').html('My data'));
if ('jsVariable' in window) {
newDiv.append($('<p>').html('The JSVariable is present on page'));
}
$('.mydiv').after($('<br>')).after(newDiv);
}

How can I save variables on refresh?

<!DOCTYPE HTML>
<html>
<head>
<title>Zautra Levels</title>
<h2 style="font-family: Trebuchet MS; color: blue;"">Zautra Levels</h2>
<p> </p>
</head>
<body>
<p>Clickables:</p>
<button id="swag" onclick="lmao()">Gain XP</button> <button id="gold" onclick="getgold()">Get Gold</button> <button id="buyupgrade" onclick="buyupp()">Level Up!</button>
<p> </p>
<div id="total">XP: 0</div>
<div id="goldt">Gold: 0</div>
<div id="upgradess">Level: 0</div>
<div id="upcostt">Required XP: 25</div>
<script>
var clicks = 0; // How many clicks you have
var upgrades = 0; // How many upgrades you have purchased
var upcost = 25; // How much the upgrades cost
var gold = 0; // How much gold you have
function updateclicks() { // Declares the function that updates the "Zautra Clicks" Text.
var v=document.getElementById("total");
v.innerHTML = 'XP: ' + clicks;
}
function updategold() { // Declares the function that updates the "Zautra Clicks" Text.
var g=document.getElementById("goldt");
g.innerHTML = 'Gold: ' + gold;
}
function updateupgradecounter() { // Declares the function that updates the "Upgrades:" Text.
var y=document.getElementById("upgradess");
y.innerHTML = 'Level: ' + upgrades;
}
function updateupcost() { // Declares the function that updates the "Upgrade Cost:" Text.
var z=document.getElementById("upcostt");
z.innerHTML = 'Required XP:' + upcost;
}
var x=document.getElementById("swag"); function lmao() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
clicks+=1;
updateclicks();
}
var j=document.getElementById("gold"); function getgold() { // When you click the "Click for MOAR Zautra's" Button you get a +1 Click.
gold+=1;
updategold();
}
var c=document.getElementById("buyupgrade"); function buyupp() {
if (clicks >= upcost) {
clicks-=upcost
upgrades+=1
upcost*=2
updateclicks();
updateupgradecounter();
updateupcost();
}
else
{
var clicksdif = upcost - clicks;
confirm("You need " + clicksdif + " more XP to level up.");
}
}
</script>
</body>
</html>
This is the code for my game that I am working on.
I'm trying to add a button, and when you press it, it saves all of the variables.
If you're level 5 with 26 XP, and 7 gold, you refresh the page, you still have those stats instead of losing them on refresh.
Please help!
(And yeah, I do realize that the code is really messed up, but that is a small issue. I'll fix that sooner or later.)
I believe that actually the easiest way, easier than cookies, is to pass the values via the URL. Example:
<form action="yourPage.php?gold=$amount&level=$whatlevel&experience=$experience" method="POST">
//Your refresh button here
</form>
and then to retrieve those variables when the page reloads, use: gold=$_POST['gold']
Another option as well is to use the GET method instead of POST.
Keep in mind that the file extension needs to be php for this code to work.
you could create a cookie in php:
setcookie("NameOfTheCookie",$value,$expireTime)
and $value can be an array of values as well.

How to bind JavaScript result to a div on my page?

i have a java script file that it's output is a table with some information.
i want to show this result in one of my DIVs in my page but the result of function,placed at top of my page's Header!
What can i do to fix this?
this is end of my java script file ,in fact this is its output
' document.write("")
document.write(" اوقات شرعی کلیه شهر ها ")
document.write("")
document.write(" ")
document.write(" اذان صبح طلوع خورشید اذان ظهر غروب خورشید اذان مغرب")
document.write(" اوقات به افق : انتخاب شهراراکاردبیلارومیهاصفهاناهوازایلامبجنورد بندرعباسبوشهربیرجندتبریزتهرانخرم آبادرشتزاهدانزنجانساریسمنانسنندجشهرکردشیرازقزوینقمکرمان کرمانشاهگرگانمشهدهمدانیاسوجیزد ")
document.write("") '' and this is its call at the and of my master page '
$(document).ready(function ogh() {
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
});
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
</script>
</form>
'
if you could't understand top of my code,,its output is a table
You can set the HTML of the div using jquery in the ready event like follows:
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
....
<script type="text/javascript">
$(document).ready(function () {
$("#myDiv").append(pz());
});
function pz() {
// do here something useful and return the text you want to add to the div
return "Hello there =) !!!";
};
</script>
<div id="myDiv"></div>
Don't forget to install jquery:
https://nuget.org/packages/jQuery
i use this
function ogh()
{
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
}
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
but i got an error : one of my functions could't access to oits data
Some steps
Move your JavaScript code at the bottom of the page.
Make use of innerHTML (basic JavaScript) or html() (jQuery) to add so.

Categories