I have a codepen at http://codepen.io/templenaylor/pen/ggoMPZ?editors=0011
I am currently displaying a temperature that references a var:
<ul>
<li id="fTemp"></li>
</ul>
When trying to change it by clicking it, it will not work. This is the function I am using to do that:
$("#fTemp").click(function(){
if(tempSwap===false){
$("#fTemp").html(fTemp + " ℉");
tempSwap=true;
} else{
$("fTemp").html(cTemp + " ℃");
tempSwap=false;
}
});
Is there something I am not seeing within my function that is incorrect?
As pointed out by #MichaelCoker, you are missing the # in your else branch.
In addition to fixing that, I would save the element to a variable to help prevent errors in the future.
var ftemp_li = $("#fTemp");
ftemp_li.click(function(){
if(tempSwap == false){
ftemp_li.html(fTemp + " ℉");
tempSwap = true;
} else {
ftemp_li.html(cTemp + " ℃");
tempSwap = false;
}
});
http://codepen.io/anon/pen/VPyNPO?editors=0011
You are not referencing the correct selector in your else block
} else{
$("fTemp").html(
is supposed to be
} else{
$("#fTemp").html(
Also you seem to binding the click event every single time your ajax is successful.
Move it out of the callback and bind your click event in DOM ready handler.
Related
I believe javascript is holding the event in memmory but I can't figure out where and how to get around it. maybe you guys can help. I have created a JSFiddle to demonstrate the problem
JSFIDDLE
So it happens when you update one event. Then you move to another event go to update that event. It brings the old event to the new event. Changes the start and end and everything. First event updates fine.
When you click event. These functions are fired.
function eventClick(calEvent){
$('#edit-event-title').val(calEvent.code);
$('#edit-event-description').val(calEvent.description);
$('#event-start-edit-dpick').data('DateTimePicker').date(calEvent.start).format('YYYY-MM-DD');
$('#event-start-time-edit-dpick').data('DateTimePicker').date(calEvent.start).format('HH:mm');
$('#event-end-edit-dpick').data('DateTimePicker').date(calEvent.end).format('YYYY-MM-DD');
$('#event-end-time-edit-dpick').data('DateTimePicker').date(calEvent.end).format('HH:mm');
$('#fc_edit').click();
}
function createUpdateEvent(calEvent, create) {
//create event
if(create){
// create the event
} else {
$(".antosubmit2").on("click", function() {
calEvent.code = $("#edit-event-title").val();
calEvent.title = $("#edit-event-title option:selected").html();
calEvent.description = $("#edit-event-description").val();
calEvent.start = moment($('#event-start-edit-dpick').data('DateTimePicker').date().format('YYYY-MM-DD') + ' ' +
$('#event-start-time-edit-dpick').data('DateTimePicker').date().format('HH:mm') +
$('#event-start-edit-dpick').data('DateTimePicker').date().format('Z'));
calEvent.end = moment($('#event-end-edit-dpick').data('DateTimePicker').date().format('YYYY-MM-DD') + ' ' +
$('#event-end-time-edit-dpick').data('DateTimePicker').date().format('HH:mm') +
$('#event-end-edit-dpick').data('DateTimePicker').date().format('Z'));
calendar.fullCalendar('updateEvent', calEvent);
$('.antoclose').click();
});
}
}
function recalcHeaderHours(event){
var currentday = moment(event.start).format("YYYY-MM-DD");
if (event.totalHours > 0) {
var prev = $("#dailytotal-"+currentday).text() || 0;
$("#dailytotal-"+currentday).text(+prev + +event.totalHours);
}
}
I hope you guys can assist. Thanks for your time :)
I fixed your issue.
The problem is that you put the on click event to the ".antosubmit2" in line 83. On first event open there will be 1 click on this class, but on the 2. event open the code put another click on it. If you open only one event 2 times, there will be no problem. But it you do it on different events, on the second open, 2 click fires on it. The newly added click use correct data, but the first click use the first event datas. This is your problem I guess.
The first click should be unbind from the ".antosubmit2".
Try to modify your code like this:
function createUpdateEvent(calEvent, create) {
//create event
if(create){
// create the event
} else {
$(".antosubmit2").unbind('click');
$(".antosubmit2").on("click", function() {...
You see the "unbind('click')" line, add it to the code and it will works.
I am a beginner and was trying to just write something from scratch: I want to 'write' inputs from text fields into a textarea.
So I made the following
(also viewable on http://jsfiddle.net/jolarti/FX6xL/1/ )
HTML:
<input type='text' id='fruit' value='fruit'>
<br/>
<input type='text' id='salad' value='salad'>
<p>This is the meal you made:</p>
<textarea id="myText" rows="4" cols="50"></textarea>
<br />
<button>Make food</button>
SCRIPT:
$(document).ready(function () {
$("#fruit");
$("#salad");
$("button").click(function () {
var fruit = $("#fruit").val();
var salad = $("#salad").val();
if (fruit === "" || salad === "") {
alert("Type in both ingredients in order to make something!!");
} else {
//alert("Would you like " + fruit + " with some " + salad + " to have for lunch?");
var phrase = ("Would you like " + fruit + " with some " + salad + " to have for lunch?");
document.getElementById("myText").innerHTML = phrase; //writes to the textarea
return false; //i use this to end the script and not make the page disappear
}
});
});
Am I using 'return' for the right purpose here?
It works and it does what I want but... is this good practice or bad practice?
I put this 'return' in, because if I don't, the page becomes completely empty after input!
+ I need explanation on why that happens.
And I wonder: could I also use 'return' to actually write output to the screen?
Yes, that would work, but try not typing anything and you see it doesn't reach the return false; so it submits ;)
That said, try this:
<button type="button">Make food</button>
Now you don't need return false; because the button is just a button.
Is this good practice or bad practice?
In this case, it is a bad practice. return false prevent the default behaviour and the event propagation. That can lead to unwanted behaviour if, for example, you want to stop the default behaviour but not the propagation or vice versa.
It is much better to use function available on the event to stop that. To use those function, you need to get the event as argument. Just write the click function like that :
$("button").click(function (e) { //Here e == Event
//Do something
e.stopPropagation(); //Prevent event from bubling
e.preventDefault(); //Prevent the default behaviour of the HTML element
}
I need explanation on why that happens
As stated above, return false prevent default behaviour. The default behaviour of a button is to send the form. That action reload the page, hence why it become blank.
To counter that, you just have to prevent the default behaviour with, wait for it, what you just learn!
$(document).ready(function () {
$("#fruit"); //What are those useless jQuery objects? ;)
$("#salad");
$("button").click(function (e) { //Don't forget the event
e.preventDefault();
var fruit = $("#fruit").val();
var salad = $("#salad").val();
if (fruit === "" || salad === "") {
alert("Type in both ingredients in order to make something!!");
} else {
//alert("Would you like " + fruit + " with some " + salad + " to have for lunch?");
var phrase = ("Would you like " + fruit + " with some " + salad + " to have for lunch?");
document.getElementById("myText").innerHTML = phrase; //writes to the textarea
}
});
});
It works, but it's kind of a legacy feature. The modern way to do this is:
$(...).on('click', function(event) {
event.preventDefault();
}
Also makes clearer what you're doing: preventing the browser's default behavior.
But in this case it's far more appropriate to just use a plain button as Niet says, so there is no default behavior. Saves you from oversights like, for example, how you don't prevent the default behavior when there's an error. :)
Other minor comments:
You're binding this behavior to every single <button> on the page, which will be surprising as soon as you add a second one; you probably want an id on that button.
Don't use .innerHTML when you have plain text! It's easy to accidentally inject HTML tags, because most of the time it appears to work. Assign to .textContent instead, or use $(...).text(some_text).
This won't work very well for bots or scrapers or when your JS fails to load or for people like me who whitelist JavaScript. :) (Another reason to use a plain button instead of a submit button!) Doesn't matter much when you're experimenting, but something that's good to keep in mind in general. If a browser already has a feature you want, just use it, then add the JS on top if necessary.
Yes, you can return at any time to end a function in JavaScript. The reason your page disappears is because it is trying to send the form data to the server; of course, since you've specified no method or action, it is doing nothing, thus the blank page.
Instead, you can remove the
<Form></Form>
tag if you're not planning to send this information back to any server on a button press. Also, your two calls to $("#fruit"); and $("#salad"); are unnecessary, as they aren't actually performing any action on the nodes after selecting them. You can simply your code to the following:
$(document).ready(function () {
$("button").click(function () {
var fruit = $("#fruit").val();
var salad = $("#salad").val();
if (fruit === "" || salad === "") {
alert("Type in both ingredients in order to make something!!");
return; //end the function if this is invalid
}
var phrase = "Would you like " + fruit + " with some " + salad + " to have for lunch?";
$("#myText").html(phrase); //writes to the textarea using jquery
});
});
Fiddle example: http://jsfiddle.net/FX6xL/2/
I'm working on a quiz game, wherein the user is presented with a quote and has to guess the author:
function startGame(quotes) {
askQuestion(quotes[0], 0, 0);
function askQuestion(quote, question, score) {
var q = "<span class='quo'>“</span><em>" + quote.quote + "</em><span class='quo'>”</span>";
$('.choice').css('visibility', 'visible');
$('#questions').html(q);
$('.choice').click(function(e){
$('.choice').css('visibility', 'hidden');
e.preventDefault();
var nextq = (question + 1);
var btntxt = (nextq < number_of_questions ? 'Next...' : 'Final results');
if ($(this).attr('data-author') === quote.author) {
score++;
$('#questions').html('<h1>Correct.</h1><a class="btn next">' + btntxt + '</a>');
document.getElementById('win').play();
} else {
$('#questions').html('<h1>Wrong.</h1><a class="btn next">' + btntxt + '</a>');
document.getElementById('lose').play();
}
$('#questions').append('<h4>Score: ' + score + '/' + nextq + '</h4>');
$('.next').on("click", function(){
question += 1;
if (question < number_of_questions) {
askQuestion(quotes[question], question, score);
} else {
tallyScore(score);
}
});
});
}
}
When a question is asked, the askQuestion() function is called again if fewer than 6 questions have been asked.
Everything works great, but I'm having issues with the sound effects. If a user gets an answer right and then an answer wrong, both the "win" and "lose" sound effects are played simultaneously.
My guess is that this has something to do with my recursively calling askQuestion() -- it seems like the entire "history" of the function is looped through. I was having a similar problem earlier — on correct answers, the score global variable was incremented by the number of previously correct answers (instead of just by one).
Any idea how I can fix that? Thanks!
Edit: As requested, here's a JSfiddle.
easy fix actually. you are re-attaching the click listener over and over, so just remove it each time it gets set.
change
$('.choice').click(function (e) {
to
$('.choice').off().click(function (e) {
http://jsfiddle.net/NADYM/
Every time askQuestion is called, you add an event handler to the html elements. So when you click on the .choice element, multiple events are run.
Try giving a unique id to all generated element and use that id to attach event handlers.
In my application after tapping on a one button it gives and alert.There are two button on alert window: 1. Cancel 2. Ok
I have tried to tap on OK by using the solution given on the forum but it dosen't work.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered!");
if (title == "Attention")
{
alert.buttons()["OK"].tap();
return true; // bypass default handler
}
return false; // use default handler
}
Function for handling alert dosen't called.Can anyone help me on this issue?
Thanks in advance.
UIATarget.onAlert = function onAlert(alert)
{
UIATarget.localTarget().delay(1);
UIALogger.logMessage("alertShown");
target.captureScreenWithName("AlertCaptured");
return true;
}
app.alert().buttons()["OK"].tap();
My solution to this problem was to add an one second delay after the function that handles the alert. You can not end your script with that function.
UIATarget.onAlert = function onAlert(alert) {
var title = alert.name();
UIALogger.logWarning("Alert with title '" + title + "' encountered.");
if (title == "Are you sure you want to delete this?") {
alert.buttons()["Delete"].tap();
return true; //alert handled, so bypass the default handler
}
return false;
}
target.delay(1);
function Open() {
var cc = document.getElementById('FName');
if ('Newfile.rtf' == cc.innerHTML)
{
alert("New File");
} //close If NewFile.rtf
else {
alert("Not new file");
}
}//close Open()
Here I have string "NewFile.rtf" in a element with id="FName" on the page. When the FName contains "Newfile.rtf" in it it stills goes to the else part of the function instead of going to if part. I tried different ways to write the compare statement in the if condition, no luck . Appreciate the help if anyone can help figure out this.
Thank you.
The simplest explanation is that your cc.innerHTML call is not returning what you think it is returning. Why don't you console.log or debug.
add something like
var innerhtml = cc.innerHTML;
console.log("innerHTML = " + innerhtml) // wont work in IE.
before the if statement.
Try using regular expressions to find your filename, also check if the text you are searching is not into another DOM element, elimate left and right spaces, you should use Google Chrome for debuging the Javascript code:
var html = document.getElementById('FName').innerHTML;
if( html.search("Newfile.rtf") != -1) { /*found*/ }
else { /*not found*/ }
but what's the type of this element? if it's about an input text type .. you can't use innerHTML but you'll use value then.
Use innerText to get that
function Open() {
var cc = document.getElementById('FName');
if ('Newfile.rtf' == cc.innerText)
{
alert("New File");
} //close If NewFile.rtf
else {
//enter code here
alert("Not new file");
}
}