Javascript function updates html field then erases it - javascript

Maybe a stupid question but i do not know the root cause of this strange javascript behavior : my "submit button" calls a "javascript function" which
updates a html field (ok), then erases it (nok) !
Why the "demo" field is erased after execution ??
(Maybe one of the easiest question of stackoverflow ever!)
<!DOCTYPE html>
<html>
<head></head>
<body>
<p id="demo"></p>
<form>
<button type="submit" value="Submit"
onClick="launchSubmit()">Submit
</button>
</form>
<script type="text/javascript">
function launchSubmit(){
document.getElementById("demo").innerHTML = "bla bla bla";
}
</script>
</body>
</html>

The JavaScript doesn't erase the value... the subsequent posting back of your form does. You put type="submit" in your button which will submit the form to the server. This then causes the server to send back a fresh copy of the HTML page for the browser to use. Of course the fresh copy does not contain any changes made by JavaScript, since those only exist in the browser's old copy of the page, which is now destroyed.
You can change it to type="button" and it won't post back the form. If you don't actually need a form here, then remove the <form></form> tags as well.
Here is some useful background reading about forms: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms

That is because your button type is set to submit. Setting this to button will keep the value on the screen.

When you click submit button, it submitted the form. Then you see a new empty page.
You should add a return false to onclick event, or you can change the type=submit attribute to type=button to make a normal button.
Use inline onclick is a bad idea, which may cause bugs if you do not take care of the escaping/returning, etc. , you had better use some libraries like jQuery, it will help you much more.
<!DOCTYPE html>
<html>
<head></head>
<body>
<p id="demo"></p>
<form>
<button type="submit" value="Submit"
onClick="launchSubmit(); return false;">Submit
</button>
</form>
<script type="text/javascript">
function launchSubmit(){
document.getElementById("demo").innerHTML = "bla bla bla";
}
</script>
</body>
</html>
The jQuery version:
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head></head>
<body>
<p id="demo"></p>
<form>
<button id="the-button">Submit</button>
</form>
<script type="text/javascript">
$('#the-button').on('click', function() {
$('#demo').text('hello world');
return false;
});
</script>
</body>
</html>

Because your form updates that element id="demo and then submits. In order to make that element remain, you must prevent the form from submitting.
Please Note:
An html form will always submit event when the action is not provided.
When you submit without the action, it submits to the same page, more
like reloading but with form data in memory.
So this is how you could approach your problem:
function launchSubmit(event){
event.preventDefault();
document.getElementById("demo").innerHTML = "bla bla bla";
}
<p id="demo"></p>
<form name="form">
<button type="submit" value="Submit"
onClick="launchSubmit(event)">Submit
</button>
</form>

Related

Passing timestamp to a form on button click

Very new to Javascript. I would like to pass a timestamp to a form when the user clicks a button, but I'm having trouble with getting the actual value to submit.
<html>
<head>
<script type="text/javascript">
var dateOfUser = new Date();
document.getElementById("userdate").value = dateOfUser;
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
// hide the content from user until they click the button
<script>
$(document).ready(function(){
$("#show").click(function(){
$("#ans").show();
});
});
</script>
</head>
<body>
<p>
Click the button to see the text.
</p>
<p><button type="button" id="show" onclick="userdate = new Date()">Show text</button></p>
<div id="ans" style="display:none">
<input type="hidden" id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text.
</div>
</body>
I've omitted the form submission code - unfortunately I did not write it and I don't have access to the code beyond using it for form submission.
But upon submission, the .csv file contains:
"timestamp":"dateOfUser"
And not the value of "userdate". As far as I understand, using document.getElementById("userdate").value = dateOfUser; should allow me to use "userdate" in the HTML.
Any help would be appreciated, I've poured over many similar questions on this site and others, but I am having trouble figuring out what I'm doing wrong.
you can remove the type="hidden" to test. At least it works for me using userdate.value.
<html>
<head>
</head>
<body>
<p>
Click the button to see the text.
</p>
<p><button type="button" id="show">Show text</button></p>
<div id="ans" style="display:none">
<input id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text.
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
// hide the content from user until they click the button
<script>
$(document).ready(function(){
$("#show").click(function(){
$("#ans").show();
$("#userdate")[0].value = new Date()
});
});
</script>
</body>
The way you put script above the body
<script type="text/javascript">
var dateOfUser = new Date();
document.getElementById("userdate").value = dateOfUser;
</script>
wouldn't work because the dom(i.e. the elements) has not loaded. While onclick and $(document).ready are different from the above way.
However, it's still better for you to put script at the bottom of body.

Why doesn't innerHTML work with white spaces?

In the below html, the front button doesn't respond while the back button changes the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="move front">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
In the below, both the buttons change the content of the tag.
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button onClick=document.getElementById('para').innerHTML="movefront">
front
</button>
<button onClick=document.getElementById('para').innerHTML="back">
back
</button>
</body>
</html>
Why does a bank space make a button unresponsive?
That is just invalid HTML.
You have to put quotes around your whole onclick attribute value, otherwise it will end at the space.
onClick = document.getElementById('para').innerHTML="move // cut off here
front" // a second (meaningless) attribute for your button tag.
Please consider this syntax:
<button onclick="document.getElementById('para').innerHTML='move front'">front</button>
You are probably having issues if you are using this technique.
I am sorry but this is not how you attach a click event to elements in modern javascript, at least if you want to work with what's called "good practices".
The better method would be to attach a click event to a desired element using javascript.
I will give you a short code example.
First the HTML - I will use your original HTML (modified a bit):
<!DOCTYPE html>
<html>
<body>
<p id ="para">Initial text. </p>
<button id="frontBtn"> front </button>
<button id="backBtn"> back </button>
</body>
</html>
As you can see, I have removed your "onclick" events from the buttons, and assigned an id to each button.
Second, we will write some javascript to properly attach a click event to each one of the buttons, and of course execute the change of text as you originally was intending to do:
if you are familiar with jQuery then this will do:
$('#frontBtn').on('click',function(){
$('#para').html('move front');
});
$('#backBtn').on('click',function(){
$('#para').html('back');
});
This can also be done with vanilla (native) javascript:
document.getElementById("frontBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "move front";
});
document.getElementById("backBtn").addEventListener("click", function(){
document.getElementById("para").innerHTML = "back";
});
Now we have a nicely structured event handler for each button, more code can be easily added.
As for where to insert your javascript ?
You can add the javascript to your html document by using script tags in your html document head like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// your code here..
</script>
</head>
<body>
....
....
Or even better - create a separate script file and load it at the bottom of your html page like this:
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
....
....
<script type="text/javascript" src="scripts.js"></script>
</body>
</html>
This is the better way to attach events to elements, using javascript.
Imagine if you try to write 50-100 lines of code inline ? impossible! but with an event handler function you can do it easily.
Things will basically work better and your project will be much easier for you to maintain.
Hope it helps a bit!

simple javascript example not working

I am learning javascript and i can't manage to make this work, an alert message should appear when i click the submit button
Html
<html>
<head>
<title>Understanding the Document Object Model</title>
<script type="javascript" src="script.js"></script>
</head>
<body>
<h1 id="title">Understanding the Document Object Model</h1>
<p id="first">This is the first paragraph</p>
<p id="second"><strong>This is the second paragraph</strong></p>
<p id="third">Third paragraph</p>
<input type="submit" id="clickMe" value="Click Me"/>
</body>
</html>
Javascript script.js
window.onload=function(){
document.getElementById("clickMe").onclick=runTheExample;
}
function runTheExample(){
alert("running the example");
}
Your type attribute is wrong.
It should be "text/javascript"
It works fine for me after making that change
==================================
EDIT:
As a note, my debugging process was to try invoking the alert() directly in the script. script.js became:
alert("running the example");
window.onload=function(){
document.getElementById("clickMe").onclick=runTheExample;
}
function runTheExample(){
alert("running the example");
}
That was triggering the alert either, which says that the whole script isn't in play. So it must be the invocation of the script that's the problem.
Once you've determined that, there aren't many things left to check.
<script type="text/javascript" src="script.js"></script>
You change your external javascript file link like this. Because,type attribute of script tag should come as text/javascript

Popup when click button

I have a simple html with a button
I subscribed to mailchimp (newsletter and forms widget)
and I got from them a code for my site that works when
you load the page.
I want the page to execute the code (open the pop up)
only when I click the button. can you help me with it?
(I feel it's kind of a easy one but I'm get a bit scared
cause it's a script code - I don't know why...)
this is my page - in the head there's the script
<html>
<head>
<script type="text/javascript" src="//s3.amazonaws.com
/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-`config="usePlainJson: true, isDebug: false"></script>`
<script type="text/javascript">require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us7.list-manage.com","uuid":"d5b6774fb8bf432d69df52d93","lid":"3ed431a3b6"}) })</script>
</head>
<body>
<button type="button">Click Me!</button>
</body>
</html>
also,
I upload it to a server - so this is the page online:
http://judamenahem.com/popuplp2/popup.html
You just have to add to the onClick of the button the code which is in the head who load the current popup.
function myFunction() {
require(["mojo/signup-forms/Loader"], function(L) { L.start({"baseUrl":"mc.us7.list-manage.com","uuid":"d5b6774fb8bf432d69df52d93","lid":"3ed431a3b6"}) });
}
and use :
<button type="button" onclick="myFunction()">Click Me!</button>
You can use standard popup boxes (those boxes that most sites use for: "Hey, you won X, do you really want to leave?") to ask the person a question via alert().
Here is some documentation on them. http://www.w3schools.com/js/js_popup.asp
You would simply need to attach a ClickEventHandler onto your button in your JS that triggers alert().
function myFunction() {
alert("I am an alert box!");
}
<button type="button" onclick="myFunction()">Click Me!</button>
So when you Click on Submit button then it open alert box
There is also prompt() function, which lets the user interact with the box

jQuery forms submit

I create this tiny JS so i can control the form submit with jQuery
$('#submit').click(function() {
$('#addForm').submit();
});
Can I use a simple href link for it?
Something like
link
I tried
link
but it didn't work (it by pass the other jQuery in the page)
If you want the JS that you created to control the submit, don't have a href value in your link:
<a id="submit">link</a>
You cannot submit your form that way with a link and some javaScript, even jQuery. You have to use an XHR call to submit your query AND not refresh the page. (you can submit your form with a link as presented by Dan, but I understand that you want to do more than just that from your questions)
The reason being that the "return false" statement will impact the link action, and not the form submission itself.
In any case, I would advise you to not use a link to submit your form at all.
You can easily submit a form with the normal submit button and a bit of jQuery. That way, you provide a nice fallback to your users that have not enabled javaScript.
You can even submit the form with some client side validation, using the following HTML / javaScript:
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#addForm').submit(function(){
validate();
ajax_submit_function_taking_form_data_as_argument($(this).serialize());
return false;
});
});
function validate(){
//Do some client side validation if required
}
function ajax_submit_function_taking_form_data_as_argument(theData){
$.ajax({
type: 'GET',
url: "http://search.google.com/",
data: theData,
error: function(e){
alert('error...');
},
success: function(data){
alert('success!');
}
});
}
</script>
<style type="text/css"></style>
</head>
<body>
<form id="addForm">
<input type="text" name="field1" value="" />
<input type="submit" value="submit" />
</form>
</body>
</html>
A last solution, albeit maybe too heavy weight for your use, would be to use the excellent jQuery form plugin from http://jquery.malsup.com/form/
I hope that helps!
You can attach to the click event with jquery. It's also cleaner not to put any javascript in your html.
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#aSubmit').click(function(){
$('#form1').submit();
return false;
});
});
</script>
<style type="text/css"></style>
</head>
<body>
<form id="form1" action="http://www.google.com/search" name=f>
<input name="q" />
</form>
submit
</body>
</html>
Never ever put JavaScript in the href attribute. If you must put in the HTML, use the onclick attribute, and remember to add return false. Also, never ever prefix script with javascript:.
Your first script block should do the job just as fine as well, though.
(And what does "it by pass the other jQuery in the page" mean?)

Categories

Resources