Document initializes after form submit - javascript

I need to have an HTML document that can contain multiple input fields.
Starting with one field, a submit should create another input field as a copy of itself.
So I declared it with HTML code and wrote a function to append a copy of it to my div.
For testing purposes, I made a button to call my js function, too.
Now I'm confused as clicking the button will create a new field and pushing enter inside a field will initialize my HTML document, deleting previously created fields.
Can anybody figure out why?
Kind regards, Tommy
<button onclick="createRow()">New row</button>
<div id="criteriaTableBody">
<div class="tr" id="criteriaRow">
<div class="td">
<form onsubmit="createRow()">
<input type="text" name="text" value="">
</form>
</div>
</div>
</div>
<script>
function createRow() {
var row = document.getElementById("criteriaRow");
var newRow = row.cloneNode(true);
document.getElementById("criteriaTableBody").appendChild(newRow);
}
</script>

That's because your form submits. Forms are used to submit data to another page, so the entered data can be processed. You don't want this, instead you want to prevent the form from submitting using Event.preventDefault().
function createRow(event) { // Mind "event" here
// Prevent form from submitting (reloading the page and deleting your "progress")
event.preventDefault();
var row = document.getElementById("criteriaRow");
var newRow = row.cloneNode(true);
document.getElementById("criteriaTableBody").appendChild(newRow);
}
<button onclick="createRow(event)">New row</button> <!-- Pass event here! -->
<div id="criteriaTableBody">
<div class="tr" id="criteriaRow">
<div class="td">
<form onsubmit="createRow(event)"> <!-- Pass event here! -->
<input type="text" name="text" value="">
</form>
</div>
</div>
</div>
I also recommend avoiding HTML attributes like onclick, onsubmit, etc. Use an EventListener instead.

Pressing enter will submit the form.
The submit event handler will run, then the contents of the form will be sent to the URL specified by the action (the current URL since there isn't an action).
This loads a new page.
Since there is no action, the new page is a brand new, unmodified by JS, copy of the current page.
Avoid intrinsic event attributes like onsubmit. Use JavaScript event binding instead. Learn about the Event object and its preventDefault method.

Related

Function works when button clicked but not when submitting the form

I have yet another question concerning this project but here's hoping ill learn a lot from it.
So I created a function, that creates a div inside a div (which will then contain a random number from dice roll) and it works when I add this function to a button click.
But clicking the button multiple times might not be ideal for a lot of dice, so I created a form and it shouldnt create the number of divs the user decides he wants, but it doesnt seem to work. I suspect it has to do with the form refreshing the page, so instead of handling the even withh addEventListener I used inline "onsumbit" and tried to return the function but it still doesnt seem to work. What am i doing wrong? Here is the HTML and JS bits:
<form>
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onsubmit="return addMoreDice()">
</form>
<button onclick="addDice()">Add Dice</button>
<div id="diceTable">
</div>
and JS:
var numInput = document.querySelector("input");
function addDice(){
var div = document.createElement('div');
div.className = "diceStyle";
div.innerHTML = "<p> here will be a dice</p>";
document.getElementById('diceTable').appendChild(div);
};
function addMoreDice(){
for(var i = 0; i < numInput; i++){
addDice();
}
}
1.You should probably include onsubmit() in form tag and add a submit button inside form.
You can use onchange() method to invoke addMoreDice() whenever the value in input box is changed
you need to add onsubmit="yourfunction()" in side form tag
and than put an input type submit inside form tag like
<form action="#" onsubmit="addDice()">
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber" onsubmit="return addMoreDice()">
<input type="submit" value="Submit">
</form>
<button onclick="addDice()">Add Dice</button>
<div id="diceTable">
</div>
Each time you submit a form, it gets you to a different page. Instead you could have this code as shown below, (remove form tags)
<p>Pick how many dice you want to roll:</p>
<input id="diceNumber" type="number" name="diceNumber"></input>
<input type="submit" onClick="addMoreDice()">
Clicking on submit after entering the input dynamically creates divisions per your need.

Why doesn't click event trigger .submit()?

I am trying to send a form by using a click event to trigger the form submission. For some reason however, this does not seem to work.
Code:
<form id="send_intake">
<div class="input_line">Voornaam: <input type="text" name="firstname" id="send_intake_firstname"></div>
<div class="input_line">Achternaam: <input type="text" name="lastname" id="send_intake_lastname"></div>
<div class="input_line">E-mailadres: <input type="email" name="email" id="send_intake_email"></div>
<input type="submit" class="form_submit" value="Stuur">
</form>
<script>
//Send form
$(document).ready(function(){
$(".function_header").on( "click", "#submit_send_intake", function() {
alert ("click event fired.");
$("#send_intake").submit(function() {
$.post("pages/forms_intake/functions/send_intake_form.php", $("#send_intake").serialize());
});
});
});
</script>
Hope you guys can see what's going wrong here :(
UPDATE:
Sorry for not providing you with all the information.
Actually this form is part of a web app. The form is inside a .php file that is loaded into a dashboard with .load().
The situation is as follows:
In the dashboard file, there is a specific DIV in which forms are dynamically loaded upon user's request. But for UI reasons I want the users to be able to submit the form with the same button every time. So when the form is loaded, the ID #submit_send_intake is assigned to that button. I'm using Jquery event delegation to bind the click event to the dynamically added ID by specifying the buttons' parent element, which is .function_header.
To summarize: .function_header and #submit_send_intake are elements that exist in the parent document (dashboard) of this form document.
I cannot see element with class function_header and element with ID submit_send_intake. Probably you didn't copy that part of markup (but please check).
If you leave action empty in your form tag, your page will be refreshed by submit. So you should specify action.

How to get the values from a form and prevent submission?

I have this simple form:
HTML
<form>
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton"
onclick="doSomething();" type="submit">Create!</button>
</form>
JS
function doSomething() {
var name, email;
name = document.getElementById("eName").value;
email = document.getElementById("Email").value;
putElementsIntoTheDOM(name, email);
}
When the user inputs some information I want to populate the DOM with the user input.
The example above works. But I think it can be done better. I just don't know how.
How can I wire the <button> so that when the user clicks it the form values are passed
to the function doSomething()?
Also, since I'm not sending the form values anywhere except populating the DOM, how can I
prevent the submission?
I've seen something like this but I can't get it too work.
<button id="create" class="boton" onclick="doSomething(this.form);"
type="submit">Create!</button>
If you don't want to send the form values anywhere, then you just need to remove type="submit" from your button.
Your example code works fine. I'm not sure what you mean by a 'better' way. More modern/idiomatic javascript would not be using the onclick attribute, but instead binding doSomething to the button. Using jQuery, that would look like:
$("#create").click(doSomething);
First of all you have to update your function declaration to be able to receive the variables you want to send
function doSomething(name,email) {
}
Secondly, if you have to send values of some fields to that function, you can do so on button click like this.
<button id="create" class="boton" onclick="doSomething(document.getElementById('eName').value,document.getElementById('Email').value);" type="submit">Create!</button>
However, using unobtrusive javascript is recommended, and for that jQuery is one of the options you can use for passing variables to your function neatly.
There is a difference between the type="submit" and type="button" that I didn't realize.
Also, the button and submit types react differently with onclick and onsubmit events.
For example
<form onclick="doSomething()">
<label for="eName">Name</label>
<input id="eName" type="text" name="eName">
<label for="Email">Email</label>
<input id="Email" type="text" name="Email">
<button id="create" class="boton" type="button">Create!</button>
</form>
Notice that at the top of the form there is onclick.
The onclick is fired whenever you focus on an input element, and of course if you click the button.
Changing the form to <form onsubmit="doSomething(); but not changing the type="button" doesn't do anything. Clicking the button doesn't trigger the function.
By changing the type="submit"and keeping the head <form onsubmit="doSomething(); triggers the function when the button is clicked. A nice added functionality to this is that if you have any <input ... required="required"> the submit will only work if those fields are filled in (and your form will let you know about the required fields).
To prevent the submission/refreshing (since I'm only populating the DOM with user input) adding return false at the form head prevents submission
<form onsubmit="doSomething(); return false">.
Finally, to get the form values adding this:
<form onsubmit="doSomething(this); return false> and then
function doSommething(formInfo) {
var name = formInfo.eName.value;
var email = formInfo.Email.value;
...
}

How to update/change HTML content with JavaScript and prevent the page from refreshing?

I'm a newbie to scripting. I want to update HTML content with JavaScript, but as you can see
the web page keeps refreshing.
How can I prevent the page from refreshing?
Javascript:
function showResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
}
HTML
<form>
<input type="text" name="willbeshown" value="">
<button onclick="showResult(this.form)">Ganti1</button>
</form>
<p id="showresulthere">Result will be shown here</p>
</body>
Don’t use a form at all. You are not submitting any form data to a server. To process data in the browser, you don’t need a form. Using a form just complicates things (though such issues could be fixed by using type=button in the button element, to prevent it from acting as a submit button).
<input type="text" id="willbeshown" value="">
<button onclick=
"showResult(document.getElementById('willbeshown'))">Ganti1</button>
<p id="showresulthere">Result will be shown here</p>
<script>
function showResult(elem) {
document.getElementById("showresulthere").innerHTML = Number(elem.value) + 2;
}
</script>
I have used conversion to numeric, Number(), as I suppose you want to add 2 to the field value numerically, e.g. 42 + 2 making 44 and not as a string, 42 + 2 making 422 (which is what happens by default if you just use an input element’s value and add something to it.
Your button should be
<button onclick="showResult(this.form); return false;">Ganti1</button>
Javascript
function showResult(form) {
var coba=form.willbeshown.value;
var coba2=coba+2;
document.getElementById("showresulthere").innerHTML=coba2;
return false; // prevent form submission with page load
}
DEMO
The others will explain how you should use jQuery, but this would explain why it didn't work in your original code.
The <button> tag submits the form, so you have to add this inside your form tag to prevent form submission:
<form onsubmit="return false">
Btw, even without giving your form an explicit action, it uses the current page to submit; it's easy to think that it will not do anything without an action.
If you define a <button /> without defining its type it will work like a submit button. Just add type="button" to your button markup and the form won't be submitted.
<button type="button" onclick="showResult(this.form)">Ganti1</button>
With this change you won't need any return false or .preventDefault() "workarounds"

jQuery not posting all inputs of a form after the .append()

I have a form generated dynamically with the method .append() of jQuery.
I can add any number of new input, textbox, cmbbox, etc...
But the problem is that when I do the sumbit of the form, the PHP target does not receive the new input added, but just the vars connected to the input already in the form before the append().
Any ideas?
The javascript:
$("#button").live('click',function add(){
$("#list").append(
'<li style="height:20px;">'
+'<input type="text" class="text" id="prova" name="prova[]" value="prova">'+
'</li>'
);
});
The Html:
<input type="submit" id="button" value="Add input">
<form name = "form" id="form" action="post.php" method="POST">
<ul style="width:670px;padding:0px 0px 30px 0px" id="list">
</ul>
<input type="submit" id="submit" value="Submit">
</form>
The PHP:
<?php
print_r($_POST);
?>
Problem 1:
Your #button should not be of type submit, since you just want to use it to add to the form and not submit the form. So you should have:
<input type="button" id="button" value="Add input">
Problem 2:
You are overwriting your variables. The name is the variable sent with the form, so each input addition must have a new name, or the variable must be an array.
Additionally, you can't have more than one element with the same id.
The simplest way to solve this is to make prova an array by using the form prova[]:
$("#button").live('click',function() {
$("#list").append(
'<li style="height:20px;">' +
// Removed repetitive ID and made prova an array
'<input type="text" class="text" name="prova[]" value="prova"></li>'
);
});
jsFiddle example
You are intercepting the click event and adding elements to the form, but the event has already started, and will complete its default action (submit the form) without re-checking the content of the form.
You should stop the event after adding the fields (preventDefault should be the right choice), and then re-submit the form.
Something along these lines:
$('#button').live('click', function add(event){
event.preventDefault();
$('#list').append(...);
$('#form').submit();
});
I haven't tested it, but I'm pretty confident that it should work :)
Just to clarify, and putting any other problems aside, #Claudio's note is the correct answer here. I just had the same problem, button type was 'button' and the new element's name was being dynamically incremented. Everything looked fine, but the added elements would not submit.
Then I noticed my form tags were inside the table tags. I moved them outside and it all worked as planned.
Have any code to show? In order for php to "see" the vars submitted, you have to ensure that it has the "name" attribute specified on the form elements. I have a feeling your issue is going to be with the jQuery not the php.
Best guess: You haven't set name attributes for your dynamically added elements.

Categories