My javascript function in the code given below is getting called twice - javascript

The below code is a simple number guessing game.
The function guess() is getting called twice. I am at loss of logic why it's happening.
<!DOCTYPTE html>
<html>
<head><title>Number Guessing Game version 1.0</title></head>
<body>
<form onsubmit="guess();return false;">
<p><h2>I am your host, human. I am thinking of a number between 0 and 100, including both</h2></p>
<p><input type="text" id="inputId" autocomplete="off"></input><button id="submitButton" onclick="guess()">Guess!!</button></p>
<p><span id="msgId"></span></p>
<p>Guesses Remaining:<span id="guessId"></span></p>
</body>
</form>
<script language="javascript">
var doubleRandom = Math.random();
var guessesLeft = parseInt("10");
var intRandom = Math.round((doubleRandom*100));
var spanObj = document.getElementById("msgId");
var guessObj = document.getElementById("guessId");
guessObj.innerHTML=guessesLeft;
function guess()
{
var guessedNumber = document.getElementById("inputId").value;
alert(23);
if(guessedNumber==null || guessedNumber.trim()==''){
spanObj.innerHTML="Type something, human";
return;
}
if(isNaN(guessedNumber)){
spanObj.innerHTML="That better be a number, Human.";
return;
}else{
if(guessedNumber>100){
spanObj.innerHTML="That better be a number between 0 and 100, Human.";
return;
}else{
spanObj.innerHTML="";
}
}
var accurateAnswer = Math.round(guessedNumber);
var difference = guessedNumber-intRandom;
if(difference>45){
spanObj.innerHTML="That's way too high, Human";
return;
}else if(difference<-45){
spanObj.innerHTML="That's way too low, Human";
}else if(difference<=45 && difference>0){
spanObj.innerHTML="That's high, Human";
}else if(difference>=-45 && difference<0 ){
spanObj.innerHTML="That's low, Human";
}else{
spanObj.innerHTML="Bingo!! You got it!! Refresh to play agin.";
}
if(guessesLeft<=0){
spanObj.innerHTML="You have exhausted your number of guesses. Try again. Refreshing game....";
setTimeout("location.reload(true)", 3000);
}
guessesLeft=guessesLeft-1;
guessObj.innerHTML=guessesLeft;
}
</script>
</html>

That's because you are calling it twice: Once in the button's onclick event, and once in the form's onsubmit event. Delete one of them.

Change
<button id="submitButton" onclick="guess()">Guess!!</button>
to
<input type="submit" id="submitButton" value="Guess!!" />
This way, irrespective of if you click the button, hit enter, or use some other method to submit the form, your event will fire, once.

When you are hit the enter button the form is submitted. On form submit you have the function triggering.
What you could do is to make the button submit the form when clicked.
<button onclick="form[0].submit()">guess</button>
If the button is clicked the form is submitted, therefore the function in from submission is called on button click. This works on hitting enter as well. Both way the function is triggered only once.

Related

Javascript to pull new website alert onclick

This might be an easy fix I am just not seeing, but I am trying to setup a basic delivery zone function. If you are in delivery zone, after you submit your zipcode an alert says you are in our zone and when you click ok, it takes you to the booking page. Else, say they are outside of the zone. I can't seem to get an onclick demand for the alert to take to the booking page. (P.S. All javacript brought into Squarespace)
<script type="text/javascript">
function IsValidZipCode() {
var zip = document.getElementById('txtZip').value;
var ZipArray = ["60543", "60188"];
var isValid = ZipArray.indexOf(zip); ;
(isValid );
if (isValid >= 0){
alert ('Nice! go ahead and book!')
// NEED TO LINK TO NEW WEBPAGE
return true;
}
else {
alert('Sorry, we do not offer delivery here at this time');
return false;
}
}
</script>
<form>
Please Enter Zip Code: <input id="txtZip" name="zip" type="number" />
<input onclick="IsValidZipCode()" id="Button" type="submit" value="Submit"/>
</form>
From the comments, it sounds like your problem is the submit button refreshing the page on click. You need to use e.preventDefault to prevent this.
<input onclick="IsValidZipCode(event)" id="Button" type="submit" value="Submit"/>
function IsValidZipCode(event) {
if (isValid >= 0){
event.preventDefault;
alert ('Nice! go ahead and book!')
window.location.href = 'yoururl.com'
}
}
Here's a good reference: preventDefault inside onclick attribute of a tag
https://jsfiddle.net/yLyvt30y/

Trouble updating div with javascript function

I'm working on a FizzBuzz solution. I had it working fine when I called the function onload and set the input variable with a prompt (see comments in my code), but when I added a form, called the function onclick, and tried to set the variable using getElementById, my function would not print to the div. In the original version, the output is visible after the function completes. In the updated version, the output flashes briefly and then disappears. It is as if I am immediately refreshing the screen. Any suggestions? Thanks
<script>
function fizzbuzz(){
// var num = prompt("Enter a number: ");
var num = document.getElementById("number").value;
var div3 = document.getElementById("div3");
for(var i=0; i<num; i++){
if (i%3===0 && i%5===0){
div3.innerHTML = div3.innerHTML+"Fizz Buzz<br>";
}else if (i%3===0){
div3.innerHTML = div3.innerHTML+"Fizz<br>";
}else if (i%5===0){
div3.innerHTML = div3.innerHTML+"Buzz<br>";
}else{
div3.innerHTML = div3.innerHTML+(i+1)+"<br>";
}
}
}
</script>
</head>
<body>
<!--body onload = "fizzbuzz()"-->
<div id = "div1">
<h1>Fizz Buzz</h1>
<form>
<p>Enter a number:</p><p><input type="text" name="number" id="number"/><input type="submit" value="Submit" onclick = "fizzbuzz()"/></p>
</form>
<div id="div3"></div>
</div>
</body>
Your button is of type submit - which is causing the page to post back / refresh, hence why you see it flash. Either prevent the default action with e.preventDefault or change your input to type of button, or use return false;
Prevent Default:
<!--Pass in event to the func-->
<input type="submit" value="Submit" onclick = "fizzbuzz(event)"/>
//Use it
function fizzbuzz(e) {
e.preventDefault();
...
}
Or use type button
<input type="button" value="Submit" onclick = "fizzbuzz()"/>
Or return false
function fizzbuzz(e) {
...
...
return false;
}
Your <input type="submit"> is submitting your form – and reloading the page – after your click handler runs.
You need to return false from the handler to prevent that.

Avoid page submission on button click if condition false in javascript

I am checking the textbox value in javascript. and saving to database. where as my save is of submit type. I want if textbox value is greater than 100 then it should alert. and after alert , page should not submit.
Firstly, bind the click event of that button to a function. Secondly, use event.prevent default to stop that button from submitting the form. Thirdly, validate the value you want. If validated, use form id to submit the form. Something like this:
$("#ButtonId").on("click", function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
if ($("#InputBoxID").val() < 100) {
$("#FormId").submit();
}
else {
alert("your message");
}
});
Above code is in jQuery, so do not forget to add the reference to jQuery.
I think you're looking for something like:
<form id="myForm" onsubmit="return validateForm();">
<input type="text" id="textfield"/>
<button type="submit">submit</button>
</form>
<script>
function validateForm(){
var value=parseInt(document.getElementById('textfield').value);
if(value>100){
alert('value is no good. larger then 100');
return false;
}
}
</script>
If you can show me your code I'd be happy to help you implementing such a feature.
Here you have an example of how to do it. I used a limit of 10 characters to make the test easier: Try if yourself
HTML:
<input type="text" id="myTextBox" onkeyup="checkValue(this)" maxlength="10"></input>
<input id="sendButton" type="submit" value="SEND"></inpu
JAVASCRIPT:
function checkValue(textbox) {
if (textbox.value.length > 10) {
alert("TEXT TOO LONG");
document.getElementById("sendButton").disabled = true;
}
else
document.getElementById("sendButton").disabled = false;
}

HTML/Javascript Page is resetting after submitting form

I am working on learning to make forms using HTML and Javascript. When I go to submit my form, it processes it, and I can see the result, but the page quickly resets so that the form is back to its starting state. How can I make sure the page doesn't reset when the function is done?
Here is the HTML for the form and the function that processes it:
<form name="calculator" onsubmit="return calculate(this);">
Enter the value of the house: $
<input type="text" name="homeValue" id="homeValue" size="7" /><br>
<select name="selMortgage" id="selMortgage">
<option>Select a mortgage length</option>
<option>15-year mortgage</option>
<option>30-year mortgage</option>
</select></br>
<p class="form"><input type="checkbox" name="chkDiscount" value="discount"/>Good Credit Discount?</p>
<input type="submit" value="Calculate" />
<div id="result"></div>
</form>
function calculate(form) {
var amountEntered = form.homeValue.value;
var termLength;
var interestRate;
var calc;
document.getElementById("result").innerHTML = "hi";
if (!/^\d+(\.\d{1,2})?$/.test(amountEntered))
{
alert("You did not enter an amount of money");
//form.homeValue.focus();
return;
}
if (form.chkDiscount.checked == true)
{
interestRate = .05;
}
else
{
interestRate = .06;
}
if (form.selMortgage.selectedIndex == 0)
{
alert("Select a mortgage length");
}
else if (form.selMortgage.selectedIndex == 1)
{
termLength = 15;
}
else if (form.selMortgage.selectedIndex == 2)
{
termLength = 30;
}
calc = (Math.pow(1+interestRate,termLength) * amountEntered)/(termLength*12);
document.getElementById("result").innerHTML = calc.toFixed(2);
}
It looks like you are missing a return false.
Since you are submitting the form the values are lost due to page reload.
You may try to POST your values then assign the post values on your form elements so that even after refresh youre still able to see the POST data submitted..
Try this:
Just use return false; at the end of your javascript function.
When the form is submitted, the JS function calculate will be invoked. Since the function does not return any value, undefined will be assumed. And in JS the undefined will be assumed to nothing and the form will be submitted to server and reload again. This is why you lose your data. From your code, the page just execute some JS code. So we can prevent submitting the form to keep your data. You may need to return false in calculate function to prevent submitting. Example as below:
document.getElementById("result").innerHTML = calc.toFixed(2);
return false;

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';

Categories