Trouble updating div with javascript function - javascript

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.

Related

How to pass clicked button value to javascript on form submit [duplicate]

I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click() event to each one.
Here's the setup:
<html>
<head>
<title>jQuery research: forms</title>
<script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var me = event.currentTarget;
var data = me.data.value;
var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
</script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
<input type='hidden' name='data' value='blahdatayadda' />
<input type='submit' name='name1' value='value1' />
<input type='submit' name='name2' value='value2' />
</form>
</body>
</html>
Live example on jsfiddle
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
I asked this same question: How can I get the button that caused the submit from the form submit event?
I ended up coming up with this solution and it worked pretty well:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val();
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
In your case with multiple forms you may need to tweak this a bit but it should still apply
I found that this worked.
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
This works for me:
$("form").submit(function() {
// Print the value of the button that was clicked
console.log($(document.activeElement).val());
}
When the form is submitted:
document.activeElement will give you the submit button that was clicked.
document.activeElement.getAttribute('value') will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement will be whichever form input that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
There is a native property, submitter, on the SubmitEvent interface.
Standard Web API:
var btnClicked = event.submitter;
jQuery:
var btnClicked = event.originalEvent.submitter;
Here's the approach that seems cleaner for my purposes.
First, for any and all forms:
$('form').click(function(event) {
$(this).data('clicked',$(event.target))
});
When this click event is fired for a form, it simply records the originating target (available in the event object) to be accessed later. This is a pretty broad stroke, as it will fire for any click anywhere on the form. Optimization comments are welcome, but I suspect it will never cause noticeable issues.
Then, in $('form').submit(), you can inquire what was last clicked, with something like
if ($(this).data('clicked').is('[name=no_ajax]')) xhr.abort();
Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').
$(document).ready(function(){
var clkBtn = "";
$('input[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
$("#myForm").submit(function(evt) {
var btnID = clkBtn;
alert("form submitted; button id=" + btnID);
});
});
I have found the best solution is
$(document.activeElement).attr('id')
This not only works on inputs, but it also works on button tags.
Also it gets the id of the button.
Another possible solution is to add a hidden field in your form:
<input type="hidden" id="btaction"/>
Then in the ready function add functions to record what key was pressed:
$('form#myForm #btnSubmit').click(function() {
$('form#myForm #btaction').val(0);
});
$('form#myForm #btnSubmitAndSend').click(function() {
$('form#myForm #btaction').val(1);
});
$('form#myForm #btnDelete').click(function() {
$('form#myForm #btaction').val(2);
});
Now in the form submition handler read the hidden variable and decide based on it:
var act = $('form#myForm #btaction').val();
Building on what Stan and yann-h did but this one defaults to the first button. The beauty of this overall approach is that it picks up both the click and the enter key (even if the focus was not on the button. If you need to allow enter in the form, then just respond to this when a button is focused (i.e. Stan's answer). In my case, I wanted to allow enter to submit the form even if the user's current focus was on the text box.
I was also using a 'name' attribute rather than 'id' but this is the same approach.
var pressedButtonName =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
$(":input[type=submit]:first")[0].name :
$(":input[type=submit]:focus")[0].name;
This one worked for me
$('#Form').submit(function(){
var btn= $(this).find("input[type=submit]:focus").val();
alert('you have clicked '+ btn);
}
Here is my solution:
$('#form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
If what you mean by not adding a .click event is that you don't want to have separate handlers for those events, you could handle all clicks (submits) in one function:
$(document).ready(function(){
$('input[type="submit"]').click( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var input = $(event.currentTarget);
var which_button = event.currentTarget.value;
var data = input.parents("form")[0].data.value;
// var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
As I can't comment on the accepted answer, I bring here a modified version that should take into account elements that are outside the form (ie: attached to the form using the form attribute). This is for modern browser: http://caniuse.com/#feat=form-attribute . The closest('form') is used as a fallback for unsupported form attribute
$(document).on('click', '[type=submit]', function() {
var form = $(this).prop('form') || $(this).closest('form')[0];
$(form.elements).filter('[type=submit]').removeAttr('clicked')
$(this).attr('clicked', true);
});
$('form').on('submit', function() {
var submitter = $(this.elements).filter('[clicked]');
})
You can simply get the event object when you submit the form. From that, get the submitter object. As below:
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
}
In case you want to send this form to the backend, you can create a new form element by new FormData() and set the key-value pair for which button was pressed, then access it in the backend. Something like this -
$(".review-form").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
let form = $(this);
let newForm = new FormData($(form)[0]);
let submitter_btn = $(e.originalEvent.submitter);
console.log(submitter_btn.attr("name"));
if (submitter_btn.attr("name") == "approve_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else if (submitter_btn.attr("name") == "reject_btn") {
newForm.set("action_for", submitter_btn.attr("name"));
} else {
console.log("there is some error!");
return;
}
}
I was basically trying to have a form where user can either approve or disapprove/ reject a product for further processes in a task.
My HTML form is something like this -
<form method="POST" action="{% url 'tasks:review-task' taskid=product.task_id.id %}"
class="review-form">
{% csrf_token %}
<input type="hidden" name="product_id" value="{{product.product_id}}" />
<input type="hidden" name="task_id" value="{{product.task_id_id}}" />
<button type="submit" name="approve_btn" class="btn btn-link" id="approve-btn">
<i class="fa fa-check" style="color: rgb(63, 245, 63);"></i>
</button>
<button type="submit" name="reject_btn" class="btn btn-link" id="reject-btn">
<i class="fa fa-times" style="color: red;"></i>
</button>
</form>
Let me know if you have any doubts.
Try this:
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){
// This is the ID of the clicked button
var clicked_button_id = event.originalEvent.submitter.id;
});
});
$("form input[type=submit]").click(function() {
$("<input />")
.attr('type', 'hidden')
.attr('name', $(this).attr('name'))
.attr('value', $(this).attr('value'))
.appendTo(this)
});
add hidden field
For me, the best solutions was this:
$(form).submit(function(e){
// Get the button that was clicked
var submit = $(this.id).context.activeElement;
// You can get its name like this
alert(submit.name)
// You can get its attributes like this too
alert($(submit).attr('class'))
});
Working with this excellent answer, you can check the active element (the button), append a hidden input to the form, and optionally remove it at the end of the submit handler.
$('form.form-js').submit(function(event){
var frm = $(this);
var btn = $(document.activeElement);
if(
btn.length &&
frm.has(btn) &&
btn.is('button[type="submit"], input[type="submit"], input[type="image"]') &&
btn.is('[name]')
){
frm.append('<input type="hidden" id="form-js-temp" name="' + btn.attr('name') + '" value="' + btn.val() + '">');
}
// Handle the form submit here
$('#form-js-temp').remove();
});
Side note: I personally add the class form-js on all forms that are submitted via JavaScript.
Similar to Stan answer but :
if you have more than one button, you have to get only the
first button => [0]
if the form can be submitted with the enter key, you have to manage a default => myDefaultButtonId
$(document).on('submit', function(event) {
event.preventDefault();
var pressedButtonId =
typeof $(":input[type=submit]:focus")[0] === "undefined" ?
"myDefaultButtonId" :
$(":input[type=submit]:focus")[0].id;
...
}
This is the solution used by me and work very well:
// prevent enter key on some elements to prevent to submit the form
function stopRKey(evt) {
evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
var alloved_enter_on_type = ['textarea'];
if ((evt.keyCode == 13) && ((node.id == "") || ($.inArray(node.type, alloved_enter_on_type) < 0))) {
return false;
}
}
$(document).ready(function() {
document.onkeypress = stopRKey;
// catch the id of submit button and store-it to the form
$("form").each(function() {
var that = $(this);
// define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit,button", that).bind("click keypress", function(e) {
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
$("#form1").submit(function(e) {
var origin_id = $(e.target).data("callerid");
alert(origin_id);
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1" name="form1" action="" method="post">
<input type="text" name="text1" />
<input type="submit" id="button1" value="Submit1" name="button1" />
<button type="submit" id="button2" name="button2">
Submit2
</button>
<input type="submit" id="button3" value="Submit3" name="button3" />
</form>
This works for me to get the active button
var val = document.activeElement.textContent;
It helped me https://stackoverflow.com/a/17805011/1029257
Form submited only after submit button was clicked.
var theBtn = $(':focus');
if(theBtn.is(':submit'))
{
// ....
return true;
}
return false;
I was able to use jQuery originalEvent.submitter on Chrome with an ASP.Net Core web app:
My .cshtml form:
<div class="form-group" id="buttons_grp">
<button type="submit" name="submitButton" value="Approve" class="btn btn-success">Approve</button>
<button type="submit" name="submitButton" value="Reject" class="btn btn-danger">Reject</button>
<button type="submit" name="submitButton" value="Save" class="btn btn-primary">Save</button>
...
The jQuery submit handler:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function() {
...
// Ensure that we log an explanatory comment if "Reject"
$('#update_task_form').on('submit', function (e) {
let text = e.originalEvent.submitter.textContent;
if (text == "Reject") {
// Do stuff...
}
});
...
The jQuery Microsoft bundled with my ASP.Net Core environment is v3.3.1.
Let's say I have these "submit" buttons:
<button type="submit" name="submitButton" id="update" value="UpdateRecord" class="btn btn-primary">Update Record</button>
<button type="submit" name="submitButton" id="review_info" value="ReviewInfo" class="btn btn-warning sme_only">Review Info</button>
<button type="submit" name="submitButton" id="need_more_info" value="NeedMoreInfo" class="btn btn-warning sme_only">Need More Info</button>
And this "submit" event handler:
$('#my_form').on('submit', function (e) {
let x1 = $(this).find("input[type=submit]:focus");
let x2 = e.originalEvent.submitter.textContent;
Either expression works. If I click the first button, both "x1" and "x2" return Update Record.
I also made a solution, and it works quite well:
It uses jQuery and CSS
First, I made a quick CSS class, this can be embedded or in a seperate file.
<style type='text/css'>
.Clicked {
/*No Attributes*/
}
</style>
Next, On the click event of a button within the form,add the CSS class to the button. If the button already has the CSS class, remove it. (We don't want two CSS classes [Just in case]).
// Adds a CSS Class to the Button That Has Been Clicked.
$("form :input[type='submit']").click(function ()
{
if ($(this).hasClass("Clicked"))
{
$(this).removeClass("Clicked");
}
$(this).addClass("Clicked");
});
Now, test the button to see it has the CSS class, if the tested button doesn't have the CSS, then the other button will.
// On Form Submit
$("form").submit(function ()
{
// Test Which Button Has the Class
if ($("input[name='name1']").hasClass("Clicked"))
{
// Button 'name1' has been clicked.
}
else
{
// Button 'name2' has been clicked.
}
});
Hope this helps!
Cheers!
You can create input type="hidden" as holder for a button id information.
<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.
A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':
$("button").click(function() {
var id = $(this).attr('id');
...
});
Here is a sample, that uses this.form to get the correct form the submit is into, and data fields to store the last clicked/focused element. I also wrapped submit code inside a timeout to be sure click events happen before it is executed (some users reported in comments that on Chrome sometimes a click event is fired after a submit).
Works when navigating both with keys and with mouse/fingers without counting on browsers to send a click event on RETURN key (doesn't hurt though), I added an event handler for focus events for buttons and fields.
You might add buttons of type="submit" to the items that save themselves when clicked.
In the demo I set a red border to show the selected item and an alert that shows name and value/label.
Here is the FIDDLE
And here is the (same) code:
Javascript:
$("form").submit(function(e) {
e.preventDefault();
// Use this for rare/buggy cases when click event is sent after submit
setTimeout(function() {
var $this=$(this);
var lastFocus = $this.data("lastFocus");
var $defaultSubmit=null;
if(lastFocus) $defaultSubmit=$(lastFocus);
if(!$defaultSubmit || !$defaultSubmit.is("input[type=submit]")) {
// If for some reason we don't have a submit, find one (the first)
$defaultSubmit=$(this).find("input[type=submit]").first();
}
if($defaultSubmit) {
var submitName=$defaultSubmit.attr("name");
var submitLabel=$defaultSubmit.val();
// Just a demo, set hilite and alert
doSomethingWith($defaultSubmit);
setTimeout(function() {alert("Submitted "+submitName+": '"+submitLabel+"'")},1000);
} else {
// There were no submit in the form
}
}.bind(this),0);
});
$("form input").focus(function() {
$(this.form).data("lastFocus", this);
});
$("form input").click(function() {
$(this.form).data("lastFocus", this);
});
// Just a demo, setting hilite
function doSomethingWith($aSelectedEl) {
$aSelectedEl.css({"border":"4px solid red"});
setTimeout(function() { $aSelectedEl.removeAttr("style"); },1000);
}
DUMMY HTML:
<form>
<input type="text" name="testtextortexttest" value="Whatever you write, sir."/>
<input type="text" name="moretesttextormoretexttest" value="Whatever you write, again, sir."/>
<input type="submit" name="test1" value="Action 1"/>
<input type="submit" name="test2" value="Action 2"/>
<input type="submit" name="test3" value="Action 3"/>
<input type="submit" name="test4" value="Action 4"/>
<input type="submit" name="test5" value="Action 5"/>
</form>
DUMB CSS:
input {display:block}
I write this function that helps me
var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
arr[$(this).attr("name")] = $(this).val();
});
return arr;
};
and then Use
var data= PupulateFormData($("form"));

How do you return all the posible value in a switch statement

So i was wondering how do i shows the result once someone inputs the letter A.
the problem is it shows up for a few seconds and disapears
here's my code:
function pop(){
var text = document.getElementById('Search_Text').value;
var res = text.split("");
for (var i = 0; i < res.length; i++){
switch(res[i]) {
case "a":
alert("a");
break;
case "A":
document.getElementById("result").innerHTML="C";
break;
}
}
}
<form onsubmit="">
<input type="text" id="Search_Text"></input>
<button type="submit"onclick="pop()">change</button>
</form>
<p id="result"></p>
You have a submit type button inside a <form> tag.
Clicking that button will cause the browser to reload the page.
Since there are many ways to stop this from happening ... One suggestion could be to put return false; inside the onsubmit attribute of the <form> tag:
<form onsubmit="return false;">
I think that's because you are submitting the form and the page reloads. Thats why you see the result only for a few seconds.
Try this:
function pop(event){
event.preventDefault();
var text =document.getElementById('Search_Text').value;
var res = text.split("");
...
}
My hunch is that you've misunderstood the correct use of forms, and that what you're really trying to do is spit out letters individually onto a page after having typed into a text box and clicked the button.
A for loop does everything as fast as the processor will allow it, so if you're rendering to a page, it's going to be pretty fast.
If you want to see things clearly, you'll have to use JavaScript timing events with callbacks. Here's an example:
function pop(){
var text = document.getElementById('Search_Text').value;
var res = text.split("");
var element = document.getElementById("result");
var duration = 500;
showNextLetter();
function showNextLetter () {
if (res.length) {
element.innerHTML += res.shift();
setTimeout(showNextLetter, duration);
}
}
}
<form onsubmit="">
<input type="text" id="Search_Text"></input>
<button type="submit"onclick="pop()">change</button>
</form>
<p id="result"></p>

Javascript: display an alert when a form is checked?

I have created a simple web app that has 2 form selections, when the user makes their selection from each I want an alert to display showing them the choices they made.
I have attempted this below but when both forms are checked the alert is not displayed. What am I missing? Note see the comment:
//BELOW IS NOT BEING DISPLAYED BUT SHOULD BE
Current code:
<!DOCTYPE html>
<html>
<body>
<h1>Calculator</h1>
<p>Select the importance of this:</p>
<form method="get">
<input type="checkbox" name="Severity" value="negligible"> Negligible<br>
<input type="checkbox" name="Severity" value="minor"> Minor<br>
</form>
<p>Select the Probability of this:</p>
<form method="get">
<input type="checkbox" name="Probability" value="improbable"> Improbable<br>
<input type="checkbox" name="Probability" value="remote"> Remote<br>
<input type="checkbox" name="Probability" value="occasional"> Occasional<br>
<button onclick= "analyseThis()"> Analyse this </button> <br>
<script>
function analyseThis(){
var severities = document.getElementsByName('Severity');
var probs = document.getElementsByName('Probability');
var severity = undefined;
for(var i = 0; i < ages.length; i++)
{
if(severities[i].checked)
{
age = severities[i].value;
}
}
var probability = undefined;
for(var i = 0; i < probs.length; i++)
{
if(probs[i].checked)
{
probability = probs[i].value;
}
}
//BELOW IS NOT BEING DISPLAYED BUT SHOULD BE
alert("Severity is: " + age + "Probability is: " + probability);
}
</script>
</body>
</html>
I would use JQuery and use the click function of the button to submit.
Here is an example:
$(document).ready(function () {
$("{form id/class button id/class OR button id/class}").click(function(e) {
e.preventDefault();
//perform validation
//if everything is good...
$("{form id/class}").submit();
});
});
Something funny is happening:
Your function analyseThis() does get called, but there is an
error when it is being evaluated.
The form on the page is being "submitted", so the page reloads
and you never see the error.
To prevent the page from reloading (so you can see your error) do this:
Pass in the event object to your analyseThis() function from the onclick hander:
<button onclick= "analyseThis(event)"> Analyse this </button>
Make your analyseThis() accept the event object, and call .preventDefault() on it so that the page doesn't reload:
function analyseThis(e){
e.preventDefault()
// the rest of your function body here....
}
After you do that, you will see the underlying error output in the console:
ReferenceError: ages is not defined (line 33, col 17)
for(var i = 0; i < ages.length; i++)
If you do want the form to be submitted, just remember to remove the e.preventDefault() call after debugging the code.
You have an error in your code - you are checking ages.length in your loop which is probably undefined (no ages variable in your code) in the first loop and your code execution should stop there.
Working JSBin code here:
http://jsbin.com/yelihugune/1/
You have a bug in your code.
for(var i = 0; i < ages.length; i++)
{
if(severities[i].checked)
{
age = severities[i].value;
}
}
'ages' is not yet defined in your code, nor is 'age'. This will be throwing an error, stopping your code from running. This is why the alert is not going.
Declare the ages array.

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

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.

Why JS doesn't execute if it it's in between form tags?

<script type="text/javascript">
window.onload = init;
function init() { //wait for load and watch for click
var button = document.getElementById("searchbutton");
button.onclick = handleButtonClick;
}
function handleButtonClick(e) { //get user input and go to a new url
var textinput = document.getElementById("searchinput");
var searchterm = textinput.value;
window.location.assign("http://google.com/example/" + searchterm)
}
</script>
<form>
<input type="text" name="search" id="searchinput">
</form>
<input type="submit" value="Ara" id="searchbutton">
In this code block, it gets user input and go to a new url with user input.
if I move last line into form element it doesn't working.
But I'm using id to find elements.
you can specify the OnSubmit as explained in the below code fragment, and it will work.
<form method="GET" onsubmit="handleButtonClick(event)">
<input type="text" name="search" id="searchinput">
</form>
function handleButtonClick(e) {
var textinput = document.getElementById("searchinput");
var searchterm = textinput.value;
window.location.assign("http://google.com/example/" + searchterm)
return false;
}
I suspect that it is because your submit button is submitting the form.
Add e.preventDefault(); and return false; to your code.
function handleButtonClick(e) { //get user input and go to a new url
e.preventDefault();
var textinput = document.getElementById("searchinput");
var searchterm = textinput.value;
window.location.assign("http://google.com/example/" + searchterm)
return false;
}
This should stop the form from submitting cross browser.
Instead of
<input type="submit" value="Ara" id="searchbutton">
use this (MDN docu)
<button type="button" id="searchbutton">Ara</button>
Your button works as a form submit button, so instead of just executing your JavaScript, it also tries to submit the form, which points back to the script itself. By using <button type="button"> you define a mere button without any submitting functionality.
Besides: If you don't need the surrounding <form> element, why not drop it out of the code?

Categories