My added eventhandler working once only when the page is loaded - javascript

I am trying to check if user change field while it is still empty.And I'm adding event listener on the username field so when the user move from one field to other then he get either a check sign or an error.
My HTML File:
<!DOCTYPE html>
<html>
<head>
<title>Registeration form</title>
<link type="text/css" rel="stylesheet" href="css/fontawesome.css"/>
</head>
<body>
<form method="post">
<fieldset>
<input type="text" name="user_name" id="user_name" style="display:inline;float:left;" placeholder="User Name">
<li id="name_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="text" name="email" id="email" style="display:inline;float:left;" placeholder="Email Address">
<li id="email_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="button" name="submit" id="submit" value="submit">
</fieldset>
</form>
<script type="text/javascript" src="js/test.js"></script>
</body>
</html>
My Javascript file:
var user_name=document.getElementById("user_name");
var user_name_status=document.getElementById("name_status");
user_name.addEventListener("blur",check_empty(user_name.value,user_name_status),false);
function check_empty(value,status){
if(value.length===0){
status.innerHTML="<sup>*</sup>This feild cannot be empty";
} else {
status.innerHTML="<i class='icon-check'></i>";
}
}

You are calling check_empty immediately. You can pass function reference check_empty to .addEventListener(). Within event handler, this references user_name. Instead of passing variable status, utilize the defined varibale user_name_status within event handler.
var user_name = document.getElementById("user_name");
var user_name_status = document.getElementById("name_status");
user_name.addEventListener("blur", check_empty, false);
function check_empty(e) {
if (this.value.length === 0) {
user_name_status.innerHTML = "<sup>*</sup>This feild cannot be empty";
} else {
user_name_status.innerHTML = "<i class='icon-check'>check</i>";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Registeration form</title>
</head>
<body>
<form method="post">
<fieldset>
<input type="text" name="user_name" id="user_name" style="display:inline;float:left;" placeholder="User Name">
<li id="name_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="text" name="email" id="email" style="display:inline;float:left;" placeholder="Email Address">
<li id="email_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="button" name="submit" id="submit" value="submit">
</fieldset>
</form>
</body>
</html>

I think the best option for you is to pass the function with argument inside an anonymous function like the code below shows.
var user_name = document.getElementById("user_name");
var user_name_status = document.getElementById("name_status");
user_name.addEventListener("blur",function(){check_empty(user_name.value,user_name_status);},false);
function check_empty(name,status) {
if (name.length === 0) {
status.innerHTML = "<sup>*</sup>This feild cannot be empty";
} else {
status.innerHTML = "<i class='icon-check'>check</i>";
}
}
<!DOCTYPE html>
<html>
<head>
<title>Registeration form</title>
</head>
<body>
<form method="post">
<fieldset>
<input type="text" name="user_name" id="user_name" style="display:inline;float:left;" placeholder="User Name">
<li id="name_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="text" name="email" id="email" style="display:inline;float:left;" placeholder="Email Address">
<li id="email_status" style="list-style-type:none;"></li>
</fieldset>
<fieldset>
<input type="button" name="submit" id="submit" value="submit">
</fieldset>
</form>
</body>
</html>

Related

jquery on form calculation max values without submit

how can i do dynamic form calculation without submit? submitting is about php server. I need to calculate this form with limiting max values. Example result value can't be above buy value. when above must give error submit button disabled.
I can't find any solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#storage","#result","#account").on(keyup, change(function(){
var abc = $("#abc").val();
var price = $("#price").val();
var storage = $("#capacity").val() - $("#abc").val();
$("#storage").val(storage);
var result = $("#price").val() * $("#abc").val();
$("#result").val(result);
var account = buy - result;
$("#account").val(account);
});
});
</script>
</head>
<body>
<form method="post" action="" >
<input id="buy" type="hidden" class="form-control" name="buy" value="5000000" />
<input type="hidden" id="capacity" class="form-control" name="capacity" value="1000000" />
Storage : <input id="storage" type="text" class="form-control" name="storage" min="0" max="1000000" value=""/><br>
Abc: <input id="abc" type="text" class="form-control" name="abc" min="0" max="1000000" value="" /> <br>
Price: <input id="price" type="text" class="form-control" name="price" value="15" /> <br>
Result: <input id="result" type="text" class="form-control" name="result" value=""/> <br>
Account: <input id="account" type="text" class="form-control" name="account" max="5000000" value="" /> <br>
<input type="button" id="submit" value="submit">
</form>
</body>
</html>
Use an input / keyup event listener. For example (Vanilla JS):
document.getElementById('myInput').addEventListener("keyup", function() {
console.log(document.getElementById("myInput").value);
// Do your stuff here
});
<input id="myInput" />
Or with jQuery:
$('#myInput').keyup(function() {
console.log($("#myInput").val());
// Do your stuff here
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
Although this is heplful, JavaScript (besides Node) is client-side and can be easily overriden, so make sure you evaluate the input in the backend too.

How do I get array to show up in an unordered list?

I have the following code, and I want the gather_form_elements array to show up as an unordered list.
Here is my html part:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta author="Justin Roohparvar">
<link rel="stylesheet" href="CSS\css.css">
<script src="Javascript/form.js"></script>
<title>Contact Form</title>
</head>
<body>
<form method="POST" action="week_1_contact_form.html">
<h1>Contact Form</h1>
<input id="first_name" type="text" maxlength="50" size ="25" placeholder="First Name" required> <br /><br />
<input id="last_name" type="text" maxlength="50" size="25" placeholder="Last Name" required> <br /><br />
<input id = "email" type="email" name="email" placeholder="Email" required> <br /> <br />
<input id="phone_number" type="tel" name="phone_number" placeholder="Phone Number" required><br /><br />
<input type="Submit" name="Submit" value="Submit" onclick="getFormElements()">
</form>
</body>
</html>
And my form.js code is below:
function getFormElements() {
var gather_form_elements = new Array(document.getElementById("first_name"), document.getElementById("last_name"),
document.getElementById("email"), document.getElementById("phone_number"));
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.write(gather_form_elements[i]);
}
}
Any suggestions would be appreciated.
First of all, you have to get values from your inputs, not just elements itself. With your approach, it should look like this:
function getFormElements() {
var gather_form_elements = new Array(document.getElementById("first_name").value, document.getElementById("last_name").value,
document.getElementById("email").value, document.getElementById("phone_number").value);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
document.write('<ul>');
for(i=0; i<gather_form_elements.length; i++)
{
document.write('<li>'+gather_form_elements[i]+'</li>');
}
document.write('</ul>');
}
As Newbie says, you need to get the value of each controls. A much simpler version of the listener is to make use of the form's elements collection. Controls must have a name to be successful, you can leverage that to work out which controls to get the values of:
function getFormElements(form) {
var values = [];
[].forEach.call(form.elements, function(control) {
if (control.name) {
values.push(control.value);
}
});
// Show values for testing
console.log(values);
return values;
}
<form onsubmit="getFormElements(this); return false"> <!-- prevent submit for testing -->
<h1>Contact Form</h1>
<input name="first_name" type="text" maxlength="50" size="25" placeholder="First Name" required> <br><br>
<input name="last_name" type="text" maxlength="50" size="25" placeholder="Last Name" required> <br><br>
<input name="email" type="email" placeholder="Email" required> <br> <br>
<input name="phone_number" type="tel" placeholder="Phone Number" required><br><br>
<input type="submit" value="Submit">
</form>
This lets you add more controls and doesn't care what you call them.
So only name controls that need a name, don't use IDs if you don't need them and put the submit listener on the form's submit handler so that no matter how the form is submitted, the listener is called. ;-)

Wont log to console, javascript

I am having trouble writing to the console with the following code. Unsure as to why it is not working as am a beginner JavaScript programmer. May be a stupid question because I am new to JavaScript.
Javascript:
function process(){
'use strict';
var user = document.getElementById("user").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("pass").value;
var age = document.getElementById("age").value;
console.log(user);
};
function init(){
'use strict';
document.getElementById('signUp').onsubmit = process;
};
window.onload = init;
html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Employee Register</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen"/>
</head>
<body>
<form action="#" method="post" id="signUp" class="form">
<h1>Sign up.
<span>Please complete all information.</span>
</h1>
<label for="user">
<span>Username:</span>
<input type="text" name="user" id="user" required>
</label>
<label for="name">
<span>Full Name:</span>
<input type="text" name="name" id="name" required>
</label>
<label for="email">
<span>Email Address:</span>
<input type="email" name="email" id="email" required>
</label>
<label for="pass">
<span>Password:</span>
<input type="password" name="pass" id="pass" required>
</label>
<label for="age">
<span>Age:</span>
<input type="text" name="age" id="age" required>
</label>
<input type="submit" value="Submit" id="submit">
</form>
<div id="members" class="output">
<h1>Registered Members</h1>
</div>
<script src="register.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
The reason for this is that the log is renewed for every request (in case of Chrome browser) and as you are setting the console.log to be fired onsubmit the log is logged but will be cleared immediately
Check the checkbox Preserve Log in the console of Chrome.
You can change the input type to a normal button to prevent the submit <input type="button" value="Submit" id="submit">.
After doing whatever you want with the fields you can submit the form with signUp.submit() or document.getElementById('signUp').submit().

Contact form doesn't send data

I have a simple contact form on contact.php, but submitting it there is no any data into corresponding php file (mail.php).
form inside contact.php
<form id="contact" action="" method="post">
<input id="name" type="text" name="name" width="250" size="35" placeholder="Your name">
<br><br>
<input id="email" type="text" name="email" width="250" size="35" placeholder="Your mail">
<br><br>
<textarea id="message" name="message" rows="6" cols="40" placeholder="Your message"></textarea>
<br><br>
<input type="button" value=" SEND " id="submit" />
<input type="reset" value="Reset" name="reset">
</form>
js inside contact.php
$('#submit').click(function(){
$.post("mail.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
mail.php
print_r( $_POST );
if((empty($_POST['name'])) || (empty($_POST['email'])) || (empty($_POST['message']))){
die("All fields must be filled !");
}
result:
Array ( ) All fields must be filled !
Working Example:
<html>
<head>
<title>Example</title>
<style type="text/css">
div { color:blue; margin:3px; cursor:pointer; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e){
$.post("mail.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
});
</script>
</head>
<body>
<div id="success"></div>
<form name="contact" id="contact" method="post">
<?php
for($i=1;$i<=10;$i++)
{?>
Text Box <?php echo $i; ?> <input type="text" name="in<?php echo $i; ?>"/><br/><br/>
<?php
}
?>
<input type="submit" name="submit" id="submit"/>
</form>
</body>
</html>
mail.php
<?php
print_r( $_POST );
if((empty($_POST['name'])) || (empty($_POST['email'])) || (empty($_POST['message']))){
die("All fields must be filled !");
}
?>
It's work for me.
This is a.html file
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('#submit').click(function(){
$.post("x.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
});
});
</script>
</head>
<body>
<form id="contact" action="" method="post">
<input id="name" type="text" name="name" width="250" size="35" placeholder="Your name">
<br><br>
<input id="email" type="text" name="email" width="250" size="35" placeholder="Your mail">
<br><br>
<textarea id="message" name="message" rows="6" cols="40" placeholder="Your message"></textarea>
<br><br>
<input type="button" value=" SEND " id="submit" />
<input type="reset" value="Reset" name="reset">
</form>
</body>
</html>
This is x.php file
<?php
print_r( $_POST );
if((empty($_POST['name'])) || (empty($_POST['email'])) || (empty($_POST['message']))){
die("All fields must be filled !");
}
?>
Try it, will prevent your form to submit naturally:
$('#submit').click(function(e){
e.preventDefault();
});
One other change you may try is:
$("#contact").serializeArray()

Login Form Validation

I have this code below which validates a form. However, there is a bug in this code. When I enter something in username and leave the password blank, the form accepts it. It shouldn't be accepting it. Any idea why?
<html>
<head> <link type = "text/css" type="text/javascript" rel="stylesheet" href="css/bootstrap.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script src="js/bootstrap.js"> </script>
<script>
$(document).ready(function() {
$('form').validate({
submitHandler: function(form) { // for demo
alert('valid form');
return false;
}
});
});</script>
</head>
<body>
<form class="well span6">
<label>Username</label>
<input type="text" id="myName" class="span3 required" placeholder="Type your username here..." /> <br/>
<label>Password</label>
<input type="text" id="myPassword" class="span3 required" placeholder="Type your password here..." /> <br/>
<input type="submit" class ="btn btn-primary">
<!-- <button class=""> Clear <br/></button><br/> -->
</form>
</body>
</html>
I'm pretty sure this validation plugin like a 'name' attribute on the field.
I've added name="myName and name="myPassword on each input and it seems to work in this jsfiddle
<form class="well span6">
<label>Username</label>
<input name="myName" type="text" id="myName" class="span3 required" placeholder="Type your username here..." /><br/>
<label>Password</label>
<input name="myPassword" type="text" id="myPassword" class="span3 required" placeholder="Type your password here..." /><br/>
<input type="submit" class="btn btn-primary">
</form>
Try to by adding the "name" attribute, to the password and username fields.

Categories