.show() not working correctly - javascript

I am having issues with an app I am creating. Depending on whether a variable of mine is null is supposed to show a specific screen. Once that variable has a value attached my app is supposed to display another div. However, my code is not working. Take a look at the Javascript/Jquery below:
(Note modifying the code in order to show that null is not the issue)
access_token = 3;
if (access_token == 3){
$('.dashboardProfile').hide();
$('.dashboardInfo').hide();
$('.dashboardConnect').show();
$('.connect').click(function () {
var url = "https://foursquare.com/oauth2/access_token";
url += "?client_id=" + foursquareApi.clientId;
url += "&response_type=token";
url += "&redirect_uri=" + foursquareApi.redirectUrl;
window.location = url;
});
}
else {
$('.dashboardProfile').show();
$('.dashboardInfo').show();
$('.dashboardConnect').hide();
}
and this is the HTML in question:
<div class="dashboard-container">
<div class="dashboardConnect">
<div class="connect">
<p>Sign In</p>
</div>
</div>
<div class="dashboardProfile">
<p>User Information and Picture</p>
</div>
<div class="dashboardInfo">
<p>Check Ins</p>
<div class="indicator checkin">#</div>
<p>Countries</p>
<div class="indicator country">#</div>
<p>Cities</p>
<div class="indicator city">#</div>
</div>
</div>
</div>
<!--container-fluid-->
This is the head of the HTML:
<head>
<title>FourSquare Dashboard</title>
<link rel="stylesheet" href="main.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="FourSquareJax.js"></script>
</head>

Easy fix. You made a small typo. Put $('.dashboardConnect').hide(); inside the else loop:
var access_token = 3;
if (access_token == 3) {
$('.dashboardProfile').hide();
$('.dashboardInfo').hide();
$('.dashboardConnect').show();
$('.connect').click(function() {
var url = "https://foursquare.com/oauth2/access_token";
url += "?client_id="+foursquareApi.clientId;
url += "&response_type=token";
url += "&redirect_uri="+foursquareApi.redirectUrl;
window.location = url;
});
}
else {
$('.dashboardProfile').show();
$('.dashboardInfo').show();
$('.dashboardConnect').hide();
}

Try changing your conditional to:
if (!access_token)
This will cause the conditional block to be entered if access_token is null, undefined, an empty string or 0.

Related

ajax call in javascript not returning items to correct lists

I am a student and am having an issue getting information on the correct lists. My sample data has a male runner and a female runner. I have three lists of runners: male, female, all. When I run my code, nothing appears on the male and female lists but all do show up on the "all" list. What modification do I need to get the runners on the appropriate gender lists?
function getXMLRacers() {
$.ajax({
url: "finishers.xml",
cache: false,
dataType: "xml",
success: function (xml) {
// Empty lists to prevent duplication.
$("#finishers_m").empty();
$("#finishers_f").empty();
$("#finishers_all").empty();
// Place runner name on appropriate lists.
$(xml).find("runner").each(function () {
var info = "<li>Name: " + $(this).find("fname").text() + " " +
$(this).find("lname").text() + ". Time: " + $(this).find("time").text() + "</li>";
if ($(this).find("gender").text === "m") {
$("#finishers_m").append(info);
} else if ($(this).find("gender").text === "f") {
$("#finishers_f").append(info);
} else { }
$("#finishers_all").append(info);
});
getTime();
}
});
};
My sample data in an XML file:
<?xml version="1.0" encoding="utf-8"?>
<finishers>
<runner>
<fname>John</fname>
<lname>Smith</lname>
<gender>m</gender>
<time>25:31</time>
</runner>
<runner>
<fname>Jane</fname>
<lname>Smith</lname>
<gender>f</gender>
<time>26:01</time>
</runner>
</finishers>
My html file where the lists are defined:
<!DOCTYPE html>
<html>
<head>
<title>NTC Race Finishers</title>
<link href="styles/my_style.css" rel="stylesheet">
</head>
<body>
<header>
<h2>NTC Race Finishers!</h2>
</header>
<div id="main">
<ul class="idTabs">
<li>Male Finishers</li>
<li>Female Finishers</li>
<li>All Finishers</li>
</ul>
<div id="male">
<h4>Male Finishers</h4>
<ul id="finishers_m"></ul>
</div>
<div id="female">
<h4>Female Finishers</h4>
<ul id="finishers_f"></ul>
</div>
<div id="all">
<h4>All Finishers</h4>
<ul id="finishers_all"></ul>
</div>
</div>
<footer>
<h4>Congratulations to all our finishers!</h4>
<button id="btnStart">Start Page Updates</button>
<button id="btnStop">Stop Page Updates</button>
<br>
<span id="freq"></span>
<br><br>
Last Updated: <div id="updatedTime"></div>
</footer>
<script src="scripts/jquery-3.4.1.min.js"></script>
<script src="scripts/jquery.idTabs.min.js"></script>
<script src="scripts/my_scripts.js"></script>
</body>
</html>
#DJB I think the problem lies somewhere within the following code
if ($(this).find("gender").text === "m") {
$("#finishers_m").append(info);
} else if ($(this).find("gender").text === "f") {
$("#finishers_f").append(info);
} else { }
try changing code so that you are not dependent on $(this).find("gender").text then try debugging from there. If you can provide more information than stackoverflow will be more helpful.
I found the problem. When calling the text function within the following if statement, I failed to add () after the word text. The correct code is:
if ($(this).find("gender").text() === "m") {
$("#finishers_m").append(info);
} else if ($(this).find("gender").text() === "f") {
$("#finishers_f").append(info);
} else { }
$("#finishers_all").append(info);

LinkButton.Text coming undefined in js

I want to configure a hyperlink to close/open its related div in asp.net. Basically, when a user clicks the sign X, the panel should be closed and the sign + should be appeared. When + is clicked, the panel should be showed again. I could not manage this and I believe my main problem is "document.getElementById('<%= lb_closePanel.ClientID %>').value" is coming as undefined. Here is the code until now. I appreciate for your helps!
<!DOCTYPE html>
....
<div class="appheader">
<h1 class="appheaderContent">Search for Client</h1>
<div id="checkBox"></div>
<div id="closePanel"><h2 id="lblClosePanel">Close Panel</h2>
<div id="xButton">
<asp:LinkButton onclientclick="CloseOpenPanel('Search')" runat="server" Text="X" style="text-decoration:none; color:white" ID="lb_closePanel"></asp:LinkButton>
</div>
</div>
</div>
<div class="app" id="Search">
...
<div>
...
</html>
<script type="text/javascript">
function CloseOpenPanel(obj) {
alert(document.getElementById('<%= lb_closePanel.ClientID %>').value); //here it comes undefined!!!!
if (document.getElementById('<%= lb_closePanel.ClientID %>').value == 'X') {
document.getElementById(obj).Visible = false;
lb_closePanel.Text = '+';
}
else {
document.getElementById(obj).Visible = true;
lb_closePanel.Text = 'X';
}
}
</script>
Your code is OK, just instead of the property value use innerHTML
alert(document.getElementById('<%= lb_closePanel.ClientID %>').innerHTML);
Instead of using .value, try using .innerHTML instead to get the text inside of your link button (rendered as an a tag)

Infinite looping slideshow of HTML pages with jQuery

I'm trying to make a slideshow of HTML pages outputting to a screen 24/7. What I have works, but different slides need different intervals. How can I achieve this?
The output is fullscreen with a fixed footer which displays logo, some messages and the time.
jQuery
$(document).ready(function () {
var div = $('#content'); // Target iFrame
var slides = ['welcome','movie']; // Which slides
var time = 5000; // Default interval
var folder = 'slides'; // Folder where the HTML slides are
var extension = 'html';
var index = 1; // Skip first (0), already loaded by default SRC from iframe
$.ajaxSetup({
cache: false // Maybe not neccesary any more, before I used a div and $.load() instead of iframe
});
function loop() {
if (index === slides.length) { // If at end
index = 0; // Start again
}
div.attr('src', folder + '/' + slides[index] + '.' + extension); // Load next one
index++;
}
setInterval(function () {
loop();
}, time);
});
HTML
<iframe id="content" src="slides/welcome.html" width="100%" height="100%" frameborder="0"></iframe>
<div id="bar">
<div class="row">
<div class="col-lg-3">
<img src="img/logo.png" alt="" id="logo">
</div>
<div class="col-lg-6">
<div id="welcome">
Welcome <span>visitor</span>!
</div>
</div>
<div class="col-lg-3">
<div id="time"></div>
</div>
</div>
</div>
Using setTimeout and buttons to start and stop the loop.
http://jsfiddle.net/nirmaljpatel/75tmnmbq/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<div id="bar">
<div class="row">
<div class="col-lg-3">
<img src="img/logo.png" alt="" id="logo">
</div>
<div class="col-lg-6">
<div id="welcome">
Welcome <span>visitor</span>!
</div>
</div>
<div class="col-lg-3">
<div id="time"></div>
</div>
</div>
</div>
<div id="content"></div>
</body>
<script>
$(document).ready(function () {
var div = $('#content'); // Target iFrame
var slides = [{"ImageName":"Welcome", "Time":200},{"ImageName":"Image1", "Time":5000},{"ImageName":"Image3", "Time":1000},{"ImageName":"Image4", "Time":500},]; // Which slides
//var slideObj = JSON.parse(slides);
//alert(slides);
var time = 5000; // Default interval
var folder = 'slides'; // Folder where the HTML slides are
var extension = 'html';
var index = 0; // Skip first (0), already loaded by default SRC from iframe
$.ajaxSetup({
cache: false // Maybe not neccesary any more, before I used a div and $.load() instead of iframe
});
function loop() {
if (index == slides.length) { // If at end
index = 0; // Start again
}
div.html("ImageName: "+slides[index].ImageName + "; Image Time Interval: "+slides[index].Time); // Load next one
index++;
}
if(index==0)
loop();
setInterval(loop, slides[index].Time);
});
</script>
</html>

JQuery: Defining a variable is stopping my script from running

<script>
$(document).foundation(
var count = 1
$("button.test").click(function(){
if ($("p.change-me").text() === "OFF") {
$("p.change-me").text("ON")
count = count + 1
}
else if ($("p.change-me").text() === "ON") {
$("p.change-me").text("OFF")
count = count + 1
}
$("p.counter").text(count)
})
)
</script>
Very simply, I want to show the count as I am pressing this On and Off button. However, when I add the "var count = 1", my button no longer works. When I get rid of that line, the button will turn the text in the tag from ON to OFF and from OFF to ON.
How come? As you can probably tell, I am teaching myself JQuery.
Thanks!
HTML as requested:
<div class="row">
<div class="small-6 columns text-center">
<button class="button radius test">CLICK THIS</button>
</div>
<div class="small-6 columns text-center">
<p class="change-me">OFF</p>
</div>
</div>
<div class="row">
<div class="small-12 columns text-center">
<p>Here we will print how much fun you are having:</p>
<p class="counter">0</p>
</div>
</div>
Take your code out of the foundation() call. Also try to remember using semicolons.
$(document).foundation();
var count = 1;
$("button.test").click(function(){
if ($("p.change-me").text() === "OFF") {
$("p.change-me").text("ON");
count = count + 1;
}
else if ($("p.change-me").text() === "ON") {
$("p.change-me").text("OFF");
count = count + 1;
}
$("p.counter").text(count);
})
#Romain's answer is correct, but just to add to that... foundation is a method-call, and you were trying to put javascript code in the section where you normally put parameters (ie inside the ()). javascript code normally has to go inside of a function's body, not in the section where you type the parameters.

Multiple Javascript Functions in Jquery

I've been having the same issue for a very long time and I'm wondering if someone can teach me what I'm doing wrong.
I created a multipage Jquery (like the one in the example below) however, when I go to add a reference to a .js file I've saved it always tends to either not load up the pages content or if positions somewhere else it just simply wont work!
My HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
img.fullscreen {
max-height: 100%;
max-width: 100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/tmp/json4.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
dealObject.dealID = $(this).attr('id');
dealObject.restaurantid = $(this).attr('data-restaurantid');
dealObject.shortName = $(this).find('h1').html();
dealObject.image = $(this).attr('data-image');
//dealObject.dname = $(this).find('input').html();
//dealObject.dname = $(this).find('desc').val();
dealObject.dealName = $(this).find('h6').html();
dealObject.description = $(this).find('h5').html();
//dataObject.dname=$(this).find('p').html()
//dealObject.name = $(this).find('desc').eq(0).val(dealObject.name);
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
//$('#index2 [data-role="content"]').html('You have selected Link' + dealObject.dname);
$('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
$('#index2 [data-role="content"]').find('#title').html(dealObject.name);
//$('#index2 [data-role="content"]').find('#description').html(dealObject.dname);
$('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
$('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
$('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);
});
var dealObject = {
dealID : null,
restaurantid : null,
shortName : null,
image : null,
dealName : null,
description: null
}
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Current Deals</h1>
</div>
<div data-role="content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</div>
</div>
</div>
<!--New Page -->
<div data-role="page" id="index2">
<!--<script src="js/ammend.js"></script>--!>
<div data-role="header">
<h1> Find A Deal </h1>
</div>
<div data-role="content">
<!-- <?php
if( !isset( $_SESSION ) ){
session_start();
}
if( isset( $_SESSION['username'] ) ){
echo ".";
} ?> --!>
<form id="test">
<label for="name">Deal Name:</label>
<input type="text" value="" name="tname" id="tname"/>
<label for="desc">Description</label>
<input type="text" value="" name="desc" id="desc"/>
<a data-role="button" id="amend" data-icon="star" data-iconpos="left">Amend Deal </a>
<input type="text" value="" name="dealid" id="dealid"/>
<h3></h3>
<!--<img src="" width="100px" height="100px" id="deal-img">
<h1 id="title"></h1>
<h3 id="description"></h3>
<p id="name"></p>--!>
</div>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
Apologies if it's hard to read. This javascript function will work just fine by itself. When an item in index is clicked it brings you to a new page in index2. On index 2 there's a submit button to which is connect to a file referenced <script src="js/ammend.js"></script>. This is where things normally seem to go wrong for me as it's like they're cancelling eachother out or just not co-operating together.
The js file at that location is:
$(document).on('pagebeforeshow', '#index2', function(){
$('#amend').on('click', function(){
if($('#tname').val().length > 0 && $('#desc').val().length > 0 && $('#dealid').val().length > 0){
userObject.tname = $('#tname').val(); // Put username into the object
userObject.desc = $('#desc').val(); // Put password into the object
userObject.dealid = $('#dealid').val();
// Convert an userObject to a JSON string representation
var outputJSON = JSON.stringify(userObject);
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
ajax.sendRequest({action : 'index2', outputJSON : outputJSON});
} else {
alert('Please fill all nececery fields');
}
});
});
$(document).on('pagebeforeshow', '#index2', function(){
if(userObject.name.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
$.mobile.changePage( "#index2", { transition: "slide"} ); // In case result is true change page to Index
}
$(this).find('[data-role="content"] h3').append('Deal Amended:' + userObject.name); // Change header with added message
//$("#index").trigger('pagecreate');
});
// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/test/login/amend.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (num) {
if(num == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Deal has been added successfully'); // In case result is false throw an error
$.mobile.changePage( "#index", { transition: "slide"} );
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Error: " . mysql_error() . "Query: " . $query;');
}
});
}
}
// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
tname : "",
desc : "",
dealid: ""
}
The above should be called when the button is being pressed but most of the time I cant even get to the stage of seeing the button once I add the referecne to this code.
If anybody has had the same issue as this before or can shed some light on the problem I'd really appreciate it.
Your problem is related to jQuery Mobile page handling.
Because you are using multiple HTML pages loaded with ajax into the DOM all your js scripts must be referenced from the first HTML files. All other HTML files will be loaded only partially, only BODY part will be loaded while HEAD is going to be discarded.

Categories

Resources