I have a button on previous page which redirects to this page but the problem is when the page loads it doesn't show the confirm box. I get this error
Uncaught RangeError: Maximum call stack size exceeded
The code for the page:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
//script
<script type="text/javascript">
function confirm(){
var con = confirm("Are You Sure?");
if(con = true){
window.location = "delete.php";
}
else{
history.go(-1);
}
}
</script>
<body onload="confirm()">
</body>
</html>
You have two issues in your javascript code:
You have named your function to be the same as the reserved function you are trying to call.
Your comparison is actually an assign
To fix the first problem, simply change the name of your function to something else like confirmDeletion()
<script>function confirmDeletion() { /* do stuff */ }</script>
<body onload="confirmDeletion()">
To fix the second problem, change the comparison. In javascript, the if statement automatically coerces the input into a boolean, meaning you don't actually need to compare it to true.
if (con) {
/* do confirmed true stuff */
} else {
/* do confirmed false stuff */
}
For future reference, make sure to always use triple equal === sign for comparison, otherwise you will get unexpected behavior.
You're always going to go back 1 page because you are not evaluating your condition correctly.
if (con = true) {
window.location = "delete.php";
}
Should be
if (con == true) {
window.location = "delete.php";
}
Note the additional =, = is an assignment operator and == is used to compare and evaluate the condition.
Try renaming your function from confirm to something else. The problem is that you're going into an infinite loop by calling confirm inside your confirm function.
So for example, this would work as I've renamed confirm to myConfirm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
//script
<script type="text/javascript">
function myConfirm(){
var con = confirm("Are You Sure?");
if(con = true){
window.location = "delete.php";
}
else{
history.go(-1);
}
}
</script>
<body onload="myConfirm()">
</body>
Edit
Also change con = true to con == true to check if con is true rather than assigning it the value true.
Change the name of the function. The condition, if(con = true)is assigning truthy value to con You should be comparing for truthy value like if(con). You should be doing,
<script type="text/javascript">
function confirmNavigation(){
var con = confirm("Are You Sure?");
if(con){
window.location = "delete.php";
}
else{
history.go(-1);
}
}
</script>
Related
Edit: Just confirming: I want what the user typed to be saved so that when he reloads/leaves the webpage and comes back what he wrote earlier is still there.
I tried using cookies but it only put one line of Default(variable) when I reloaded the page. Im trying to get it to work with localStorage now but it sets the textarea to "[object HTMLTextAreaElement]" or blank when I reload. I read that this error can be caused by forgetting to add the .value after getElementById() but I did not make this mistake. I am hosting and testing the webpage on Github(pages). What am I doing wrong? here is the code(ignore the comments also it might not work in jsfiddle bc it localstorage didn't work there for me):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>le epic web page</title>
</head>
<body><!--
= "\n"-->
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
<script>
var Default="P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if(localStorage.getItem("P") == ""){
document.getElementById("txt").value=Default;
localStorage.setItem("P")=Default;
}else{
document.getElementById("txt").value=localStorage.getItem("P");
}
//update cookie (called when typed)
function save(){
var txt=document.getElementById("txt").value;
//txt=txt.replace(/\r\n|\r|\n/g,"</br>");
localStorage.setItem("P",txt);//set cookie to innerHTML of textArea, expires in 1 day
}
//when page closed/reloaded
window.onbeforeunload = function(){
localStorage.setItem("P",txt);//update cookie when page is closed https://stackoverflow.com/a/13443562
}
</script>
</body>
</html>
When you are exiting the page, you are referencing the text element and storing that in localstorage. Since localStorage is a string it converts the html element reference into the text you see.
window.onbeforeunload = function(){
localStorage.setItem("P",txt);
}
You are doing it correctly with save, so just call save with the beforeunload event
window.addEventListener('beforeunload', save);
Another bug in the code is the line
if(localStorage.getItem("P") == ""){
when localStorage is not set, it returns null. So the check would need to be a truthy check ( or you can check for nullv)
if(!localStorage.getItem("P")){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>le epic web page</title>
</head>
<body>
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
</body>
<script>
const Default =
"P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if (
localStorage.getItem("P") === "" ||
localStorage.getItem("P") === null ||
localStorage.getItem("P") === undefined
) {
localStorage.setItem("P", Default);
} else {
let currentValue = document.getElementById("txt");
currentValue.value = localStorage.getItem("P");
}
function save() {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
}
window.onbeforeunload = function () {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
};
</script>
</html>
I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?
Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.
document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>
So, I've found this JSFiddle example. In JSFiddle works well, the problem is that, even if I search any != from "advogados" (just testing), the browser goes to: http://www.site.com/index.html?procura=teste
No jQuery conflict, no html issue.
Here's JS
$("#procura").on("submit", function(event){
// prevent form from being truely submitted
event.preventDefault();
// get value of text box
name = $("#procura_texto").val();
// compare lower case, as you don't know what they will enter into the field.
if (name.toLowerCase() == "advogados")
{
//redirect the user..
window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
}
else
{
alert("no redirect..(entered: " + name + ")");
}
});
If your javascript is somewhere in your HTML before your <form> your $("#procura") will be an empty set, so the submit-action won't be bound to anything. Try following code:
<html>
<head>
<script type="text/javascript" src="/path/to/your/jquery.js"></script>
<script type="text/javascript">
$(function() {
// This code will be run if your document is completely
// parsed by the browser, thus all below elements are
// accessible
$('#procura').on('submit', ....);
});
</script>
</head>
<body>
<form id="procura">...</form>
</body>
</html>
$(function() {}) is also known as $(document).ready(function() {}), (documentation)
You aren't defining the variable name. http://jsfiddle.net/zwbRa/59/
var name = $("#procura_texto").val();
I am making a interactive application with a text field to practice javascript, but I am finding for validation, that the case does not display innerHTML text though the rest of the function loops though. text.innerHTML works in all other cases, am I missing something here?
Javascript
function getNum(input){
if (isNaN(input)) {
oldstate = state-1;
state = 33;
console.log("Loading error Message...");
act();
}
else{return(parseInt(input, 10));}
}
function act(){
console.log("Case: "+state);
input = inputf.value;
inputf.value="";
switch(state){
case 0:
name = input;
text.innerHTML = "Well, hello there, "+name+"! Nice to meet you. What's your age?";
break;
case 1:
text.innerHTML = "Loading...";
age = getNum(input);
text.innerHTML = "So, "+name+" you are "+age+" years old!";
break;
case 33:
text.innerHTML = "That is NOT a number! Hit Submit to Return.";
console.log("Error Successfully loaded!");
state = oldstate;
break;
}
state=+1;
}
function getStr(input){
}
Here is my HTML with the text field id's. Any optimization suggestions would also be appreciated.
HTML
<!DOCTYPE html>
<html>
<head>
<title>titles are lame</title>
<link/>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="script.js"></script>
<script></script>
</head>
<body>
<div id="wrapper"><div id="text">First, let's have your name.</div>
<br>
<input type='text' id="input"><input type="submit"id="submit" onclick="act()">
</div>
<script>
var state = 0;
var inputf = document.getElementById("input");
var text = document.getElementById('text');
var input, name, age,oldstate;
document.getElementById("input").addEventListener("keydown", function(e) {
// Enter is pressed
if (e.keyCode == 13) { act(); }
}, false);
</script>
</body>
</html>
I think I know what the problem is. In case 1, you call the getNum method, it executes just fine in the correct case, calls the act() method, enters case 33 correctly, returning an error and... then keeps executing case 1. Because you didn't specify a return statement in the first case of the getNum function, age has an undefined value. It should work fine if you add this line:
if (!age) return;
just after calling the getNum method in case 1.
EDIT: I just realized you should also check how state is managed after detecting an error. Adding the line I gave you will leave a state of 33.
Click here to see the answer..
act() //Changed
Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}