HTML Form to display output by using a button - javascript

Please let me know what I am doing wrong, I have tried to debug but it hasn't been working. I want to enter information into a text field and then display that after clicking a button.
<!DOCTYPE html>
<html>
<head>
<script type = 'text/javascript'>
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").onclick = display();
</script>
</head>
<body>
<form id='form'method = 'post'>
<p> Name: <input type="text" id="name"/></p>
<p><input id ="Submit" type = "button" value = 'Submit' /></p>
</form>
</body>
</html>

The problem is that you are making use of a <form> POST. The default behaviour is to navigate away from the page (or refresh if you're posting to the same page), and doing so would mean that the script cannot execute any further functionality. To prevent this, you need to use .preventDefault() to prevent the default behaviour of the form submission.
In order to do this, I've changed your .onclick = display() functionality to add an event listener on the click, which prevents the default behaviour, and then calls display():
.addEventListener("click", function(event) {
event.preventDefault();
display();
});
Adding this provides the following working example:
var name; //name
console.log("hi from script");
function getName() { //get name
return document.getElementById("name").value;
}
function display() { //get the name and display
name = getName();
alert(name);
}
document.getElementById("Submit").addEventListener("click", function(event) {
event.preventDefault();
display();
});
<form id='form' method='post'>
<p> Name: <input type="text" id="name" /></p>
<p><input id="Submit" type="button" value='Submit' /></p>
</form>
Hope this helps! :)

Create an empty p tag and give it an id, then call the id and .html to input the text into the field. Like so
so get your html ready
<p><span id="youridhere"><p>
then add this to your function instead of using alert.
$('#youridhere').html(name);
that should do it
here's a jsfiddle of what I think you are looking for
https://jsfiddle.net/uzdt715L/
$('button').click(function(){
var thing = $('#whatever').val();
$('#final').html(thing);
});

You need to update your click handler syntax. The following should work for you,
document.getElementById("Submit").addEventListener("click", display);
See this related question - addEventListener vs onclick

Your code is not really wrong.
But because the JavaScript is placed before htm code, so the onlick event is not registered.
You must replace
document.getElementById("Submit").onclick = display();
With
document.onload = function() {
document.getElementById("Submit").onclick = display();
}
Sorry for the formatting as I'm answering via mobile.

Related

Javascript getElementByID from form input

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>
So, the user shall enter for instance "1+2". The result shall appear below.
Any idea where is my mistake?
Best regards
Here is how you can achieve that.
eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.
I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.
remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13
num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
if(e.which==13)
{
var value = num_field.value.match(/(^[-+/*0-9]+)/g);
if(!value) return;
else value = value[0];
var res = eval(value);
document.getElementById("display_result").innerText = res;
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calc" />
<p id="display_result"></p>
You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)
The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):
<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post" id="form">
<span>Type here:</span>
<input type="text" id="calc"> <!-- inputs are self closing no need for closing tag -->
<input type="submit" value="submit"> <!-- added a submit button -->
</form>
<script>
form = document.getElementById("form");
num_field = document.getElementById("calc");
form.onsubmit = function() { // attach this event to the form
document.getElementById("display_result").innerHTML = evalAlternate(num_field.value); // add .value here to get the value of the textbox
return false; // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
}
function evalAlternate(fn) { // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
fn = fn.replace(/ /g, "");
fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
return new Function('return ' + fn)();
}
</script>
<p id="display_result"></p>
</body>
</html>
see the below fiddle
https://jsfiddle.net/ponmudi/13y9edve/
num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
if (event.keyCode === 13) {
document.getElementById("display_result").innerHTML = eval(num_field.value);
return false;
}
}
This should work:
calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>
eval() JavaScript Method
Try this:
var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
if (event.keyCode == 13) { // Enter key.
// Sanitize before using eval()
var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
document.getElementById("display_result").innerHTML = eval(calculation);
}
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>
You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

I'm trying to make a specific input into a text area call a specific javascript function, but it won't work

So to give a little bit of detail, I'm trying to make an interactive fiction game or text adventure. I have a form where all the "commands" for the game will be typed. I'm working on the first command which is the string "start" to call a prompt. Just to test the code, I have the prompt say "success!" when done correctly. What's happening though, is as soon as I open the web browser to test, the prompt triggers before I even type a command. Here's the code.
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm"> <input type="text" name="">
</form>
</body>
</html>
And then here's the javascript.
var input = document.getElementById("testForm");
if (input = "start") {
prompt("Success!");
}
Try this:
<html>
<head>
<script type="text/javascript" src="scripts/engine.js"></script>
</head>
<body>
<form id="testForm">
<input type="text" id="myInput">
</form>
<script>
var myForm = document.getElementById("testForm");// get the form element.
var myInput = document.getElementById("myInput");// get the input element
myForm.onsubmit = function() { // when the form is submitted, execute this function.
if (myInput.value == "start") { // if the value of the input equals 'start', show prompt.
prompt("Success!");
}
return false; //return false, so the form doesn't get submitted.
};
</script>
</body>
</html>
Edit:
Added submit event handler, that returns false, so the form does not get submitted.
You need to check the value of the input like so
var input = document.getElementById("inputID");
var value = input.value;
The code will always be ran straight away because it has no event handler. You could add a button which triggers it
document.getElementById('button').addEventListener('click', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});
Or if you prefer on the forms submit event:
document.getElementById('testForm').addEventListener('submit', function () {
var input = document.getElementById("inputID");
if (input.value === 'start') {
// Do something
}
});

pass JavaScript variable to HTML input box and (to use in PHP file)

I'm trying to pass a JavaScript variable to the value of an hidden input button to use in my PHP file output.
My HTML is:
<input type = "hidden" id = "location2" name = "location2" value = ""/>
I'm using this onclick="myFunction();" in my "Submit Form" input to run the function as it is not able to be done in the window.load()
My JavaScript below is calling indexes from another function and assigning the text to the variable 'location' (I know this sounds strange but it was the only way I have got it to work so far):
function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
document.getElementById("location2").value=(location);
}
Any help would be hugely appreciated as I am really struggling and have been working on this for some time (as you can probably tell, I dont really know what I'm doing) - I just need to call the value of this variable into my PHP file output and the majority of my web form is completed.
Thanks very much
Marcus
I've just changed my HTML as follows
I've removed myFunction from my submit
I've added the following HTML button:
<button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>
The variable is now passing!!!! The only problem is when I press the onclick button, it is now submitting my form!!
Is it okay for me to replace my previous submit button with this code??
THANKS TO EVERYONE FOR THEIR HELP ON THIS!!
I Was not sure what you doing but below example may help you. It will post the value as well as the option text.
Here we are using print_r to print the $_POST array from the AJAX Request. using this method, you should be able to debug the issue.
<!DOCTYPE html>
<html>
<body>
<?php if($_POST) {
print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
<input type = "hidden" id = "location2" name = "location2" value = ""/>
<input type = "hidden" id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect").options;
//alert("Index: " + y[x].index + " is " + y[x].text);
document.getElementById("location2").value=(y[x].index);
document.getElementById("locationname").value=(y[x].text);
//alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
myFunction();
};
</script>
</body>
</html>
i'm assuming your form method is 'POST' and action value is the same php page where you are expecting to see the 'location2' hidden input value, if that is the case, you can use $_POST['location2'] to get the value in that php page.
Yes it is fine to use button tag by default it acts like the submit button inside the form tag. You can also make it act like button(won't submit the form) by using the attribute type='button'.
Edited
button or input type='submit' can submit the form only when it is placed within the form tag(without javascript).
<form action='http://www.stackoverflow.com/'>
<button>stackoverflow</button> <!-- this works -->
</form>
<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->
var go = function() {
document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->

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?

How to grab the onSubmit event for a form?

I want to know how to grab the onsubmit event from a form to do some form validation, because I don't have access to it directly. (I am writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)
I got so frustrated trying to do this for my plugin that I have written a Hello World version below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop ups when the page loads.
Here is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Test</h2>
<form action="#" method="post" id="commentform">
<p><input type="text" name="author" id="author" size="22" tabindex="1" />
<label for="author"><small>Name (required)</small></label></p>
<p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
</form>
<script type="text/JavaScript">
<!--
alert("Hello world");
var formCheck = document.getElementById("commentform");
formCheck.onSubmit = doMapping();
function doMapping() {
alert("form submitted");
return false;
}
-->
</script>
</body>
</html>
Change this:
formCheck.onSubmit = doMapping()
to this:
formCheck.onSubmit = doMapping
When you add parenthesis to the end of a function you execute that function. When you assign a function (or pass it as a parameter to another function) you need to omit the parenthesis as that is the way to retrieve a function pointer in JavaScript.
Edit: You will also need to move the declaration of the doMapping function above the assignment of that function to the onsubmit event like this (good catch tvanfosson!):
function doMapping() {
alert("form submitted");
return false;
}
formCheck.onSubmit = doMapping();
However if the doMapping function is not used elsewhere you can declare the doMapping function as an anonymous function like this:
formCheck.onSubmit = function() {
alert("form submitted");
return false;
}
which seems a bit cleaner to me.
Using jQuery.
$(document).ready( function() {
$('#commentform').submit( function() {
alert('form submitted');
return false;
});
});
Thank you! Actually I solved it another way, using both Andrew's suggestion and the window.onload event - I think the problem was partly because the element hadn't actually loaded.
window.onload = function(){
if (document.getElementById("commentform")){
document.getElementById("commentform").onsubmit = doMapping;
}
}
function doMapping(){
alert("form submitted");
return false;
}

Categories