Form submits but no data present in console - javascript

I am trying to make my first form using HTML and JS(vanilla). When I submit the form the console shows the form coming in but as I check through it, there appears to be none of the data i entered into the fields.
I have read through a number of the forum posts on here and other forum sites but most of the are using Jquery, React, or some other framework, I am super new to this and forms are already hard enough.
window.onload = () => {
formID.addEventListener("submit" , (e) =>
{
console.log("form event listener activated");
e.preventDefault();
console.log("default prevented");
console.log("formID: " , e);
myModule.addToTable(e);
});
}
function addToTable(e) {
console.log("e " , e);
console.log("e target " , e.target);
console.log("e target.value " , e.target.value);
console.log("this is a test, line 80 client.js");
}
<form id="FormID" class="FormClass" method='POST' action="#">
<input class="inputClass" type="text" name='Name' placeholder="Name" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Model-Num' placeholder="Model Number" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Current-Stock' placeholder="Current Stock Amount" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Target-Stock' placeholder="Target Stock" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Reorder-Amount' placeholder="Reorder Amount" value=""/> <br/> <br/>
<input type="submit" value="Submit"/>
</form>
Result
under the target area i see
textContent: "↵ ↵ ↵ ↵
or
"↵↵↵↵↵↵↵↵↵↵"
I am of course wanting to get the actual values for my fields that were entered in the text box. Any help is absolutely appreciated.
Remember, I am super new, I do not understand a lot fo the backend DOM but I am trying to learn it.

The reason why it is not working is because you are using formID without even initializing the element to it. Try this instead
document.getElementById("FormID").addEventListener("submit" , (e) => {
//your code here
});
I also noticed that you use myModule in calling addToTable(e) which will cause error(based on that snippet) because myModule is undefined. Just call addToTable(e) directly. Check the working version of your code below
window.onload = () => {
document.getElementById("FormID").addEventListener("submit" , (e) =>
{
console.log("form event listener activated");
e.preventDefault();
console.log("default prevented");
console.log("formID: " , e);
addToTable(e);
});
}
function addToTable(e) {
console.log("e " , e);
console.log("e target " , e.target);
console.log("e target.value " , e.target.value);
console.log("this is a test, line 80 client.js");
}
<form id="FormID" class="FormClass" method='POST' action="#">
<input class="inputClass" type="text" name='Name' placeholder="Name" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Model-Num' placeholder="Model Number" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Current-Stock' placeholder="Current Stock Amount" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Target-Stock' placeholder="Target Stock" value=""/> <br/><br/>
<input class="inputClass" type="text" name='Reorder-Amount' placeholder="Reorder Amount" value=""/> <br/> <br/>
<input type="submit" value="Submit"/>
</form>

Related

Change HTML Document Title from Form input

I am trying to change a HTML page's title based on form input. This is needed because the page will be printed as a PDF and we want it to be saved as the customer's name + caller.)
I know the following code will change the document's title.
onClick="document.title = "My new title";
But I'm trying to do something like:
onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;"
Here is an example form:
<form action="">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName" ><br>
<input type="submit" value="Submit" onClick="document.title = document.getElementById("customerName").value +" " + "Caller" ;">
</form>
document.title = document.getElementById('customerName').value +' ' + 'Caller' ;
You have quote issues. Also use the submit event instead of click
document.getElementById("form1").addEventListener("submit", function(e) {
e.preventDefault(); // remove if you DO want the form to submit
document.title = document.getElementById("customerName").value + " " + "Caller";
})
<form action="" id="form1">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName"><br>
<input type="submit" value="Submit">
</form>
To give you the answer just try this code and see what i did different :)
let handleSubmit = (event) => {
event.preventDefault()
document.title = document.getElementById("customerName").value + " " + "Caller";
}
<form action="#" onsubmit="handleSubmit(event)">
<label for="customerName">Customer name:</label><br>
<input type="text" id="customerName" name="customerName"><br>
<input type="submit" value="Submit">
</form>

the function i set for my html button isn't working

i set a function for my button but the button doesn't follow it and it isn't being used anywhere else either
<div id="main2" class="main">
<form>
<label class="Courier" for="EventName"></label><br/>
<input class="Courier" required type="text" id="EventName" placeholder="Event name"><br/>
<input class="Courier" required type="Text" id="location" placeholder="venue"><br/>
<input class="Courier" required type="Text" id="DateAndTime" placeholder="Date and time"><br/>
<input class="Courier" required type="Text" id="Duration" placeholder="Duration"><br/>
<input class="courier" required type="Text" id="Clothing" placeholder="Dress code"><br/>
<input class="courier" required type="Text" id="Food" placeholder="Food"><br/>
<textarea class="courier" id="Notes" name="Notes" rows="4" cols="50">Enter additional notes here</textarea><br/>
<button id="submitEvent">Submit</button>
</form>
<br/>
<div id="newEvent"></div>
</div>
Javascript for the button below
$('#submitEvent').on('click' , function submitEvent(){
var event = $('#EventName');
var location = $('#location');
var DateAndTime = $('#DateAndTime');
var Duration = $('#Duration');
var Clothing = $('#Clothing');
var Food = $('#Food');
var Notes = $('#Notes');
var data ={
event: event,
location:location,
DateAndTime: DateAndTime,
Duration: Duration,
Clothing: Clothing,
Food: Food,
Notes: Notes
};
var eventRef = database.ref('Events');
var newEventRef = eventRef.push(data, function(err) {
if (err) {
console.error('Error Saving Data', err)
}
else{
console.log('success saving data');
$('#EventName').val('');
$('#location').val('');
$('#DateAndTime').val('');
$('#Duration').val('');
$('#Clothing').val('');
$('#Food').val('');
$('#Notes').val('');
}
})
})
i expect it to submit this to at least put on the console that the upload to firebase was successful or not but it doest do either it just refreshes my page to index.html and instead of the usual url it will be http://localhost:63342/Event%20Planner/www/index.html?Notes=1
when its usually
http://localhost:63342/Event%20Planner/www/index.html
Change this:
$('#submitEvent').on('click' , function submitEvent(){
to this:
$(document).on('click', '#submitEvent', function(){
I presume you are using .on() because the #submitEvent button is added dynamically. However, you must attach the .on event to an element that already exists when the DOM is initially rendered -- $(document) is a safe and common choice.
Reference:
Event delegation
I recommend you use the submit method https://api.jquery.com/submit/
<form id="yourFormName">
<label class="Courier" for="EventName"></label><br/>
<input class="Courier" required type="text" id="EventName" placeholder="Event name"><br/>
<input class="Courier" required type="Text" id="location" placeholder="venue"><br/>
<input class="Courier" required type="Text" id="DateAndTime" placeholder="Date and time"><br/>
<input class="Courier" required type="Text" id="Duration" placeholder="Duration"><br/>
<input class="courier" required type="Text" id="Clothing" placeholder="Dress code"><br/>
<input class="courier" required type="Text" id="Food" placeholder="Food"><br/>
<textarea class="courier" id="Notes" name="Notes" rows="4" cols="50">Enter additional notes here</textarea><br/>
<button type="submit">Submit</button>
</form>
And then
$( "#yourFormName").submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
Cheers!

Disable textbox if other textbox is not empty in CSS and JavaScript

I have a search form which contains text-boxes. What I want to ask is if textbox1(Hotel (num_rooms)) is not empty then the textbox2(Packages(num_days)) will be disabled or if textbox2(Packages(num_days)) is not empty then the textbox1(Hotel (num_rooms)) will be disabled. Because this search form will leads to different output based on the inputs of an user. If the user tries to put data in textbox1 and submit it, then it will return a lot of recommendations based on the user preferences about hotel same as in packages.
<form action="Filtered-SearchResult.php" method="post">
<div class="SearchForm">
<label id="Form"><h3 style="color:beige; text-align:left;">Search Form</h3></label><br>
<br>
<input type="text" name="location" class="searchtext" id="locate" placeholder="location" onkeyup="LettersOnly(this)" /><br>
<input type="text" name="from_budget" class="searchtext" placeholder="minimum budget" style="width:150px;" onkeyup="NumbersOnly(this)" />
<input type="text" name="to_budget" class="searchtext" placeholder="maximum budget" style="width:150px;" onkeyup="NumbersOnly(this)" /><br>
<input type="text" name="person" class="searchtext" placeholder="no of person" onkeyup="NumbersOnly(this)" /><br>
<input type="text" name="no_of_rooms" class="searchtext" style="width:150px;" placeholder="hotel(num_rooms)" onkeyup="NumbersOnly(this)" />
<input type="text" name="no_of_days" class="searchtext" style="width:150px;" placeholder="Packages(num_days)" onkeyup="NumbersOnly(this)" />
<script>
function LettersOnly(input) {
var regex = /[^a-zA-Z ]/gi;
input.value = input.value.replace(regex, "");
}
function NumbersOnly(input) {
var regex1 = /[^0-9]/gi;
input.value = input.value.replace(regex1, "");
}
</script>
<input type="submit" name="search1" value="Show Prices" id="Prices2" />
</div>
</form>
You can write a change event for no of rooms and no of days like this.
You can add more condition accordingly
$("#no_of_days").change(function(){
if($(this).val() == ""){
$("#no_of_rooms").attr("disabled", false);
}else{
$("#no_of_rooms").attr("disabled", true);
}
});
$("#no_of_rooms").change(function(){
if($(this).val() == ""){
$("#no_of_days").attr("disabled", false);
}else{
$("#no_of_days").attr("disabled", true);
}
});

Add multiple fields to form

I would like to add a function that generates multiple fields to my form.
This is how my form looks like:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".
How can I do this?
https://jsfiddle.net/374cxt5s/
Try this: https://jsfiddle.net/Twisty/q8zj00s0/1/
HTML
<form action="form_sent.php" method="post">
<ul id="fieldList">
<li>
<input name="name[]" type="text" placeholder="Name" />
</li>
<li>
<input name="phone[]" type="text" placeholder="Phone" />
</li>
<li>
<input name="email[]" type="text" placeholder="E-Mail">
</li>
</ul>
<button id="addMore">Add more fields</button>
<br>
<br>
<input type="submit">
</form>
CSS
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
JQuery
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
$("#fieldList").append("<li> </li>");
$("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
$("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
$("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
});
});
This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0] as the first one.
I'm assuming you probably want to create a dynamic form that allows you to add multiple contacts, etc.
CodePen Example
http://codepen.io/anon/pen/yeVRgw
The Basic HTML Setup
So that you can loop through things, and for sake of your own sanity, you'll probably want to segment out each chunk within the form. We'll also set up a hidden input to track how many partitions of name,phone,email have been created. We'll default at 1
<form action="form_sent.php" method="POST">
<input type="hidden" name="contacts" id="contacts" value="1">
<div class="form-contacts-container">
<div class="form-contact" id="form-contact-1">
<input type="text" name="name-1" id="name-1" placeholder="Name">
<input type="text" name="email-1" id="email-1" placeholder="E-mail">
<input type="text" name="phone-1" id="phone-1" placeholder="Phone">
</div>
<!-- We'll be adding additional inputs here -->
</div>
<div class="form-contacts-add">
<input type="button" value="Add More Fields" id="add-fields">
</div>
<div class="form-contacts-submit">
<input type="submit" name="submit" id="submit" value="Submit">
</div>
</form>
The JavaScript
This assumes you are using jQuery, so ensure that this is in your <head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Now we need to do a few things - firstly, attach an event listener to our button and secondly, add a new <div class="form-contact"> with included fields to our form. We'll also need to ensure that we're counting up to make sure each section has a unique name/id, and we'll increase the hidden input value to count how many contacts have been added in total.
<script type="text/javascript">
var total = 1; // Our default for how many contacts we have
$( document ).on( 'click', '#add-fields', function() {
var addBlockId = total = total + 1;
var addBlock = document.createElement('div');
$(addBlock).addClass('form-contact');
$(addBlock).attr('id','form-contact-' + addBlockId);
var inputName = document.createElement('input');
$(inputName).attr('type','text');
$(inputName).attr('name','name-' + addBlockId);
$(inputName).attr('id','name-' + addBlockId);
$(inputName).attr('placeholder','Name');
$(inputName).appendTo($(addBlock));
var inputEmail = document.createElement('input');
$(inputEmail).attr('type','text');
$(inputEmail).attr('name','email-' + addBlockId);
$(inputEmail).attr('id','email-' + addBlockId);
$(inputEmail).attr('placeholder','E-mail');
$(inputEmail).appendTo($(addBlock));
var inputPhone = document.createElement('input');
$(inputPhone).attr('type','text');
$(inputPhone).attr('name','phone-' + addBlockId);
$(inputPhone).attr('id','phone-' + addBlockId);
$(inputPhone).attr('placeholder','Phone');
$(inputPhone).appendTo($(addBlock));
$(addBlock).appendTo($('.form-contacts-container'));
$('#contacts').val(total);
});
</script>
Processing your Form
The last piece of the puzzle is to process your form properly. Not goign to give you all the answers here, but the basic logic would be to grab the $_POST['contacts'] value we've been updated and run a loop through to grab all of your inputs and associated values. For instance in PHP:
$total = $_POST['contacts'];
$contacts = array();
for( $i = 1; $i < $total; $i++ ) {
$this_contact = $array(
'Name' => $_POST['name-' . $i],
'Email' => $_POST['email-' . $i],
'Phone' => $_POST['phone-' . $i]
);
array_push($contacts, $this_contact);
}
var_dump( $contacts );
try something like this :
(function() {
var button=document.getElementById("add-user");
button.addEventListener('click', function(event) {
event.preventDefault();
var cln = document.getElementsByClassName("user")[0].cloneNode(true);
document.getElementById("users").insertBefore(cln,this);
return false;
});
})();
<form id="users" action="form_sent.php" method="post">
<div class="user">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id='add-user'>Add more fields</button><br><br>
<input type="submit">
</form>
https://jsfiddle.net/9955n4fo/
It might not be a bad idea to wrap your input fields in a div just so when you append the other inputs they appear consecutively. Try something like this in your html
<form action="form_sent.php" method="post">
<div id="fields">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
and then your javascript can be completed as so
$(function() {
$('button').click(function() { addFields(); });
});
function addFields() {
var html = "<input name='name' type='text' placeholder='Name'><br>
<input name='phone' type='text' placeholder='Phone'><br>
<input name='email' type='text' placeholder='E-Mail'><br><br>";
$('#fields').append(html);
}
You need to implement jQuery to change the HTMLs DOM.
So, you add this in your <head></head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
You need to modify your HTML like this:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button extra="0">Add more fields</button><br><br>
<input type="submit">
</form>
Then you need to use this jQuery code:
<script>
$("button").on("click",function(){
var extra = $(this).attr("extra") + 1;
$("form").append("<input type='text' placeholder='Other Field' name='field' />");
$(this).attr("extra",extra);
}
</script>
This is the end!! :)
Try This :
Jquery append() function seems to sort out your answer
HTML Code should be as follow :
<form action="form_sent.php" method="post">
<div class = 'xyz'>
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
you JS should be as follow :
$(button).click(function(event){
$('.xyz').append("<input type ='text' class ='name' placeholder = 'Enter name'/><br/>");
$('.xyz').append("<input type='text' class='phone' placeholder='Enter phone'/><br/>");
$('.xyz').append("<input type='mail' class='phone' placeholder='Enter e-mail'/><br/>");
event.preventDefault();
});
This is how I would solve it.
HTML:
<form action="form_sent.php" method="post">
<div id="inputHolder">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id="addMoreFields">Add more fields</button><br><br>
<input type="submit">
</form>
JS:
$( document ).ready(function() {
$("#addMoreFields").click(function(event) {
event.preventDefault();
$("#inputHolder").append('<input name="name" type="text" placeholder="Name"><br>');
$("#inputHolder").append('<input name="phone" type="text" placeholder="Phone"><br>');
$("#inputHolder").append('<input name="email" type="text" placeholder="E-Mail"><br><br>');
});
});
https://jsfiddle.net/r71odb7t/
First you want to clone the elements you want to be adding. Do that when the page loads. Then when the button is clicked, clone the copy and add a copy to the page. And, you could either add type="button" to the button or use e.preventDefault() so your form does not get submitted when the button is clicked.
$(function() {
var inputs = $('form > button').prev().prev().prevUntil().clone().add('<br><br>');
$('form > button').on('click', function(e) {
e.preventDefault();
$(this).before(inputs.clone());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>

Validating messages before submit

I'm making a html5 application which require all fields to be filled in before the submit button can be clicked.
What I want to do now is give an alert if a textbox is not filled in, the problem is that my submit button is disabled until all fields are filled in, so I can't really add an alert to that button.
Any idea's on how to solve this?
I want it so that after filling in the final textbox the submit button becomes available without first having to click on it.
Note that the 'required' does not work.
I have the following code:
HTML:
<form id="winForm">
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
</p>
<p>
<input type="text" id="telefon" name="telefon" onclick="generateFullAdress()" required />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="sendTheMail()" value=" ">
</button><div id="loading"><img src="images/loadingBar.gif" id="load"></img></div>
</p>
</form>
Jquery/JS
<script type="text/javascript">
function generateFullAdress() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
var $input = $('input:text'),
$register = $('#submitBtn');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
if(trigger) {
$register.attr('disabled',true);
}else {
$register.removeAttr('disabled');
}
});
</script>
Help would greatly be appreciated.
Thanks!
If you have a form as such:
<form id="form">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$(function() {
$('#form').submit(function() {
// DO STUFF
return true; // return false to cancel form action
});
});
OR
perform the samething with the onsubmit event like
<form action="youraction" onsubmit="validatefunction" method="post">

Categories

Resources