I use jquery mobile build a alarm project, i created two page in my index.html, when i click Add Alarm button, the dialog page show up, then i can set the alarm date and time, I want to use setInterval to trigger alarm when i click save button.
But in found that, the function in setInterval doesn't work. How could this happen?
Below is my html file:
<div data-role="page" id="pageone">
<div data-role="header">
<h1>Share Alarm</h1>
Add Alarm
</div>
<ul data-role="listview">
...
</ul>
</div>
<div data-role="page" id="addNewAlarm">
<div data-role="header">
<h1>New Alarm</h1>
</div>
<div data-role="content">
<form action="" method="post" data-ajax="false" id="setAlarm">
<div data-role="fieldcontain">
<input id="alarmTitle" type="text" placeholder="title" data-inline="true"/>
<input id="alarmDate" type="date" data-role="datebox" name="alarmdate"
data-options='{"mode":"calbox","useFocus": true, "useNewStyle":true}' class="ui-icon-datebox"
readonly/>
<input id="alarmTime" type="datetime" data-inline="true" data-role="datebox"
data-options='{"mode":"timeflipbox","useFocus": true, "useNewStyle":true}'
class="ui-icon-datebox"/>
</div>
<input type="submit" value="Save" data-inline="true" data-icon="check" id="saveAlarm"/>
</form>
</div>
<div data-role="footer"></div>
</div>
and this is my js file:
$(document).ready(function () {
$("#saveAlarm").click(function () {
var deStr = $("#alarmDate").datebox('getTheDate').toLocaleDateString();
var dtStr = $("#alarmTime").datebox('getTheDate').toTimeString();
setTimer($("#alarmTitle").val(),deStr,dtStr);
setInterval(function(){alert(1111);},1000);
alert(123);
});
});
function setTimer(title,dateStr,timeStr) {
var timer = setInterval(function(){
var now=new Date();
console.log(now.toTimeString());
if(now.toLocaleDateString() == dateStr && now.toTimeString() == timeStr){
alert("Alarm "+title+"has gone off !");
// clearInterval(timer);
}
},1000);
return timer;
}
Both two setInterval function didn't work. What's wrong with my code?
I finally figure it out, Same like #Khanh TO commented, i used below js code instead of my original one, and it works well now.
var timer=[],timerId,deStr,dtStr;
$(document).on("pagehide", "#addNewAlarm", function () {
$("#saveAlarm").click(function () {
deStr = $("#alarmDate").datebox('getTheDate').toLocaleDateString();
dtStr = $("#alarmTime").datebox('getTheDate').toTimeString().substring(0, 5);
if ($.inArray(timerId,timer) == -1) {
setTimer($("#alarmTitle").val(),deStr,dtStr);
timer.push(timerId);
}
});
});
function setTimer(title, dateStr, timeStr) {
var timer = setInterval(function () {
var now = new Date();
console.log(now.toTimeString());
if (now.toLocaleDateString() == dateStr && now.toTimeString().substring(0, 5) == timeStr) {
alert("Alarm " + title + "has gone off !");
clearInterval(timer);
}
}, 1000);
return timer;
}
jQuery Mobile automatically enhances pages by registering its functions to handle the jQuery ready. If you want to include custom JavaScript
in a document, you have to take care not to have your code executed before jQuery Mobile has finished
processing the document. This means you have to wait for a different event, called pageinit
$(document).on("pageinit", function() {
//Your code.
});
Or you could try delegated event:
$(document).on("click","#saveAlarm",function () {
var deStr = $("#alarmDate").datebox('getTheDate').toLocaleDateString();
var dtStr = $("#alarmTime").datebox('getTheDate').toTimeString();
setTimer($("#alarmTitle").val(),deStr,dtStr);
setInterval(function(){alert(1111);},1000);
alert(123);
});
Related
I am getting an error when attempting to run a function once a checkbox is being checked. The above error appears consistently each time I am attempting to run it. Heres the code:
HTML:
<body>
<header>
<div class="header_container">
<h1>Trivia Quiz</h1>
<p>Welcome to the Trivia Quiz 2020!</p>
<p>The aim of the game is to get as many questions correct as possible!<br> The topics range from film to geography, so good luck!</p>
<div class="header_settings" id="header_settings">
<input type="checkbox" id="checkbox" onclick="TimeToggle()">
<label for="TimeToggle">Time Limit</label><br>
<input type="text" id="Timer" name="Timer" placeholder="Seconds" id="header_input">
</div>
<button>Start</button>
</div>
</header>
</body>
And Javascript (stored externally, linked in the head of the HTML document.):
var header_input = document.getElementById("header_input");
var header_settings = document.getElementById("header_settings");
var checkbox = document.getElementById("checkbox");
function TimeToggle() {
if (checkbox.checked) {
header_settings.style.height = "3%";
setTimeout(function () {
header_input.style.display = "none";
}, 500);
} else {
header_settings.style.height = "10%";
setTimeout(function () {
header_input.style.display = "block";
}, 500);
}
}
The code is intended to toggle the height of the div named "header_settings", and the display setting of the input named "header_input" depending on whether the checkbox is checked.
I would appreciate any pointers regarding how this is not working, I have tried a lot. Thanks :)
Is this what you are trying to do ? You can use an onchange function and pass this as an argument and check if in your toggle function if input is checked or unchecked.
Also, you have had two id selectors on your input which is not possible.
In addition, please ensure that your scripts.js is loading just added before the </body> end tag
Add this code as your HTML input
<input type="checkbox" id="checkbox" onchange="TimeToggle(this)">
Live Working Demo:
function TimeToggle(el) {
var header_input = document.getElementById("header_input");
var header_settings = document.getElementById("header_settings");
var checkbox = document.getElementById("checkbox");
if (el.checked) {
header_settings.style.height = '50px';
setTimeout(function() {
header_input.style.display = "none";
}, 500);
} else {
header_settings.style.height = '100px';
setTimeout(function() {
header_input.style.display = "block";
}, 500);
}
}
<body>
<header>
<div class="header_container">
<h1>Trivia Quiz</h1>
<p>Welcome to the Trivia Quiz 2020!</p>
<p>The aim of the game is to get as many questions correct as possible!<br> The topics range from film to geography, so good luck!</p>
<div class="header_settings" id="header_settings">
<input type="checkbox" id="checkbox" onchange="TimeToggle(this)">
<label for="TimeToggle">Time Limit</label><br>
<input type="text" name="Timer" placeholder="Seconds" id="header_input">
</div>
<button>Start</button>
</div>
</header>
</body>
Your problem is a very common one. You are trying to get the html elements using document.get... before the DOM has loaded. You need to wrap those document fetches in the onload listener for the window:
let checkbox;
window.onload = function() {
checkbox = document.getElementById();
};
function TimeToggle() {//...}
Place the external JS to at the end. Just before</body>. And your problem will be solved.
Somewhat like
<body>
<!--Your HTML content here-->
<script src = "External Js.js"></script>
</body>
How a javascript popup can be restricted to show on only first three visits for a page?
here is the html code
<div id="vr-apper" style='display:none'>
<div id="popup">
<center>
<!-- Content -->
<input class="procced_pop_btn" type="submit" name="submit" value="Proceed" onClick="PopUp('hide')" />
</center>
</div>
</div>
Here is javascript code to show popup
<script>
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') document.getElementById('vr-apper').style.display = "none";
else document.getElementById('vr-apper').removeAttribute('style');
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
</script>
I would recommend using cookies that increments by 1 using incremention method ++ of JavaScript, and if the cookies value is 4 or above it won't show the popup!
I am fairly new to this and I need help making the link "login" to be replaced with logged in after clicking submit with javascript/jquery.
Here is what I have on my index page. Currently I have a pop up login page and I need to stop the function after clicking the word submit and then replace login with logged in.
This is a simple demo site and only needs simple code. Thank you!
<Head>
<script type='text/javascript' charset='utf-8'>
$(document).ready(function(){
$('.popbox').popbox();
});
<div id= "toggle" class='popbox'>
<a div id=login class='open' href='#'>Login</a>
<div class='collapse'>
<div class='box'>
<div class='arrow'></div>
<div class='arrow-border'></div>
<form name="myform" action="#" method="post" id="subForm">
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId:'193731474136796', cookie:true,
status:true, xfbml:true
});
</script>
<img src="facebookbutton.png">
<script>
//your fb login function
function fblogin() {
FB.login(function(response) {
//...
}, {scope:'read_stream,publish_stream,offline_access'});
}
</script>
<div class="line-separator"></div>
<div class="input">
<input type="username" name="cm-name" id="name" placeholder="Username" />
</div>
<div class="input">
<input type="password" name="cm-password" id="password" placeholder="Password" />
</div>
<input type="submit" value="login" id="submit" /> Forgot Username or Password?
</form>
And I have a linked javascript page for the popup.
(function(){
$.fn.popbox = function(options){
var settings = $.extend({
selector : this.selector,
open : '.open',
box : '.box',
arrow : '.arrow',
arrow_border : '.arrow-border',
close : '.close'
}, options);
var methods = {
open: function(event){
event.preventDefault();
var pop = $(this);
var box = $(this).parent().find(settings['box']);
box.find(settings['arrow']).css({'left': box.width()/2 - 10});
box.find(settings['arrow_border']).css({'left': box.width()/2 - 10});
if(box.css('display') == 'block'){
methods.close();
} else {
box.css({'display': 'block', 'top': 10, 'left': ((pop.parent().width()/2) -box.width()/2 )});
}
},
close: function(){
$(settings['box']).fadeOut("fast");
}
};
$(document).bind('keyup', function(event){
if(event.keyCode == 27){
methods.close();
}
});
$(document).bind('click', function(event){
if(!$(event.target).closest(settings['selector']).length){
methods.close();
}
});
return this.each(function(){
$(this).css({'width': $(settings['box']).width()}); // Width needs to be set otherwise popbox will not move when window resized.
$(settings['open'], this).bind('click', methods.open);
$(settings['open'], this).parent().find(settings['close']).bind('click', function(event){
event.preventDefault();
methods.close();
});
});
}
}).call(this);
EDIT:
I figured out what was wrong. Thank you guys!
jsfiddle
This is a pretty simple solution. It replaces the login link with a span that contains the text you wanted.
http://jsfiddle.net/gVVcM/
jQuery:
$('button').on('click',function(){
$('#login').replaceWith('<span>Logged In</span>');
});
HTML:
<a id='login' href='#'>Log In</a>
<button>Submit</button>
edit: now that you posted the submit id.
$('#submit').on('click',function(){
$('#login').replaceWith('<span>Logged In</span>');
});
edit2: Prevent Default?.
$('#submit').on('click',function(e){
e.preventDefault();
$('#login').replaceWith('<span>Logged In</span>');
});
If you're using jQuery you can call the following once you've successfully logged in.
$('a#login.open').text('Logged In');
This is if you're trying to be super specific about the element you're searching for. If you are using chrome or anything other than IE you can try this out in the console debugger window to see that it works.
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.
I used ui-tabs ,this is the code iam used:
<script type="text/javascript">
$(function () {
$('#tabs').tabs({ event: '' });
});
function validateContact() {
var fname = $('#first_name1').val();
if (fname == '') {
alert("Enter Name");
} else {
$('#tabs').tabs({ event: 'click' });
doitcontact();
}
}
function doitcontact() {
var cnt = $("#frmdocontact").serialize();
$.ajax({
type: "POST",
url: "doitcontact.php",
data: cnt,
success: function (msg) {
var spt = msg.split('#$#$');
//alert(spt);
$('#hid_uid').val(spt[0]);
$('#custom').val(spt[0]);
$('#hid_add_vehicle').val(spt[0]);
$('#hid_saleid').val(spt[1]);
var valreturn = $("#return").val();
if (valreturn) {
valreturn = valreturn + "?cntdoit=" + spt[0];
$("#return").val(valreturn);
}
//alert(msg);
//console.log(contactSent);
var pkg = $('input:radio[name=pkg]:checked').val();
var $tabs = $('#tabs').tabs();
var selected = $tabs.tabs('option', 'selected');
$tabs.tabs('select', selected + 1);
//window.location="thankyou.php"
}
});
}
</script>
<ul>
<li id="tabVInfo">Contact Information</li>
<li id="tabVCond">Vehicle Information</li>
<li id="tabVPhoto">Additional Vehicle Information</li>
<li id="tabVCheck">Check Out</li>
</ul>
<div id="tabs-2">
<form id="frmdocontact" name="frmdocontact" method="post">
<input id="first_name1" maxlength="40" name="first_name" size="20" type="text" />
<input type="button" id="sub" name="sub" value="Next >>" class="next-product" onclick="validateContact();" />
</form>
</div>
<div id="tabs-">hhhhhhhhh</div>
<div id="tabs-4">kkkkkkkk</div>
<div id="tabs-5">llllllllll</div>
I want to remove the clicked event when the page is loaded.That is working correctly.
Then i have to be able to click on tabs if already filled out data. so if i filled out page 1 and 2 and am on 3 then they should be able to click on the 1 or 2 tab and it should have the already entered data in it.
Here page 1 and 2 means divs.In my code when i load the page the tabs are not clickable.Then i enter datas into page 1 and click on nex button then it goes to 2nd page and all tabs are now clickable.
But i actually need to page 1 tabs pnly shoud be clickable.
How can i do this?
Can anyone have solve it?
if there is any solution for that?.............
Give a solution ASAP...........
Just remove the {event: ''} inside your tabs calling to enable all clicks. Then you change the HREF of the tab you want to disable. In this example I have disabled the check out tab.
$("#tabs").tabs();
$("#tabVCheck > a").attr("href", "#");
you can test it here:
http://jsfiddle.net/nKsZF/28/