How to make "focus" on input field on page load - javascript

When i click on input then "focus" jquery is working fine, but when i load page then "email-field" has curser, my goal is that if input has curser on page load this should be foucus and also add 'class is-focused' , which is add on input click.
PLease help me.
or if we can do this by add class on fieldset then anyone type any value in input.
// For input focused animation
$("input:text:visible:first").focus();
$(function() {
$("input:text:visible:first").focus();
// Trigger click event on click on input fields
$("form input.form-control, form textarea.form-control").on("click, change, focus", function(e) {
removeFocusClass();
// Check if is-focused class is already there or not.
if(!$(this).closest('form fieldset').hasClass('is-focused')) {
$(this).closest('form fieldset').addClass('is-focused')
}
});
// Remove the is-focused class if input does not have any value
$('form input.form-control, form textarea.form-control').each(function() {
var $input = $(this);
var $parent = $input.closest('form fieldset');
if ($input.val() && !$parent.hasClass('is-focused')) {
$parent.addClass('is-focused')
}
});
// Remove the is-focused class if input does not have any value when user clicks outside the form
$(document).on("click", function(e) {
if ($(e.target).is("form input.form-control, form textarea.form-control, form fieldset") === false) {
removeFocusClass();
}
});
function removeFocusClass() {
$('form input.form-control, form textarea.form-control').each(function() {
var $input = $(this);
if (!$input.val()) {
var $parent = $input.closest('form fieldset');
$parent.removeClass('is-focused')
}
});
}
});
fieldset.is-focused input {
border:5px solid red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form class="user-login-form">
<div class="form-head"><h2 >Sign in</h2>
<div class="description-text" ><p class="small-text" data-drupal-selector="edit-line1">Not a member yet?</p>
Register now<p class="small-text" data-drupal-selector="edit-line2"> and join the community</p>
</div>
</div>
<fieldset class="js-form-item js-form-type-textfield form-type-textfield js-form-item-name form-item-name form-group col-auto">
<input type="text" id="edit-name--MmB1Jbss54g" name="name" value="" size="60" maxlength="254" placeholder="Email address" class="form-text required form-control" required="required" aria-required="true" autofocus>
<label class="option js-form-required form-required">Email address</label>
</fieldset>
<fieldset class="js-form-item js-form-type-password form-type-password js-form-item-pass form-item-pass form-group col-auto">
<input type="password" id="edit-pass--Db3_6vLkpJQ" name="pass" size="60" maxlength="128" placeholder="Password" class="form-text required form-control" required="required">Show
<label for="edit-pass--Db3_6vLkpJQ" class="option js-form-required form-required">Password</label>
<small id="edit-pass--Db3_6vLkpJQ--description" class="description text-muted">
<p class="small-text">Forgot your password? Click here</p></small>
</fieldset>
</form>
</body>
</html>

You just need to add class in fieldset on page load. you can do with one single line code.
$("input:text:visible:first").closest('form fieldset').addClass('is-focused');
You can also refer jsfiddle url here

Related

HTML5 validation does not trigger when fields are not accesible

I have a form with multiple fields, and I need to scroll 10-15 fields until the submit button. I want to check if the form is valid or not via jquery. If the first field of my form is required and I click on the submit button the field borders are going red but the message is not displayed. If I remove all the required fields from the top and just add the last fields as required the message is displayed. If I resize the browser to be able to see the first field when press the submit the validation message is displayed. Does this function (reportValidity) work with not accessible fields?
$('form').each(function() {
var $form = $(this);
$form.find(':submit').on({
'mousedown': function(e) {
var form = $(this).closest('form')[0];
if (form.checkValidity()) {} else {
form.reportValidity();
}
},
});
});
.test {
margin-bottom: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<div class="test">
<label>Email:
<input name=email type=text required title="enter your email">
</label>
<br>
</div>
<input type=submit>
</form>
It can be solved by adding event.preventDefault() before the reportValidity() call.

jQuery form doesn't validate when button is outside of form tags

I can't seem to get my form to validate when the button is outside the <form></form> tag. Any ideas how I can achieve this? I can't place it inside the form for technical reasons (it's inside a sticky navbar).
My HTML markup:
<form id="frm-shipping" class="frm-shipping" method="post">
<input type="text" name="contact_phone" class="has_validation"
placeholder="Contact phone" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
<input type="text" name="first_name" class="has_validation"
placeholder="First Name" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
</form>
<button class="btn" onclick="nextStep();">Next</button>
And the jQuery code:
function nextStep()
{
$.validate({
form : '#frm-shipping',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
var params = $( "#frm-shipping").serialize();
// AJAX call here
}
});
}
When I click the button, nothing happens. Simply nothing :( Any suggestions?
You can assign the button to the form with form attribute. See W3Schools example.
<button class="btn" form="frm-shipping" onclick="nextStep();">Next</button>
function nextStep()
{
$.validate({
form : '#frm-shipping',
borderColorOnError:"#FF0000",
onError : function() {
console.log('error')
},
onSuccess : function() {
console.log('te3st')
var params = $( "#frm-shipping").serialize();
// AJAX call here
}
});
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="frm-shipping" class="frm-shipping" method="post">
<input type="text" name="contact_phone" class="has_validation"
placeholder="Contact phone" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
<input type="text" name="first_name" class="has_validation"
placeholder="First Name" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
</form>
<button class="btn" form='frm-shipping' onclick="nextStep();">Next</button>
Try this
$('.btn').click(function(){
Validate method
});

Additional input fields when filling up previous

Im trying to add additional fields in case when my user has filled up one group of inputs. So the idea is that when he finishes filling up the last input in that group, another group of inputs for same kind of items collapses/appears under existing one. One group of items consists of three inputs. After filling up that one, another group of inputs would appear under. I will present my code under. Hope someone can help me!
<div class="new-providers">
<div class="provider-append" id="toggleExtraProvider">
<div class="form-group">
<label>Provider</label>
<input type="text" class="form-control" id="practiceProvider" placeholder="Full provider name with coredentials" />
</div>
<div class="form-group">
<label>NPI</label>
<input type="text" class="form-control" id="providerNPI" placeholder=" NPI" />
</div>
<div class="form-group">
<label>MM #</label>
<input type="text" class="form-control" id="providerM" placeholder="M Provider #" />
</div>
<hr />
</div>
</div>
I tried appending the provider-append class on to the new-providers class
This is my jQuery script:
<script type="text/javascript">
$(document).ready(function() {
$("#toggleExtraProvider div.form-group input").each(function() {
if($(this).val() =! "") {
var target = $("new-providers");
target.append(".provider-append");
}
});
});​
</script>
You need to check for empty input box in a particular div use filter() for that
and use jQuery clone() to clone the parent div (input group) if all input box filled. And you should use change event instead of input, Since input will be overkill here it will run each time when you change a single character in text box on the other hand change event fires when user finish typing and input box loose focus.
$(document).ready(function () {
$(document).on("change",".provider-append input",function(){
var allHaveText;
var parentDiv = $(this).closest("div.provider-append");
emptyInputs=parentDiv.find("input[type=text]").filter(function () {
return !this.value;
});
if(emptyInputs.length==0)
{
newGroup = parentDiv.clone().appendTo(".new-providers");
newGroup.find("input[type=text]").each(function(){
$(this).val("");
});
}
});
});
Here is a working sample
$(document).ready(function () {
$(document).on("change",".provider-append input",function(){
var allHaveText;
var parentDiv = $(this).closest("div.provider-append");
emptyInputs=parentDiv.find("input[type=text]").filter(function () {
return !this.value;
});
if(emptyInputs.length==0)
{
newGroup = parentDiv.clone().appendTo(".new-providers");
newGroup.find("input[type=text]").each(function(){
$(this).val("");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="new-providers">
<div class="provider-append">
<div class="form-group">
<label>Provider</label>
<input type="text" class="form-control" placeholder="Full provider name with coredentials" />
</div>
<div class="form-group">
<label>NPI</label>
<input type="text" class="form-control" placeholder=" NPI" />
</div>
<div class="form-group">
<label>MM #</label>
<input type="text" class="form-control" placeholder="M Provider #" />
</div>
<hr />
</div>
</div>
I hope it will help you.

How to detect when entire form is out of focus?

I have a text form with an input field for name and an input field for email. On the mobile site, when the user clicks on a field, it is brought to the top of the viewport with the keypad below it. However, when either text field is de-selected, it gets stuck here and does not reset.
I have found the jquery focusOut event to reset the page zoom, but this fires whenever either field is not focused (ie. when the name fields is active and email is not). How can I detect when NEITHER input field is in focus?
Right now my form code is:
<form class="form-signin" action="http://" method="post" id="subForm" onsubmit="movedrop()">
<input type="text" class="form-control" id="fieldName" name="cm-name" placeholder="Full Name" tabindex=1 required>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="fieldEmail" name="cm-hjjhkh-hjjhkh" class="form-control" placeholder="Email" tabindex=2 required>
<button class="btn btn-lg btn-white btn-block subscribe" id="click-subscribe" type="submit" tabindex=3>SUBSCRIBE</button>
</form>
and my javascript:
$("form").focusout(function() {
document.body.scrollTop = 0;
console.log("focus out");
})
Which fires every time either field is deselected. I want it to fire when neither is selected.
You need to check that none of the others members have become active in the meantime. Focusout just tells you when one of the input fields loses focus.
Try the following code:
$("form").focusout(function() {
var anyActive = false;
$.each($(this).find(':input'), function(index, inputField){
if($(inputField).is(':active')){
anyActive = true;
}
});
if(anyActive){
$('#focusBox').html('One is active');
} else {
$('#focusBox').html('None is active');
}
document.body.scrollTop = 0;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-signin" action="http://" method="post" id="subForm" onsubmit="movedrop()">
<input type="text" class="form-control" id="fieldName" name="cm-name" placeholder="Full Name" tabindex=1 required>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="fieldEmail" name="cm-hjjhkh-hjjhkh" class="form-control" placeholder="Email" tabindex=2 required>
<button class="btn btn-lg btn-white btn-block subscribe" id="click-subscribe" type="submit" tabindex=3>SUBSCRIBE</button>
</form>
<div id="focusBox"></div>
I've dealt with this type of thing in the past by looking at focus events for the entire page as a whole. Essentially, I use two flags to keep track of whether or not the form 1) has focus and 2) has ever had focus. Then, I use a single handler for both click and focusin for the entire body the looks at the target of the event: if that target is inside the form, we know that the form hasn't lost focus. If not and wasFormFocused, then we know the form has lost focus: reset the flags and do whatever else is necessary (in this case, scroll to the top). This solution handles tabing out, clicking out, and also clicking on labels with the form.
var wasFormFocused = false, isFormFocused = false;
$("#theForm").focusout(function() {
isFormFocused = false;
});
var handleClickOrTab = function(event) {
if ($(event.target).parents("#theForm").length) {
wasFormFocused = true;
return;
}
if (wasFormFocused && !isFormFocused) {
wasFormFocused = false;
document.body.scrollTop = 0;
$("body").append('<br>form lost focus (scrollTop = 0)');
}
}
$("body").click(handleClickOrTab).focusin(handleClickOrTab);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="theForm" class="form-signin" action="http://" method="post" id="subForm" onsubmit="movedrop()">
<input type="text" class="form-control" id="fieldName" name="cm-name" placeholder="Full Name" tabindex=1 required>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="fieldEmail" name="cm-hjjhkh-hjjhkh" class="form-control" placeholder="Email" tabindex=2 required>
<button class="btn btn-lg btn-white btn-block subscribe" id="click-subscribe" type="submit" tabindex=3>SUBSCRIBE</button>
</form>
<h4>CLICK me (cause you can't tab to me)</h4>
<input type="text" placeholder="TAB to me or CLICK me">

three or more fields in same form - how to add/remove blank fields dynamically

I have three separate fields within the same form. I would like to have the ability to dynamically add/remove blank fields for each one.
Here's the fields and a JQuery segment - that does work for the very first field but not the others. What do I need to do? I've also tried putting the 2nd .append statement into the first one, that did not work either.
I also threw an alert into the 2nd one to see if it would trigger. It does, but the button call does not work.
If I can get the first 2 fields to work, how do I handle the third one? Like I said, the very first one works fine.
Fields
<div class="col-sm-3" id="submitterEmail">
Email<g:field type="email" name="submitterEmail" class="form-control" required="" value="" aria-labelledby="submitterEmail-label"/><button id="add">Add+</button>
</div>
<div class="col-sm-2">
Fax<g:field type="text" name="submitterFax" class="form-control" required="true" value="" aria-labelledby="submitterFax-label"/><button id="add2">Add+</button>
</div>
<div class="col-sm-5">
Specimen<g:select name="specimen" from="" class="form-control" type="text" required="true" class="form-control" aria-labelledby="specimen-label"/>
</div>
JQuery
$(document).ready(function(){
//when the Add Filed button is clicked
$("#add").click(function (e) {
//Append a new row of code to the div
$("#submitterEmail").append('<div><g:field type="email" name="submitterEmail" class="form-control" required="" value="" aria-labelledby="submitterEmail-label"/><button class="delete">Delete</button></div>');
});
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
});
$(document).ready(function(){
//when the Add Filed button is clicked
$("#add2").click(function (e) {
//Append a new row of code to the div
$("#submitterFax").append('<div><g:field type="text" name="submitterFax" class="form-control" required="" value="" aria-labelledby="submitterFax-label"/><button class="delete">Delete</button></div>');
alert('this is an alert test)
});
});
});
Try this it will work
<?php ?>// you can remove this tag.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//when the Add Filed button is clicked
$("#add").click(function (e) {
//Append a new row of code to the div
$("#submitterEmail").append('<div><input type="text" name="submitterEmail" class="form-control" required="" value="" aria-labelledby="submitterEmail-label"/><button class="delete">Delete</button></div>');
});
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
});
$(document).ready(function(){
//when the Add Filed button is clicked
$("#add2").click(function (e) {
//Append a new row of code to the div
$("#submitterFax").append('<div><input type="text" name="submitterFax" class="form-control" required="" value="" aria-labelledby="submitterFax-label"/><button class="delete">Delete</button></div>');
});
$("body").on("click", ".delete", function (e) {
$(this).parent("div").remove();
});
});
</script>
Html part.
<div class="col-sm-3" id="submitterEmail">
Email<g:field type="email" name="submitterEmail" class="form-control" required="" value="" aria-labelledby="submitterEmail-label"/><button id="add">Add+</button>
</div>
<div class="col-sm-2" id="submitterFax">
Fax<g:field type="text" name="submitterFax" class="form-control" required="true" value="" aria-labelledby="submitterFax-label"/><button id="add2">Add+</button>
</div>
<div class="col-sm-5">
Specimen<g:select name="specimen" from="" class="form-control" type="text" required="true" class="form-control" aria-labelledby="specimen-label"/>
</div>
One of my colleagues in my office also came up with this alternative fix if anyone is interested....maybe a little bit more involved perhaps, but also works nicely with some Bootstrap elements and formatting. If it helps someone (it helped me!), then I'm glad to share it.
var counter = 0;
function addContactEmail(){
$("#submitterEmailTbody").append('<tr id="submitterEmail'+counter+'Row"><td><input type="text" name="submitterEmail" class="form-control" required=""/></td><td><button type="button" class="btn btn-danger" onclick="deleteContactEmail('+counter+')" onkeypress="deleteContactEmail('+counter+'); return false"><span class="glyphicon glyphicon-minus"></span></button></td></tr>');
counter++;
}
function deleteContactEmail(id){
$("#submitterEmail"+id+"Row").remove();
}
function addContactFax(){
$("#submitterFaxTbody").append('<tr id="submitterFax'+counter+'Row"><td><input type="text" name="submitterFax" class="form-control" required=""/></td><td><button type="button" class="btn btn-danger" onclick="deleteContactFax('+counter+')" onkeypress="deleteContactFax('+counter+'); return false"><span class="glyphicon glyphicon-minus"></span></button></td></tr>');
counter++;
}
function deleteContactFax(id){
$("#submitterFax"+id+"Row").remove();
}

Categories

Resources