Can't update inner HTML with JQuery, it turns back immediately [duplicate] - javascript

This question already has answers here:
Page reloads on hide/show button click using jQuery
(2 answers)
Closed 2 years ago.
I have been trying to make this very simple feature work where the user clicks the submit button and the question number is updated.
On the browser when I click the button the question number becomes "2" for a second and turns back to "1" immediately. There is no console warnings or errors.
I tried it on the JSFiddle as well and when the button is pressed it gave me a 404 error code.
Here is the very small script and HTML that I am trying to run and also the JSFiddle:
$(document).ready(() => {
var level = 1;
$('button').click(() => {
level++;
$("#question").text("Question " + level);
});
});
<h1 id="question">Question 1</h1>
<form>
<h3>What is your name?</h3>
<textarea type="text" name="answer" rows="3" cols="50"></textarea>
<br>
<button class="btn btn-outline-primary btn-lg" type="submit" name="submit">Submit</button>
</form>

Because the page is reloading when you submit the form.
The default submit action for a <form> is the current URL when not otherwise specified. And the default type for a <button> within a <form> is submit when not otherwise specified. Though in this case you are explicitly specifying type="submit". So essentially your markup is explicitly indicating that you want to reload the page when clicking the button.
Since you're not intending to post a form, you can simplify the HTML and remove the <form> elements and make the button no longer a submit button:
<h1 id="question">Question 1</h1>
<h3>What is your name?</h3>
<textarea type="text" name="answer" rows="3" cols="50"></textarea>
<br>
<button class="btn btn-outline-primary btn-lg" name="submit">Submit</button>
If for some other reason you want/need to keep the <form> (styling perhaps? though since it's not semantically a "form" then I'd recommend using something else, like a <div>) then you can at least specify type="button" to prevent default submit behavior:
<button class="btn btn-outline-primary btn-lg" type="button" name="submit">Submit</button>

The default type of button is submit even if you have not written but you also have specified it.
So what happens to your code :
Your function executes, we see the result and it reload as the type='submit' behaviour.
Make it type='button' not removing the type attribute.
And another thing i can see is you dont need to call $(document).ready() because it is not a function which is needed as the html loads.

Related

Using a button with JavaScript & HTML [duplicate]

This question already has answers here:
Clicking a button within a form causes page refresh
(11 answers)
Closed 2 years ago.
I know, the title seems to lead to a repetitive/useless question, but I can't find a solution in other questions. Let me explain better and read what follows before closing my question.
I created a form by learning from different sources. It all seems to work fine, until I have to click on submit button, with "Save as TXT" written on it. It happens quite a strange thing:
if I click on the text "Save as TXT" inside the button, it submits my data correctly;
if I click on the coloured part around the text "Save as TXT" of the button, it refreshes the page.
I think I found why this happens, but I can't fix it. It seems to be something which has to do with both my HTML code and my JavaScript code. Here it is a part of it:
Javascript
$(function(){
$("#submitLink").click(function(event){
// things to do on submit...
});
});
HTML
<form method="post" name="myForm" action="" id="formToSave">
<!-- some fields to compile... -->
<div class="input-group mb-3">
<button class="btn btn-primary btn-lg" id="align" type="submit">Save as TXT</button>
</div>
</form>
How can I change this part of the code in order to submit successfully by clicking anywhere on the button (and do what I write in the JS function)?
Thanks in advance,
happy coding everyone!
ps. I read this "famous" question you added by after closing my question, but it is not helping me. By writing type="button" instead of type="submit" I get no results, I'm sorry
if I click on the text "Save as TXT" inside the button, it submits my data correctly;
When you click on the text itself, you are clicking the <a> element, and therefore triggering its event listener.
if I click on the coloured part around the text "Save as TXT" of the button, it refreshes the page.
When you click on any part of the button, are triggering the <button>'s event listener.
Therefore, I suggest
So it seems like the solution is to taking the <a> element's event listener and attaching it to the <button>.
One way to do this is to replace
<button class="btn btn-primary btn-lg" id="align" type="submit">Save as TXT</button>
with
<button class="btn btn-primary btn-lg" id="align" onclick="{Save as TXT}" type="button">Save as TXT</button>
where "{Save as TXT}" was the code you previously had in the <a>'s href.
The reason you need to add type="button" is so you can disable the button's default behavior submitting the form (and therefore refreshing the page).
Then, since you got rid of the <a> tag, you need to attach any listeners that used to listen for clicks on the <a> tag to the <button> instead.
To do this, replace:
$("#submitLink").click(function(event){
// things to do on submit...
});
with
$("#align").click(function(event){
// things to do on submit...
});
See it in action:
<form method="post" name="myForm" action="" id="formToSave">
<!-- some fields to compile... -->
<div class="input-group mb-3">
<button class="btn btn-primary btn-lg" id="align" onclick="console.log('Submitted')" type="button">Save as TXT</button>
</div>
</form>
You need for the BUTTON type 'button' but you had 'submit'. So it wants to submit the form which follows in a reloading, with button the action is needed to be done from you.
The A-tag is not needed so I deleted it. On the contrary if clicked at the corners anything happened, now this functions
<button type="button" id='btn'>Save as TXT</button>
Just test it.
$(function(){
$("#btn").click(function(event){
console.log('Submit');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" name="myForm" action="" id="formToSave">
<div class="input-group mb-3">
<button class="btn btn-primary btn-lg" id="btn" type="button">Save as TXT</button>
</div>
</form>

Button onclick function won't set tab title (dose only for a second) [duplicate]

This question already has answers here:
How to prevent buttons from submitting forms
(20 answers)
Closed 2 years ago.
<form>
<p>Enter Title Text:</p>
<input type="text">
<button onclick="hello()">Submit</button>
</form>
</body>
<script>
function hello() {
document.querySelector("title").textContent =
document.querySelector("input").value;
}
My intent is for the tab title to change to the text the user entered upon clicking the button. I think it is working but only for a split second then changing back. Any help is greatly appreciated. Thanks!
Change the button's type to "button" so clicking it does not submit the form. The default type for a button inside a form is "submit", which will cause it to submit the form and hence reload the page when it is clicked. Explicitly setting the type prevents this behavior.
See also: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
<button type="button" onclick="hello()">Submit</button>
function hello() {
document.querySelector("#result").textContent = "Title text is: " + document.querySelector("input").value;
}
<form>
<p>Enter Title Text:</p>
<input type="text">
<button type="button" onclick="hello()">Submit</button>
</form>
<p id="result">
</p>
Here is the solution:-
<form onsubmit="event.preventDefault()">
<p>Enter Title Text:</p>
<div class="title"></div>
<input type="text">
<button onclick="hello()">Submit</button>
</form>
function hello() {
document.querySelector(".title").innerHTML =
document.querySelector("input").value;
}
First, you need to prevent the default behaviour of form by using preventDefault or just omit form tag it works the same in both cases, in order to use "onclick" event of your button
Then, for getting the desired result you can use innerHTML like I have used here.

Cloned div disappears after appendChild

I'm trying to add a duplicate function to clone and append a div. Here's the JS:
function NL(){
var original = document.getElementsByClassName('form-block')[0];
var clone=original.cloneNode(true);
document.getElementsByTagName('form')[0].appendChild(clone);
}
document.getElementsByClassName('new-line')[0].addEventListener('click',NL);
and the HTML:
<form class='myform'>
<div class='form-block'>
<span class='line'>1</span>
<button class='new-line'>New Line</button>
<button class='new-nested'>New Nested Line</button>
<input class='input' type='text' placeholder='Enter Value...'>
<button class='new-input'>Add input</button>
</div>
</form>
CodePen Link
The idea is when you click the "New Line" button, a new 'form-block' is cloned and appended under the first one. But if you click on the "New Line" button now, the new block shows up briefly and then disappears. I can't figure out why.
I can't modify anything in the HTML, and I can only use vanilla JS.
Thanks!
button default type is submit. When there is no type specified it will act as a submit button & in your case it is trying to make a post call. You can open the developers console and check the network tab. In order to prevent that use
preventDefault()
function NL(event){
event.preventDefault() // Here is the change
var original = document.getElementsByClassName('form-block')[0];
var clone=original.cloneNode(true);
document.getElementsByTagName('form')[0].appendChild(clone);
}
document.getElementsByClassName('new-line')[0].addEventListener('click',NL);
DEMO
Just use type="button"
<button type="button" class='new-line'>New Line</button>
<button type="button" class='new-nested'>New Nested Line</button>

HTML Onlcick event only works with # Anchor Tag

When I attempt to call a function my this page using the below code. I just seems to refresh the page and not call the script.
<form role="search" name="locationForm">
<div class="form-group">
<input id="locationInput" type="text" class="form-control" placeholder="Search">
</div>
<button class="btn btn-primary btn-lg" type="submit" onclick="start();">Submit</button>
</form>
If I add a '#' to the end of the url, reload the page, then the onlcick event works as it is suppose to.
As far as I knew these were Anchor tags and I have no idea why they would be required in the calling of a function.
How do I correct this? As I don't want to have to use the #.
You are using a button element, whose default behavior, when clicked, submits its parent form. return false will stop the form from submitting:
<button class="btn btn-primary btn-lg" type="submit" onclick="start(); return false;">Submit</button>
If you don't want the button to automatically submit, you could change its type to button. Then, all it will do is run its onclick code. (You can still have that code submit the form manually)
I suppose you want to run the start() function when you submit the form?
You said you're working with an click event listener.
Try to listen for the submit event, instead.
$('#your_form_id').on('submit', function(e) {
e.preventDefault();
your script...
});
The code above basically does this.
Furthermore, the preventDefault keeps the form from actually submitting itself.
You could access the form data with
$('#your_form_id').serialize();
I hope this pushes you into the right direction!

Setting display to inline submits form but block does not

I have a website that is set up to be used on mobile devices. The user can draw on a canvas element and then click the "submitButton" button to save the canvas to a server. When the user clicks the button, the "submitButton" button disappears and a "submittingButton" button appears in it's place. All this is working correctly. In fact, the entire project is working correctly after I changed the "submittingButton" button to a type=button instead of type=submit.
My question is, however, when I change the style.display of the "submittingButton" button, if I set the style.display to block, the form is not submitted (which is what I want) but the button is displayed on a new line. However, if I set the style.display to inline or inline-block, the form is submitted, the page refreshed, and the drawing is cleared. Why does the form submit when the style.display is set to inline or inline-block but not submit when the style.display is set to block?
Here are the relevant parts of my code:
function sendImage(){
if(window.hasBeenDrawn){
document.getElementById("signError").style.display="none";
document.getElementById("submitButton").disabled=true;
document.getElementById("clearButton").disabled=true;
window.wasSent=true;
document.getElementById("submitButton").style.display="none";
document.getElementById("submittingButton").style.display="";
//document.getElementById("submittingButton").style.display="block";
saveImage();
}
And the HTML:
<form method="post" action="" class="sigPad">
<div id="receipt" style="text-align:center">
<div class="sig sigWrapper">
<canvas style="width:85%; height:95%; margin-top:25px" height="300" class="pad" id="myCanvas" />
<input type="hidden" name="output" class="output" />
</div>
<br />
</div>
<div id="clearSubButtons">
<button id="clearButton" onclick="redoSig(); return false;" > </button>
<button id="submitButton" type="submit" onclick="sendImage()"> </button>
<button id="submittingButton" style="display:none;"> </button>
</div>
</form>
PS. I have the code working as expected, by changing the "submittingButton" to type=button. I don't want the form to submit, the saveImage() function uses an ajax post to submit the image to the server.
I have no idea why changing the display value of the button causes it to submit the form, however I can offer the following.
By default, a button element in a form is a submit button, so if you have a button that you don't what to act as a submit button, give it a type of button (or use an input element with a type of button), so:
<button id="clearButton" onclick="redoSig(); return false;" > </button>
would be better as:
<button id="clearButton" type="button" onclick="redoSig();">Clear</button>
or
<input id="clearButton" type="button" onclick="redoSig();" value="Clear">
so there is no chance of the form submitting when it's clicked. Similarly for the submittingButton button, change it to a button then it can't submit the form.
Finally, all you seem to be doing is changing the label of the button. You can probably do that using something like:
<form onsubmit="return modifiedSubmit(this);" ...>
...
<input name="submitButton" type="submit" value="Submit signature">
</form>
and the function:
function modifiedSubmit(form) {
if (form.submitButton) {
form.submitButton.value = "Submitting...";
form.submitButton.disabled = true;
window.setTimeout(function(){form.submit();}, 10);
return false;
}
}
Untested of course, but hopefully you get the idea. The timeout is to ensure the button label changes before the form submits, otherwise browsers may decide that since they are in the process of navigating to another page, they won't do any DOM updates and so won't change the label.

Categories