Passing variable to function on another page - javascript

I am working on a website and am planning on having it so that certain links will have a value set, this will change what container is displayed when the page loads. How would I have it so the link passes a value that would be used for the onload functions?
Here is a mockup of my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lunch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="script.js"></script>
</head>
<body onload="navBar(); dateChange(); tabulate(0);">
<nav>
<ul>
<li>Appitizers</li>
<li>Breakfast</li>
<li>Lunch</li>
<li>Dinner</li>
<li>Dessert</li>
<li>Ten-Course Dinner</li>
<li>Send in your Recipes!</li>
</ul>
</nav>
<div class="main">
<div class="box">
<ul>
<li><a onclick="tabulate(this.id);" id="1">Chicken Clubhouse Sandwiches</a></li>
<li><a onclick="tabulate(this.id);" id="2">Smokey Tomato Soup</a></li>
</ul>
</div>
<div id="0" class="recipe" style="display: block;">
<div class="tabs">
<a class="tab"> </a>
</div>
<div class="page">
<p>The recipes you'll find here are ones you can use to impress guests at your next get together</p>
</div>
</div> <!--recipe card end-->
<div class="recipe" id="1">
<h1>Chicken Clubhouse Sandwiches</h1>
</div> <!--recipe card end-->
<div class="recipe" id="2">
<h1>Smokey Tomato Soup</h1>
</div> <!--recipe card end-->
</div>
</body>
</html>
And here is my tabulate function:
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}

You would need to make use of the URL's GET parameters:
lunch.html?item=2
In conjunction with passing the variable into the JavaScript function:
// Set up an object for GET parameter
var $_GET = {};
// Find and extract the various GET parameters
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location.toString().replace(/^.*?\?/, '').replace(/#.*$/, '').split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
// Target a specific get parameter, given the GET parameter name
var tabNum = $_GET['item']; // Comes through as '2' in this example
// Pass the parameter into the function
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
See this post and this post for further reference.
Hope this helps! :)

I haven't tested this, but you should be able to get by with passing a GET variable via PHP into tabulate(), in a way like this:
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
window.addEventListener('DOMContentLoaded', function(evt) {
var id = <?php echo htmlspecialchars($_GET['id'], ENT_COMPAT, 'utf8'); ?>;
tabulate(id);
});

Related

Change image src to a local image using javascript?

First time ever touching javascript here, so bear with me.
My file structure looks like so:
I want to change the image in my HTML using js. Here's the relevant HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Assignment 3A</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style/assignment_3.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="data/data.js"></script>
<script src="script/htmlMaker.js"></script>
<script src="script/assignment_3.js"></script>
<script id="news-detail-template" type="text/html">
<img class='news_photo' src='{{photo}}' >
<div class='news_heading'>{{heading}}</div>
<div class='date'>{{Date}}</div>
<div class='news_detail'>{{details}}</div>
</script>
<script id="news-item-template" type="text/html">
<div news_id='{{id}}' class='news_item' > {{heading}} </div>
<img class='news_img' src='data/NBA.jpg'>
</script>
</head>
<body>
<div class="newsDiv">
<div class="left">Latest</div>
<div id="news" class="marquee"></div>
<img id="toggle" class="right" src="data/pause.png" onclick="toggle(this)">
</div>
<div id="detail" class="detail">
</div>
</body>
</html>
And then the corresponding js code in assignment_3.js:
function toggle(image) {
if (image.src != "data/pause.png")
{
image.src='data/pause.png';
}
else if (image.src == "data/pause.png")
{
image.src='data/play.png';
}
}
Obviously, something is amiss here, as the browser doesn't seem to recognize my image paths at all. How would I go about doing this correctly?
When you use image.src, it returns the full path of the image. In the if condition, you only checks the relative path of the image. To check for the relative path of the image, you can use image.getAttribute('src').
function toggle(image) {
if (image.getAttribute('src') == "data/pause.png") {
image.setAttribute('src', 'data/play.png');
} else {
image.setAttribute('src', 'data/pause.png');
}
}
<body>
<div class="newsDiv">
<div class="left">Latest</div>
<div id="news" class="marquee"></div>
<img id="toggle" class="right" src="data/pause.png" onclick="toggle(this)">
</div>
<div id="detail" class="detail">
</div>
</body>
I have modelled a minimal, complete and verifiable example of your problem in this JSFiddle. I don't see any issues in your toggle logic. The only thing you need to consider is using img.getAttribute('src') instead of img.src. This is because
img.getAttribute('src') - Gives you the actual value that the HTML markup has set
img.src - Effective absolute path of the source
function toggle(img) {
// var playSrc = "data/play.png"; // to use your file instead
var playSrc = "https://cdn.iconscout.com/icon/premium/png-256-thumb/play-button-1516951-1285078.png";
// var pauseSrc = "data/pause.png"; // to use your file instead
var pauseSrc = "http://www.pngall.com/wp-content/uploads/5/Pause-Button-Transparent.png";
if (img.getAttribute('src') != pauseSrc)
{
img.setAttribute('src', pauseSrc);
}
else // The part if (image.src == "data/pause.png") is redundant
{
img.setAttribute('src', playSrc);
}
}
With that out of the way, you have a lot of junk in the <head> tag, which you need to remove (I have put them below). Probably, the code isn't working because of that.
<script id="news-detail-template" type="text/html">
<img class='news_photo' src='{{photo}}' >
<div class='news_heading'>{{heading}}</div>
<div class='date'>{{Date}}</div>
<div class='news_detail'>{{details}}</div>
</script>
<script id="news-item-template" type="text/html">
<div news_id='{{id}}' class='news_item' > {{heading}} </div>
<img class='news_img' src='data/NBA.jpg'>
</script>
As Harshana points out, you need to use the getAttribute function to check equality. You can set the image source using a regular assignment operator, but you cant use == to check for equality.

how can i click another page's link which includes functions in current page

There is 2 pages. main.jsp and list.jsp
when I execute goPage() in main.jsp I would like to make event of click list.jsp's nav>ul>li(2).
because list.jsp shows information by click of javascript function
so i need to make click when i enter list.jsp
so anyway would be great if i can show elements in list.jsp
this is main.jsp
<body>
<div class="main_wrap">
<div class="sub1"><div class="main_title1">월별 통계</div></div>
<div class="sub2"><div class="main_title2"><a href="javascript:goPage();" onclick="callChart(50035); callPie(50035); callMap(50035); callTitle('살인');">발생 현황</div></div>
</div>
<script type="text/javascript">
function goPage() {
location.href="list.jsp";
}
</script>
</body>
this is list.jsp
all function is located in each scrript file.
<body>
<div class="wrap">
<div class="title">발생현황</div>
<nav>
<ul>
<li><img src="css/f4f0edb08c97567ce6b0475a63bf7000.png" alt="Italian Trulli" width="50px" height="30px"></img></li>
<li>살인</li>
<li>절도</li>
<li>강간</li>
<li>강도</li>
</ul>
</nav>
<div class="chart_map">
<span class="div_sub1">지도 전국 범죄율</span>
<div class='korea'></div>
</div>
<div class="chart_pie">
<span class="div_sub1">검거자</span>
<div class="pie_arrests"></div>
</div>
<script src="js/pie_period.js?v=<%=System.currentTimeMillis() %>"></script>
<script src="js/pie_arrests.js?v=<%=System.currentTimeMillis() %>"></script>
<script src="js/korea_map.js?v=<%=System.currentTimeMillis() %>"></script>
</div>
</body>
Instead of trying to make a click when going to list.jsp, maybe try running the same code when loading list.jsp instead, so add something like this to the file:
<!-- list.jsp -->
<script type="text/javascript">
window.addEventListener("load", function(event) {
callChart(50035);
callPie(50035);
callMap(50035);
callTitle('살인');
});
</script>
You could something like:
Redirect to the list.jsp with a query string
If there is a query string with a certain key - click the button
Code sample
On main page:
function goPage() {
location.href="list.jsp?doclick=1";
}
On list page:
document.addEventListener('DOMContentLoader', function () {
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('doclick');
if(myParam == 1) {
callChart(50033);
callPie(50033);
callMap(50033);
callTitle('강간');
}
});

How to loop through div tags with same class name

On my page, I have 5 div tags named "dropdown". I want to find all "a" tags under each "dropdown" div tag. I hope I am explaining this properly but this is what I have. Can someone confirm that it is right:
var dropdownDivs = document.getElementsByClassName('dropdown');
for(i = 0; i < dropdownDivs.length;i++)
var lnks = document.getElementsByClassName('dropdown').getElementsByTagName('a');
var dropdownDivs = document.getElementsByClassName('dropdown');
var links = dropdownDivs.getElementsByTagName('a');
You do not need the for loop.
How to get elements of specific class inside a div already found in JavaScript?
One line with pure javascript
let test = document.querySelectorAll('.dropdown a');
console.log(test);
My HTML for test
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="dropdown">
<a> TOTO </a>
</div>
<div class="test">
<a> TOTOB </a>
</div>
<div class="dropdown">
<a> TOTOC </a>
</div>
<div class="dropdown">
<a> TOTOD </a>
</div>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
You'll need to get the links inside the for loop:
var dropdownDivs = document.getElementsByClassName('dropdown');
var lnks = [];
for (i = 0; i < dropdownDivs.length; i++) {
lnks.push(...dropdownDivs[i].getElementsByTagName('a'));
}
lnks.forEach(function(el) {
el.style.color = "red";
});
<div class="dropdown">
link
</div>
link
<div class="dropdown">
link
</div>
<div class="dropdown">
link
</div>
link
You can shorten it to a single call, by using Document#querySelectorAll:
var lnks = document.querySelectorAll('.dropdown a');
lnks.forEach(function(el) {
el.style.color = "red";
})
<div class="dropdown">
link
</div>
link
<div class="dropdown">
link
</div>
<div class="dropdown">
link
</div>
link
Use document.querySelectorAll('.dropdown a'). Here's the MDN on querySelectorAll.
I think your for loop itself is probably correct. Your problem though may be what you are doing with it in the loop.
const divs = document.getElementsByClassName('target');
for (let i = 0; i < divs.length; i++) {
console.log(divs[i].getElementsByTagName('a')[0]);
}
<div class="target">A</div>
<div class="target">B</div>
<div class="target">C</div>
<div class="target">D</div>
<div class="target">E</div>
In your example, you're just setting them into a variable each time. If there is more to it, then that might be okay. If you're trying to collect them all into one variable, you'll want to put them in an array instead.
const divs = document.getElementsByClassName('target');
let anchors = [];
for (let i = 0; i < divs.length; i++) {
anchors.push(divs[i].getElementsByTagName('a')[0]);
}
console.log(anchors);
<div class="target">A</div>
<div class="target">B</div>
<div class="target">C</div>
<div class="target">D</div>
<div class="target">E</div>
As other people already suggested how to do it through java script, If want to go with jquery this can help.
$(".dropdown").each(function(){
$(this).find("a").each(function(){
console.log(this);
})
})

jQuery Single Page app dynamic divs

I have a jQuery Single Page app that works but not the way I want it to.
I have a list of counties that is read from a JSON file (the list can be filtered). When one is chosen, it appears as a hyperlink that links to another "page" with a town from that county (the "page" is actually just a div in the same page). The trouble is I have to manually create the divs beforehand. E.g if there are five items in the JSON file and I want to add one more, I have to manually add an extra div in the page.
It works OK for the counties, I can add extra counties to the JSON and it builds an extra hyperlink but for the "page" it links to I need to create a new div in the html. When I create the divs dynamically (under the inner "each" in the Javascript code) nothing happens when you click on the link as the div does not exist in the html.
Is there a solution to this? (see code below)
HTML (with js):
<!doctype html>
<html>
<head>
<script src="js/jquery-1.11.2.min.js"></script>
<script src="jquery.mobile-1.4.5/jquery.mobile-1.4.5.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.4.5/jquery.mobile-1.4.5.css"></script>
<title>How to Parse a JSON file using jQuery</title>
</head>
<body>
<div data-role="page">
Menu
<div data-role="content">
<div id="results">
<ul id="mynewlist" data-role ="listview" data-autodividers="true" data-filter="true" data-filter-reveal="true">
</ul>
</div>
</div>
<div data-role="panel" class="cd-panel from-left" data-position="left" data-position-fixed="false" data-display="reveal" id="myKoolPanel" data-theme="a">
<ul id ="myul" data-role="listview" data-theme="a" data-divider-theme="a" style="margin-top:-16px;" class="nav-search">
<li>
Towns in Ireland
</li>
<li>
Map of Ireland
</li>
</ul>
</div>
</div>
<script>
$(document).ready(function(){
$.getJSON( "data.json", function( data ) {
var items = [];
var z=0;
$.each( data, function( i, item ) {
z=z+1;
items.push('<li><a href=#textcontainer'+z+'>' + i + '</a></li>');
$.each(item, function(property, value) {
$('#textcontainer'+z).append(value);
});
});
$('#mynewlist').append( items.join('') );
});
});
</script>
<div id ="textcontainer1"> </div>
<div id ="textcontainer2"> </div>
<div id ="textcontainer3"> </div>
<div id ="textcontainer4"> </div>
<div id ="textcontainer5"> </div>
</body>
</html>
JSON file:
{
"Kerry": {
"town": "Kenmare"
},
"Cork": {
"town": "Mallow"
},
"Limerick": {
"town": "Charleville"
},
"Meath": {
"town": "Trim"
},
"Waterford": {
"town": "Lismore"
}
}
Using AngularJs you can solve it.
Define js file as below
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
var data;
$scope.data =[{
"name":"Kerry",
"town": "Kenmare"
},
{
"name":"Cork",
"town": "Mallow"
},
{
"name":"Limerick",
"town": "Charleville"
},
{
"name":"Meath",
"town": "Trim"
},
{
"name":"Waterford",
"town": "Lismore"
}] ;
});
HTML file code :
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"> </script>
<script language="javascript" type="text/javascript" src="fileName.js"> </script>
</head>
<body>
<div ng-controller="ctrl">
<div ng-repeat="d in data">
{{d.name}} : {{d.town}}
</div>
</div>
</body>
</html>
I hope this will help.

dynamically setting variables in html5 body?

Hi i am trying to dynamically set some of the contents of an html5 body with var strings defined in a JS.
below is what i have written so far and it doesnt seem to display the value specified.
<link href="src/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="src/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="src/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<body>
<script>
var name = "John Smith";
</script>
<div data-role="page" id="page">
<div data-role="header">
<button></button>
<h1>New Claim</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li> <p><h3>Your Name: <var>name</var></h3></p></li>
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
i am trying to insert John Smith inside the "Your Name: text.
Thanks
You will have to use JavaScript to "print" the contents of a variable, to the HTML-source. Here's an example:
<div id="test"></div>
document.getElementById('test').innerHTML = 'This goes into the element!';
But since you're using jQuery, you could do this as well:
$('#test').text('This goes into the element!');
You should either give the VAR-Tag itself or it's wrapping LI-Tag an unique ID.
In HTML
<li>
<p>
<h3>Your Name: <var id="name">name</var></h3>
</p>
</li>
JavaScript
var name = "John Smith";
$("#name").text(name);
And by the way:
You shouldn't nest a Heading inside of a Paragraph, this doesn't make any sense.
Paragraphs are INLINE while Headings are BLOCKELEMENTS.
Check out this FIDDLE
You probably want something like below. Have global JS variables assigned, reference them with a VAR html5 tag, use JS at the end of body (or after DOM load) to substitute the keys in the VAR tags with the values held in the global VARS object.
<script>
VARS = {};
VARS.name = "John Smith";
VARS.age = 45;
</script>
...
Name : <var>name</var><br/>
Age : <var>age</var>
...
<script>
// run once at end of body
var all = document.getElementsByTagName("var");
for(var i=0; i<all.length; i++) {
var elm = all[i];
var key = elm.innerHTML;
if(VARS[key] != null)
elm.innerHTML = VARS[key];
else
elm.innerHTML = "";
}
</script>
The tag isn't supposed to be used this way
Try this:
<link href="src/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="src/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="src/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<body>
<script>
var name = "John Smith";
$(document).ready(function() {
$("#name").text(name);
});
</script>
<div data-role="page" id="page">
<div data-role="header">
<button></button>
<h1>New Claim</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li> <p><h3>Your Name: <span id="name"></span></h3></p></li>
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
Edit: just to clarify one thing. The tag isn't supposed to be used to hold the place to the value of a variable. It's correct semantic meaning is more to represent a mathematical variable or a programming variable when you are showing some code on your page. If I'm wrong here, please someone correct me.
try this
$(document).ready(function() {
$("h3").text("Your name : John Smith");
});
Add some classes on your divs, to easuly select the good tags

Categories