Focus event not working in HTML form - javascript

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>

Related

How to check all the form fields were given to enable the submit button?

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>

Error message in contact form

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 = '';
});

Detect the name of required field and not validated when submit a 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
}
}

How to submit form if validate using jquery?

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);
}
});

jQuery's val() returns empty string on bootstrap popover input field

I have a bootstrap popup form with a few input fields. I've added a submit button to the form, that triggers client-side JS validation. However, when the button is clicked, the current value of the input fields is not captured by jQuery's val() method: I just get an empty string.
Here is the markup:
<div class="popover fade right in" style="top: -154.5px; left: 249px; display: block;">
<div class="arrow">
</div>
<h3 class="popover-title">New Job Site contact</h3>
<div class="popover-content">
<form class="popover-form form-horizontal" id="newjobsite_contact_form" accept-charset="utf-8" method="post" action="http://dev.temperature/home/#">
<div class="form-group">
<div class=" required ">
<input type="text" class="form-control" id="popover-first_name" required="1" placeholder="First name" value="" name="first_name">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
</div>
<div class=" required ">
<input type="text" class="form-control" required="1" placeholder="Phone" value="" name="phone">
</div>
<div class="">
<input type="text" class="form-control" placeholder="Mobile" value="" name="mobile">
</div>
<div class="">
<input type="email" class="form-control" placeholder="Email" value="" name="email">
</div>
<div class="">
<input type="url" class="form-control" placeholder="Website" value="" name="website">
</div>
</div>
<div class="popover_buttons">
<button class="btn btn-success" onclick="submit_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_submit">Submit</button>
<button class="btn btn-warning" onclick="close_newjobsite_contact(); return false;" type="button" id="newjobsite_contact_cancel">Cancel</button>
</div>
</form>
</div>
</div>
Here is the JS:
function submit_newjobsite_contact() {
errors_found = validate_popover_form($('#newjobsite_contact_form'));
if (errors_found.length == 0) {
// Form values submitted to PHP code through AJAX request here
} else {
error_msg = "Please check the following errors:\n";
$(errors_found).each(function(key, item) {
error_msg += "- "+item.message+"\n";
});
alert(error_msg);
}
}
function validate_popover_form(form_element) {
found_errors = [];
$('span.error').remove();
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
console.log($(item).val()); // More validation here, just putting debugging code instead
});
return found_errors;
}
What am I doing wrong? All other attributes for these input fields are being correctly retrieved by jQuery, just not the value after I've typed text into them.
The answer to this problem couldn't be found here because I didn't post the whole source JS, which is too large. What really happened is that I accidentally cloned the popover form, which led to a duplication of the input fields.
form_element.find('select,input').each(function(key, item) {
if ($(item).attr('required') && $(item).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(item).attr('name'), message: "A value for "+$(item).attr('placeholder')+" is required"});
}
I Modified it to:
form_element.find('select,input').each(function(key, item) {
if ($(this).data('required') == '1' && $(this).val().length == 0) {
found_error = true;
found_errors.push({elementname: $(this).attr('name'), message: "A value for "+$(this).attr('placeholder')+" is required"});
}
Try using data attributes so instead of using required="1" use data-required="1"
<input type="text" class="form-control" required="1" placeholder="Surname" value="" name="surname">
so your input should be like this:
<input type="text" class="form-control" data-required="1" placeholder="Surname" value="" name="surname">

Categories