Additional input fields when filling up previous - javascript

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.

Related

Form validation on blur

I have 5 input fields and I want them to validate on blur, and show either an error or success message, but through DOM scripting and not with an alert box. I've tried several different codes, even just small bits and pieces to see if it's correctly interacting with my html but it doesn't seem to work.
So far, I have a small code to test if it even runs, and it's supposed to show an alert box but it does not. I would prefer to not use any innerHTML and use all functions within the javascript only.
My html:
<div id=fNID>
<label for="firstNameID">First Name: </label>
<input id="firstNameID" type="text" name="firstNameA" value="" />
<span> </span>
</div>
<div id=lNID>
<label for="lastNameID">Last Name: </label>
<input id="lastNameID" type="text" name="lastNameA" value="" />
<span> </span>
</div>
My javascript:
firstNameID = document.surveyForm.getElementById("firstNameID");
document.surveyForm.getElementById(fN).addEventListener("blur", validateName);
function validateName() {
var nameRegEx = /[a-zA-Z]+/;
var firstNameID = document.getElementById("firstNameID");
if (fN.matches(nameRegEx)) {
alert("Success!")
} else {
alert("error")
}
}
window.addEventListener("load", setupForm, false);
}
Bootstrap has a nice pattern for input validation. They use divs following the input: one for valid input, one for invalid input, making the appropriate one visible:
<div class="form-group">
<label for="uname">Username:</label>
<input class="form-control" id="uname">
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">Please fill out this field.</div>
</div>
Bootstrap's CSS classes modify the display based on the input's pseudo-classes :valid and :invalid.
You can set these pseudo-classes in JavaScript with the setCustomValidity() method.
input.setCustomValidity("input is invalid")
will assign the :invalid pseudo-class to the input.
input.setCustomValidity("")
will assign the :valid pseudo class.
A working example:
const input = document.getElementById('uname');
function makeValid() {
input.setCustomValidity('');
}
function makeInvalid() {
input.setCustomValidity('a problem');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<h3 class="m-2">Bootstrap input with validation</h3>
<form class="was-validated mx-2">
<div class="form-group">
<label for="uname">Username (required):</label>
<input type="text" class="form-control" id="uname" placeholder="Enter username" name="uname">
<div class="valid-feedback">Valid.</div>
<div class="invalid-feedback">This field is invalid.</div>
</div>
</form>
<div class="m-2">
<p>Use setCustomValidity() to change input state:</p>
<button onclick="makeValid();">:valid</button>
<button onclick="makeInvalid();">:invalid</button>
</div>
It's also worth noting that most browsers have native support for displaying validation messages on inputs. Here's an example that doesn't use any Bootstrap features:
const input = document.getElementById('uname');
function makeValid() {
input.setCustomValidity('');
}
function makeInvalid() {
input.setCustomValidity('this is invalid');
}
body {
background-color: #aaa;
}
.m-2 {
margin: .5rem;
}
.mt-5 {
margin-top: 1rem;
}
<body>
<h3 class="m-2">Generic input with validation</h3>
<form class="mt-5">
<label for="uname">Username:</label>
<input type="text" id="uname" placeholder="Enter username" name="uname">
<p>Use setCustomValidity() to change input state:</p>
<button onclick="makeInvalid();">input:invalid</button>
</form>
<div class="m-2">
<button onclick="makeValid();">input:valid</button>
</div>
</body>

How can I set cursor into html text input field?

For a Flask app I am trying to set the cursor into an input text field in a form. The form looks like this:
<form method="get" autocomplete="off">
<div class="row">
<div class="four columns">
<label for="from-currency">Exchange:</label>
<input type="text" placeholder="currency to exchange from" value="{{ from_curr }}" name="from_currency" id="from-currency" class="input-field"/>
</div>
<div class="four columns">
<label for="to-currency">To:</label>
<input type="text" placeholder="currency to exchange to" value="{{ to_curr }}" name="to_currency" id="to-currency" class="input-field"/>
</div>
<div class="four columns">
<label for="calculate-button"> </label>
<input type="submit" value="Calculate" id="calculate-button" class="input-field">
</div>
</div>
</form>
I tried using JavaScript (element.focus();), but it did not move the cursor into my input field.
<script>
function submit_param(inp) {
inp.addEventListener("input", function(event) {
var val = this.value;
var urlParams = new URLSearchParams(window.location.search);
urlParams.set(inp.name, val);
var queryString = urlParams.toString();
history.pushState({}, "", "?"+queryString);
location.reload();
inp.focus();
});
}
submit_param(document.getElementById("from-currency"));
submit_param(document.getElementById("to-currency"));
</script>
What am I doing wrong, or how else can I move the cursor back into the input filed at the end of my script block?
How can I set cursor into html text input field?
<input type="text" autofocus>
The autofocus attribute is a boolean attribute.
When present, it specifies that an element should automatically get focus when the page loads.
Hope this helps. Good luck.

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

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

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

Jquery keypress to validate email inputs

What I'd like to accomplish is this:
If a user types in a valid email, display the (.check)'ok' sign. If not valid, display nothing(for the time being. I'll put something in later).
I have 3 email fields. I'm trying to 'validate' for each one.
<form id="emailsForm" method="POST" action="/account/recommend/">
<div class="prepend">
<p><strong>Emails:</strong></p>
<div>
<span class="added"><p class="check">ok</p></span>
<input type="email" id="email1" class="input-text" onblur="alert(/([A-Z0-9a-z_-][^#])+?#[^$#<>?]+?\.[\w]{2,4}/.test(this.value))">
</div>
<div>
<span class="added"><p class="check">ok</p></span>
<input type="email" id="email2" class="input-text">
</div>
<div>
<span class="added"><p class="check">ok</p></span>
<input type="email" id="email3" class="input-text">
</div>
<button type="submit" class="submit">Send</button>
</div>
</form>
$("form#emailsForm :input").each(function(){
$('input').blur(function() {
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
if (testEmail.test(this.value)){
$('input').siblings(".check").css('visibility', 'visible');
}
else {
}
});
});
http://jsfiddle.net/RFcaN/23/ What am I doing wrong?
Thanks for your help and suggestions!
First off you need to find the sibling of this input, so change your selector from $('input') to $(this).
Secondly, .check is not a sibling of the input. It's a descendant of the sibling.
$(this).siblings(".added").find('.check').css('visibility', 'visible');

Categories

Resources