Basic Javascript onclick function call not working - javascript

I have an input and two buttons, each of which are supposed to change the text within the input field. If I put the single line of code within onclick directly, it works perfectly. If I move the line to a separate function and attempt to call it via onclick, nothing happens, and I don't know why.
I've looked at many other SO questions about onclick, but none of them seemed to help with this. I'm stumped. JSFiddle is here: https://jsfiddle.net/wjw00h44/2/
Relevant code:
<div class="container">
<div class="row">
<div class="col-sm-8">
<input type="text" class="form-control" id="noun-sentence" placeholder="Enter a sentence here">
</div>
<button type="button" class="btn btn-default" onclick="document.getElementById('noun-sentence').value = 'go away'">Check</button>
<button type="button" class="btn btn-default" id="noun-button" onclick="changeWords()">Check2</button>
</div>
<p id="test_p"></p>
</div>
<script>
function changeWords() {
document.getElementById('noun-sentence').value = 'go away';
return false;
}
</script>

In js fiddle, click on the settings gear icon in the javascript window and change how the script loads. Don't put it in either of the 'on' events, but either directly in the head or body elements. Then click 'run' and try again.

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>

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

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.

html onclick keeps redirecting to a function of javascript

Im calling a function from onclick of a button. When i press the button it executes my function deletes everything from the screen and displays the button inside my function. Everything works ok but why does it delete everything from screen. How to make it for it to only run the function but keep previous html elements prior to clicking the function?
<div id="form-container">
<form id="dim_form" action="">
<div class="bg">
<label class="form-label-a" for="dimm">Dimension</label>
<input id="dimm" type="text" />
</div>
<div class="bg">
<label class="form-label-b" for="dimm_upper">Upper tolerance</label>
<input id="dimm_upper" type="text" required />
</div>
<div class="bg">
<label class="form-label-c" for="dimm_lower">Lower tolerence</label>
<input id="dimm_lower" type="text" required />
</div>
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
</form>
</div>
data_table()
document.write("<input class='download' type='button' id='button-a' value='download xls' />");
I tried with "button" instead of submit. return false, basically everything i found on google and nothing works for me.
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
When this method is not used for testing, it is often used to write some text to an output stream opened by the document.open() method. See "More Examples" below
see the full documentation here: https://www.w3schools.com/jsref/met_doc_write.asp
if you want to add some nodes without cleaning the whole HTML try append
https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/append
document.write will erase everything you had earlier. Instead use append.
function data_table() {
const input = document.createElement('input');
input.type = "submit";
input.id = "button-a";
input.value = "download xls";
document.querySelector('.bg').appendChild(input);
}
<div class="bg">
<input class="form-button" type="submit" onclick="data_table();" value="Calculate" />
</div>
Document is referred to the entire html page when you are trying to do document.write it will write on the entire page....
There can be couple of work arounds but i will suggest this one
Give class to the element you want to add element to.
Get element by the class you assign to the element in first step
var x = document.getElementsByClassName("example");
if you want to keep whats already there
x.appendChild("whatever you want to add goes here");
if you want to add only new element and discard everything previously present
x.innerHtml="whatever you want to add goes 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>

Prepend object using jquery and disappear

I am writing a javascript file using jquery in order to inject the input box on the html page. However, when I inject the input on the page and within a few second the input box disappear. I am wondering why is that happen.
function injectArea(data) {
$('#test').prepend('<input type="text" class="input-block-level" placeholder=" " value="hi">');
}
P.S. I m using twitter bootstrap. not sure if that causes the problem.
when i call the function i do this:
$(document).ready(function(){
$(#button).click(injectArea);
});
This is my html:
<form class="form">
<button id ="button" class="btn btn-large btn-primary">Update Profile</button>
</form>
This fiddle shows that there is nothing wrong with prepend or the way you are using it. The issue must come from elsewhere. My guess is that you may have an AJAX callback that fires a few seconds after you call it which is overriding the change you are making to #test.
Fiddle:
http://jsfiddle.net/jy43A/
Update:
You said:
For some reason my page refresh itself.
#button is a <button> tag. Clicking on it will submit the form and refresh the page (if it targets the current page). use preventDefault(); to stop the submit default action:
function injectArea(data) {
data.preventDefault();
$('#test').prepend('<input type="text" class="input-block-level" placeholder=" " value="hi">');
}
You can see that the text box appears, then the page refreshes. This will look different in your case, but it will probably be along the same lines as this:
The effect WITHOUT preventDefault():
http://jsfiddle.net/jy43A/3/
And this works:
The effect WITH preventDefault():
http://jsfiddle.net/jy43A/2/
More info:
preventDefault info:
http://api.jquery.com/event.preventDefault/
Are you sure you're using the right method?
prepend:
<div id="a"></div>
$("#a").prepend("<span>");
<div id="a">
<span></span>
</div>
insertBefore:
<div id="a"></div>
$("#a").insertBefore("<span>");
<span></span>
<div id="a"></div>

Categories