I have created a contact (4 input text) form and I want if user doesn't text in anyone of input a text message will appear above each input.
Contact From:
<form class="form-horizontal" method="post" action="#" name="form" onsubmit="return validation();">
<fieldset>
<div><h2 style="font-family: Myriad Pro;color:#7f8c8c">form</h2></div>
<div class="form-group">
<div class="col-sm-8">
<input id="fname" name="name" type="text" placeholder="Όνομα" class="form-control">
<div id="error1" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input id="lname" name="surname" type="text" placeholder="Επώνυμο" class="form-control">
<div id="error2" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 ">
<input id="email" name="email" type="email" placeholder="E-mail" class="form-control">
<div id="error3" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 ">
<textarea id="message" name="message" type="text" placeholder="Το σχόλιο σας.." columns="7" rows="7" class="form-control" style="background-color:#e5e6e6;" required=""></textarea>
<div id="error4" style="color:#e8645a"></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-3 text-center">
<button type="submit" class="btn btn-primary btn-block" id="label" >SEND</button>
</div>
</div>
</fieldset>
</form>
And the script I use:
function validation(){
if (document.form.name.value == "") {
document.getElementById('error1').innerHTML="*Error Msg1 ";
}else if (document.form.surname.value == "") {
document.getElementById('error2').innerHTML="*Error Msg2 ";
}else if (document.form.email.value == "") {
document.getElementById('error3').innerHTML="*Error Msg3 ";
}else if (document.form.message.value == "") {
document.getElementById('error4').innerHTML="*Error Msg4 ";
}
return false;
}
My issue is that if for example the user doesn't fill his name(error message displayed below the text field) BUT then if he text his name the error message IS still displayed.How can I solve this?
There is an example here: Fiddle
I would suggest that you clear the error message at the start of the validation again:
function validation(){
document.getElementById('error1').innerHTML=""
document.getElementById('error2').innerHTML=""
document.getElementById('error3').innerHTML=""
document.getElementById('error4').innerHTML=""
//Your validation code below:
...
}
This way whenever the input validates, all of the error messages will be cleared and evaluated again.
You might want to consider storing the labels at the start of the function in a field so you have easy access to them later. This should help with readability as well. For example:
function validation(){
var errorMessage1 = document.getElementById('error1');
//Access the label using your new variable:
errorMessage1.innerHTML = "Your value here"
...
On keyup event lets try resetting the error message
document.form.name.addEventListener("keyup", function(){
document.getElementById('error1').innerHTML = '';
});
Related
I need to enable the submit button, only when all the Input values were given.
I have a form like the below in my blade file.
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value=""/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5"> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>
Added the required attribute inside the controller.
In controller:
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required',
]);
}
The problem is, even if I add the name field and click the button , the submit button is disabled on click.
The button should be disabled, only when all the input fields were given.
Script:
const button = document.querySelector("#buttonSubmit");
const buttonExpirationDataKey = 'button-disabled-expiration';
button.addEventListener("click", () => {
var form = document.getElementById("contactForm");
var fields = ["name", "email","body"];
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if(form[fieldname].value !== ""){
button.disabled = true;
let now = new Date();
let expirationTime = 1000 * 5; // 5 secs to disable the submit button
let expirationDate = new Date(now.getTime() + expirationTime);
localStorage.setItem(buttonExpirationDataKey, expirationDate);
button.dataset.enabledAt = expirationDate;
}
else {
button.disabled = false;
}
return false;
}
});
The for loop iterates over each input element, if the particular input element have a value and then If we click the submit. The button is disabled and stored in the local storage.
How to check all the form input and the textarea has values and then after clicking the submit button, the button should be disabled for 5 secs.
https://jsfiddle.net/1vgzj8oc/
How could I do this? Could anyone please help?
You can simply add the required attributes to the HTML
<input type="text" name="name" id="name" value="" required/>
But if you choose to do it with jS, you can do it this way...
<input type="text" name="name" id="name" value="" class="requiredInput"/>
<input type="submit" value="Submit" class="requiredInput primary" id="buttonSubmit" disabled/>
const requiredInputs = document.querySelectorAll(".requiredInput");
requiredInputs.forEach(function(input) {
// Logic
});
You can add required attribute. added link for reference
[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required]
<form method="POST" id="contactForm">
<div class="row">
<div class="col-6">
<input type="text" name="name" id="name" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-6">
<input type="text" name="email" id="email" value="" required/>
<div class="error">Error Message</div>
</div>
<div class="col-12">
<textarea name="body" id="message" rows="5" required> Enter your message</textarea>
<div class="error">Error message</div>
</div>
<div class="col-12">
<input type="submit" value="Submit" class="primary" id="buttonSubmit" disabled/>
</div>
</form>
The method validateRegistrationForm is not being called, I have tested this by placing an alert inside and can't figure out why this is the case.
There is other JavaScript to validate other things though I have removed that until this issue is resolved.
The JavaScript itself is being linked to the HTML via script tags inside of the body. I put an alert at the top of the JS to make sure the link is working and it is.
HTML:
<form name="registrationForm" id="registrationForm" action="AddUserDetails">
<div class="form-group">
<label for="firstName">First Name</label>
<span id="firstNameError">*</span>
<input type="text" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName">Second Name</label>
<span id="lastNameError">*</span>
<input type="text" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<span id="phoneNumberError">*</span>
<input type="text" class="form-control" id="phoneNumber">
</div>
<div class="form-group">
<label for="eMail">E-Mail</label>
<span id="eMailError">*</span>
<input type="text" class="form-control" id="eMail">
</div>
<div class="form-group">
<label for="eMailConfirmation">Confirm E-Mail</label>
<span id="eMailConfirmationError">*</span>
<input type="text" class="form-control" id="eMailConfirmation">
</div>
<div class="form-group">
<label for="password">Password</label>
<span id="passwordError">*</span>
<input type="password" class="form-control" id="password">
</div>
</form>
<div class="text-center">
<input type="button" id="submitRegistationForm" value="Submit">
</div>
JavaScript:
var $ = function (id) {
return document.getElementById(id);
}
var validateRegistrationForm = function () {
alert("");
var isValid = true;
//First Name Validation
if ($("firstName").value == "") {
$("firstNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("firstNameError").firstChild.nodeValue = "";
}
//Second Name Validation
if ($("lastName").value == "") {
$("lastNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
isValid = false;
} else {
$("lastNameError").firstChild.nodeValue = "";
}
if (isValid) {
$("registrationForm").submit();
}
}
window.onload = function () {
$("submitRegistationForm").onclick = validateRegistrationForm;
}
Redefining $ seems like an awful idea, especially if this is code shared amongst other developers. In either case, why even wait for window.onload? You could just declare your click handler outside of it. Working jsfiddle:
$("submitRegistationForm").onclick = validateRegistrationForm;
https://jsfiddle.net/ou3gLLqe/
My HTML code is
<body>
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>
<script>
function search() {
var Tab = document.getElementById("Tab").value;
alert(Tab);
var Eamillogin = document.getElementById("UEmailLogin").value;
if (Eamillogin == "") {
alert("please enter email");
Eamillogin.focus();
}
}
</script>
</body>
When I click on submit button, JavaScript alert shows "please enter email". It works fine. But Eamillogin.focus(); not working. After showing alert, the form automatically direct to test1.php page.Pointer not focus on Email. How to correct it?
Eamillogin variable contains the value of the #UEmailLogin element.
To set the focus on the element, use element.focus();
Here's updated code
var Eamillogin = document.getElementById("UEmailLogin"); // Removed .value from here
if (Eamillogin.value === "") { // Added .value here
alert("please enter email");
Eamillogin.focus(); // Focus element
}
function search() {
var Tab = document.getElementById("Tab").value;
var Eamillogin = document.getElementById("UEmailLogin");
if (Eamillogin.value === "") {
alert("please enter email");
Eamillogin.focus();
}
}
<form name="contactus" id='contactus' action="test1.php" method="post" enctype="multipart/form-data">
<input type="hidden" value="2" name="Tab" id="Tab">
<div class="row underlinDv">
<div class="col-sm-4">
Your Email :
</div>
<div class="col-sm-8">
<input maxlength="100" type="email" class="form-control" placeholder="Enter Email" name="UEmailLogin" id="UEmailLogin" minlength="3">
</div>
</div>
<!--18-->
<div class="row underlinDv">
<div class="col-sm-8 col-md-offset-4">
<input type="submit" id="demo2GetTags" class="btn btn-primary btn-md" value="Submit" onclick='search()' />
</div>
</div>
</form>
I create a form in html5 like this example :
<form action="/my/url/insert.php" method="POST">
<div class="row">
name <input name="name" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
$('form').submit(function(){
console.log('test');
});
</script>
The problem :
I want to detect the name of the required field that are not validated when submiting and logging it.
for example : if I don't fill the input "album" when submit i detect it before the message "a field is required..."
is there a way to do this ?
thank you.
Here you go.. Loop through each input:required field and get its name with .attr.
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
console.log($(this).attr('name'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Updated
$('form').submit(function(e) {
e.preventDefault();
$(this).find('input:required').each(function(){
if($(this).val()==""){ //check if its empty
console.log($(this).attr('name'));
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate action="/my/url/insert.php" method="POST">
<div class="row">
name
<input name="name" required/>
</div>
<div class="row">
type
<input name="type" required/>
</div>
<div class="row">
year
<input name="year" required/>
</div>
....
<div class="row">
album
<input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save" />
</div>
</form>
Assuming that only required will be the property for validation, above condition will hold good and yea, by default when you say required, browser will have its validation suppressing validation written by you. If you want your validation to work, add novalidate to form as said in one of the comments above..
Select them by property required:
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
console.log($(this).attr("name"));
});
});
});
To do a simple required check on your own make a simple "not empty" condition. But for this, your form need the novalidate class, otherwise submit callback will not be triggered and nothing ever happens.
$(function() {
$('form').submit(function(){
$("input:required", $(this)).each(function() {
if( $(this).val() != "" )
console.log($(this).attr("name"));
});
});
});
Full example here: https://jsfiddle.net/vvdh66rb/
You can also do like this:
<form action="/my/url/insert.php" method="POST" onSubmit="return myFunction()">
<div class="row">
<!--I am only giving id to one to show an exmaple you can give to differnt-->
name <input name="name" id="some" required/>
</div>
<div class="row">
type <input name="type" required/>
</div>
<div class="row">
year <input name="year" required/>
</div>
....
<div class="row">
album <input name="album" required/>
</div>
<div class="row">
<input type="submit" value="Save"/>
</div>
</form>
<script>
function myFunction() {
var x = document.getElementById('some').value;
if (x == "" || x == null) {
alert('sadsd');
return false;
//You can give anything else than alert
}
}
I am validating form with jquery. So when form submit i am using event.preventDefault(); after validate form , form will be submit to respective action page.But in my case it doesn't work.
Code what i did-
$('form[name=contact_form]').submit(function(event) {
event.preventDefault();
var formData = $('form[name=contact_form]').serialize();
var phone = $.trim($('form[name=contact_form]').find('input[name=PHONE]').val()).length;
var intRegex = /[0-9 -()+]+$/;
var alert = $('#contact_alert');
var success = $('#contact_success');
if(phone==0){
phone.focus();
alert.html("<p class='alert alert-danger' style='text-align:left;'>Phone number is required</p>");
}
else if((phone < 10)){
phone.focus();
alert.html("<p class='alert alert-danger' style='text-align:left;'>Please enter a valid phone number</p>");
return false;
}else{
return true;
}
});
Html Page :
<?php
echo form_open_multipart('home/inquiry', array('name' => 'contact_form'));
?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="hidden" name="form_type" value="C">
<input type="text" name="NAME" id="user-name" class="form-control" placeholder="Full Name"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="PHONE" id="user-phone" class="form-control" placeholder="Phone"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="EMAIL" id="user-email" class="form-control" placeholder="Email"/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="SUBJECT" id="user-subject" class="form-control" placeholder="Reason for inquiry"/>
</div>
</div>
<div class="col-md-12">
<textarea class="form-control" name="MESSAGE" id="user-message" placeholder="Message"></textarea>
</div>
<div class="col-md-12 text-left">
<div class="form-group">
<input type="submit" name="submit" class="btn btn-warning">
</div>
</div>
</div>
<?php echo form_close(); ?>
Do not call event.preventDefault(); if you want the form to be submitted after it validates ok.
Returning false after failed validation is enough.
$(this).submit();
When it's valid.
Try to replace the return true; for $(this).submit();
I usually do something like
$("#submit").submit(function(e){
if(validateFields() == true){ //If all fields are valid
$("#submit").submit();
}
else{
e.preventDefault(e);
}
});