javascript - printing form values to console.log giving undefined error - javascript

I was trying to print form values on submit to console.log to test. But getting a undefined message. Can't figure out where I am going wrong exactly. I have gone through various answers on StackOverflow but still no luck. Here is the code -
HTML
<form class="form-inline">
<label class="required">* required </label>
<div class="form-group">
<input type="text" class="form-control inputArea" id="fullname" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="email" class="form-control inputArea" id="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="tel" class="form-control inputArea" id="phn" placeholder="Phone Number *">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
JavaScript
<script>
var formInput = document.querySelectorAll('#fullname, #email, #phn');
document.querySelector('form.form-inline').addEventListener('submit', function (e) {
e.preventDefault();
console.log(formInput.value);
});
</script>

You are getting undefined because forminput is not a single object it has multiple objects which doesn't have property value.
You can get value by index like below
console.log(formInput[0].value);

You are querying the form before the values are inputted. The first line of your script should be inside the event listener:
<script>
document.querySelector('form.form-inline').addEventListener('submit', function (e) {
e.preventDefault();
var formInput = document.querySelectorAll('#fullname, #email, #phn');
console.log(formInput.value);
});
</script>
The values are being query-ed on page-load. You need to wait until the user submits before you check the values.

You can try this. Hope it helps!
function myFunction(){
var a = document.getElementById("fullname").value;
var b = document.getElementById("email").value;
var c = document.getElementById("phn").value;
console.log(a);
console.log(b);
console.log(c);
return false;
}
<form class="form-inline" onsubmit = " return myFunction()">
<label class="required">* required </label>
<div class="form-group">
<input type="text" class="form-control inputArea" id="fullname" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="email" class="form-control inputArea" id="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="tel" class="form-control inputArea" id="phn" placeholder="Phone Number *">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>

Related

Why is my form not returning an alert when password does not match the confirm password field Javascript?

So I'm new to JS, and I'm trying to make this form prevent submission if password does not match the confirm password field. However, when I enter in 2 different passwords, I don't get an alert like I've coded in the script below. Any thoughts? For reference, the form was built w/ bootstrap.
<form class="form-signin">
<div class="form-label-group">
<input type="text" id="fullName" class="form-control" placeholder="Username" required autofocus>
<label for="fullName">Full name</label>
</div>
<div class="form-label-group">
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required>
<label for="inputEmail">Work email</label>
</div>
<div class="form-label-group">
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<label for="inputPassword">Password</label>
</div>
<div class="form-label-group">
<input type="password" id="inputConfirmPassword" class="form-control" placeholder="Password" required>
<label for="inputConfirmPassword">Confirm password</label>
</div>
<button class="btn btn-lg btn-primary btn-block text-uppercase" id ="register-btn" type="submit">Register</button>
<hr class="my-4">
<div class="registration-login">
<p class="already-have__account">Already have an account?</p> Login
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="registration__section">
<h2>Innovative supply chain teams use Rumi to manage scalable and sustainable packaging.
</h2>
</div>
<script>
var form = document.getElementById('form-signin');
form.onsubmit = function() {
if (inputPassword.value !== inputConfirmPassword.value) {
alert("Your passwords don't match");
return false;
}
else {
return true;
}
}
Just a minor mistake.
You are using get getElementById.
var form = document.getElementById('form-signin');
There is no id with 'form-signin',
<form class="form-signin">
Rename the class to id.
<form id="form-signin">
Check out this (JSFiddle). It's working here.

JavaScript Onclick is not working in tag

HTML:
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="new User().register()">REGISTER</div>
</div>
</form>
Js File
var User = function() {
var self = this;
self.register = function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/
var regEight = /^8[0-9].*$/
if($("#empId").val() =='')
{
alert(Language.InvalidEmployeeId);
return false;
}
if(mobile =='')
{
alert(Language.EmptyMobileNumber);
return false;
}
}
};
if i write a coding for click event like below its working when i use OnClick event function is not calling
$("#regBtn").click(function ()
{
new User().register();
})
how to make the onclick work.. thanks in advance
In onclick call a function that does new User().register().
Do not write literal expression, wrap that expression in function and call that function.
try with this code
$("#regBtn").click(function() {
var mobile = $("#mobile").val();
var regSeven = /^7[0-9].*$/;
var regEight = /^8[0-9].*$/;
if ($("#empId").val() == '') {
// alert(Language.InvalidEmployeeId);
console.log("InvalidEmployeeId");
return false;
}
if (mobile == '') {
//alert(Language.EmptyMobileNumber);
console.log("Empty mobile number");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="javascript:if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn">REGISTER</div>
</div>
</form>
</div>
Do something like this...
<div class="loginDiv">
<form class="validate" role="form">
<div class="form-group float-label-control">
<input type="text" id="empId" placeholder="Employee ID" required>
</div>
<div class="form-group float-label-control">
<input type="tel" name="mobileNo" maxlength="10" id="mobile" placeholder="Mobile Number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required>
</div>
<div class="align_center">
<div class="btn loginBtn" id="regBtn" onclick="registerUser()">REGISTER</div>
</div>
</form>
</div>
Java script
function registerUser(){
new User().register();
}
In this case the function registerUser() is re-usable as you commented above "Actually i want to make use of the onclick event so that function can be reused if i give a id i cant reuse that in another page".

Timeout function works for one form but ignores the other

I'm having a very specific problem. I have two forms on a page, bootstrap validator included and it works just fine, except that it doesn't have the RegEx check for email input. So I created a short RegEx validation, but when I try to handle error messages, they work as intended only for the second form. When I click submit button, error messages show up on both form, but timeout functions works nly for the latter one. Submit button for the top form keep creating new error messages whenever I click on it. Any advice? Please see my code below:
HTML:
Top form:
<form action="" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name:" required>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email Address:" required>
</div>
<div class="form-group">
<input type="tel" class="form-control" name="phone" placeholder="Phone Number:" required>
</div>
<div class="form-group">
<input type="text" class="form-control" name="amount" placeholder="Investment Amount (£)">
</div>
<button class="btn btn-block btn-submit" type="submit" name="submit">Enquire Now</button>
Bottom form:
<form action="" method="POST" class="row form-find-more">
<div class="form-group col-lg-3 col-md-3">
<input type="text" name="name" placeholder="Full Name*:" required>
</div>
<div class="form-group col-lg-3 col-md-3">
<input type="email" name="email" placeholder="Email Address*:" required>
</div>
<div class="form-group col-lg-3 col-md-3">
<input type="text" name="phone" placeholder="Phone Number*:">
</div>
<div class="form-group col-lg-3 col-md-3">
<button class="btn" type="submit" name="submit">Submit Request</button>
</div>
</form>
My jQuery snippet:
<script>
var emailReg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var elm = $('<div class="help-block with-errors">Please enter a valid e-
mail</div>');
$(document).on('click', 'form button[type=submit]', function(e) {
var isValid = emailReg.test(jQuery.trim($(e.target).parents('form').find("input[type=email]").val()));
if(!isValid) {
e.preventDefault(); //prevent the default action
$('form').append(elm);
}
});
setTimeout(function() {
elm.detach();
}, 5000);
</script>
Managed to fix the problem by some code edits:
var emailReg = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-
9]+\.)+[a-zA-Z]{2,}))$/;
var elm = $('<div class="help-block with-errors">Please enter a valid e-mail</div>');
$(document).on('click', 'form button[type=submit]', function(e) {
var isValid = emailReg.test(jQuery.trim($(e.target).parents('form').find("input[type=email]").val()));
if(!isValid) {
e.preventDefault(); //prevent the default action
$('form').append(elm.prop('outerHTML'));
setTimeout(function() {
$('.help-block.with-errors').remove();
}, 3000);
}
});
Thank you everyone who helped.

Onsubmit not working

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>

JQuery code I wrote stopped working, is there anywrong I've overlooked?

For the below code I want the content of the submit button with the .btn-primary attribute to change to "Success!" only if the input fields are all not null.
At preset the code goes straight to success when the button is press whether or not the fields have content.
I thought it might be because the fields may somehow already have a value that is not null so I ran this code: alert($('#Comment').attr("value")); and it returned undefined in the alert message. Undefined is the same as null in js/jquery isn't it?
I got this code to work earlier and it was typed almost the same way with just a few changes. I undid the changes but it still does not work.
Any help will be appreciated. (If anyone knows this) Are there instances in which the same code could not work at a different time, all things being equal?
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
$(document).ready(function () {
var Fname = $('#FirstName').attr("value");
var Lname = $('#LastName').attr("value");
var Email = $('#Email').attr("value");
var Comment = $('#Comment').attr("value");
$(".btn-primary").click(function () //This block should say, if all fields are not null changed the content of button to "Success!" and change the content of <h1> to "THANKS, I'VE GOT YOUR MESSAGE."
{
if (Fname != null && Lname != null && Email != null && Comment != null)
{
$("button").html("Success!");
$("h1").html("THANKS, I'VE GOT YOUR MESSAGE");
}
})
});
</script>
And this is the html on the same page
<form class="form-horizontal" role="form" action="/Home/Contact" method="post">
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" data-val="true" data-val-required="Please enter your first name" id="FirstName" type="text" placeholder="First Name" name="FirstName"/>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your last name" id="LastName" type="text" placeholder="Last Name" name="LastName"/>
<span class="field-validation-valid text-danger" data-valmsg-for="LastName" data-valmsg-replace="true" data-></span>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your email" id="Email" name="Email" type="email" placeholder="Email#Address.com"/>
<span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" required data-val="true" data-val-required="Please enter a brief detailed message" id="Comment" name="Comment" placeholder="A Short but detailed message"></textarea>
<span class="field-validation-valid text-danger" data-valmsg-for="Comment" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="submit" class="btn btn-primary btn-sm active" value="submit">Submit</button>
<input type="reset" class="btn btn-default btn-sm active" value="reset">
</div>
</div>
</form>
When your document loads you are storing the value of Fname, Lname ..... so on. The issue is you then use these values in your conditional test but the values will not have changed as they are just the raw value from the first time the page loaded. One quick fix would be to bring these inside the click so on every click they can re evaluated
Also when checking you are only checking for null but these are not going to equal null anyway. Better would be to fully validate them or just test for generic truthy which excludes the falsy values such as null, undefined, empty string
$(document).ready(function () {
$(".btn-primary").click(function (e)
{
var Fname = $('#FirstName').val();
var Lname = $('#LastName').val();
var Email = $('#Email').val();
var Comment = $('#Comment').val();
//ADDED JUST TO STOP THE FORM SUBMITTING
e.preventDefault();
//very quick test but this could be a lot more detailed for true validation on each field
if (Fname && Lname && Email && Comment) {
$("button").html("Success!");
$("h1").html("THANKS, I'VE GOT YOUR MESSAGE");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>
<form class="form-horizontal" role="form" action="#" method="post">
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" data-val="true" data-val-required="Please enter your first name" id="FirstName" type="text" placeholder="First Name" name="FirstName" />
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your last name" id="LastName" type="text" placeholder="Last Name" name="LastName" /> <span class="field-validation-valid text-danger" data-valmsg-for="LastName" data-valmsg-replace="true" data-></span>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input class="form-control" required data-val="true" data-val-required="Please enter your email" id="Email" name="Email" type="email" placeholder="Email#Address.com" /> <span class="field-validation-valid text-danger" data-valmsg-for="Email" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<textarea class="form-control" required data-val="true" data-val-required="Please enter a brief detailed message" id="Comment" name="Comment" placeholder="A Short but detailed message"></textarea> <span class="field-validation-valid text-danger" data-valmsg-for="Comment" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="submit" class="btn btn-primary btn-sm active" value="submit">Submit</button>
<input type="reset" class="btn btn-default btn-sm active" value="reset">
</div>
</div>
</form>

Categories

Resources