How to autopopulate div class form - javascript

I have an Autoresponder email form on my page.
Below is part of the code of that form, for the email to be entered by customer:
<div id = "af-form-45" class = "af-form" >
<div id = "af-body-45" class = "af-body af-standards" >
<div class = "af-element" >
<label class = "previewLabel" for = "awf_field-57" > </label>
<div class="af-textWrap">
<input class="text" id="awf_field-57" type="text" name="email" value="Form 555" tabindex="500" onfocus=" if (this.value == 'Form 555') { this.value = ''; }" onblur="if (this.value == '') { this.value='Form 555';} " / >
</div>
<div class="af-clear"> </div>
</div>
</div>
</div>
</div>
The prepopulated email value in that form is 'Form 555'. Meaning that is someone lands on the page and sees the form, it already has the value of 'Form 555'
What I need to do is to pre-populate the field not with 'Form 555', but with certain value, which I get from running a Javascript in my header (that Javascript is long, so I'm not including it here).
But for example, if I put the below code on the page, it will return a certain email address (which I need to be prepopulated in the form).
<script type="text/javascript">formData.display("email")</script>
So I need to do the same, but inside that div class form - this email address to be added instead of 'Form 555' prepopulated value
Thanks!

You can set val throu
$("#awf_field").val(formData.display("email"));

Pretty simple, is there something else you are struggling with?
Change
<script type="text/javascript">formData.display("email")</script>
to
<script type="text/javascript">
$('#awf_field').val(formData.display("email"))
</script>

Related

Bootstrap 4 form validation with Vanilla JS malfunction

I was able to create a script to validate my Bootstrap 4 form but somehow the error message is REPLACING the input field. Is there an elegant way to validate a BS4 with Vanilla JS or I should just go down the road of using Bootstrap validation? What's the best practice in the industry? It's my first time dealing with form validation.
Here's the fiddle:
https://jsfiddle.net/wunrsjdy/
HTML:
<div class="container">
<div id="form">
<h1 class="page-title">Quer Ser Nosso Cliente? Preencha o QuestionĂ¡rio Abaixo</h1>
<form id="form-user" action ="#" method="POST">
<div class="form-group" id='errorTeste'>
<label for="name">Empresa</label>
<input type="text" class="form-control" id="name" name= "name" placeholder="">
</div>
<button type="submit" class="btn btn-primary" id="button-send">Enviar</button>
</form>
</div>
JS
const name = document.getElementById('name')
const form = document.getElementById('form-user')
const errorElement = document.getElementById('errorTeste')
form.addEventListener('submit', (e) => {
let messages = []
if (name.value === '' || name.value == null) {
messages.push('Preencha o nome')
}
if (messages.length > 0) {
e.preventDefault()
errorElement.innerText = messages.join(', ')
}
})
In your fiddle, you are changing the innerText attribute of errorElement. But errorElement is also (equal to) your .form-group element:
const errorElement = document.getElementById('errorTeste')
// A little further down your html...
<div class="form-group" id='errorTeste'>
I believe that this causes your input and label elements in .form-group to be replaced by the inner text.
I feel you are on the right track, though. Try showing another element that contains a styled error/warning message when a user input is invalid using the element's style.display attribute. Maybe you tried giving the #errorTeste id to a separate error message element, but assigned it to the .form-group element by accident? Just a hunch.
Here's a decent example of how you could make it look:

Form Validation Not Resetting After Failing Validation

I'm using a small script to validate a postcode, which works and stops the user entering an invalid password, but when an invalid post code is entered you then can't submit a correct entry. For example, if I enter 'ST' I get the message telling me the postcode is invalid, so without refreshing the page manually I enter 'ST6 1SA' (which is a valid Stoke postcode) and I can't submit the form, I just keep getting the invalid tool tip advising me the post code is not in the correct format.
JS:
<script>
// Validate the postcode before it's sent
(function () {
var postcode = document.getElementById('postcode-entry');
var wrapper = document.getElementById('validation');
var notify = document.createElement('div');
var mnisLookup = document.getElementById('mnis-results');
var matchingClients = document.getElementById('matching-clients');
var postcodeWrapper = document.getElementById('postcode-wrapper');
notify.id = 'notify';
notify.style.display = 'none';
wrapper.appendChild(notify);
postcode.addEventListener('invalid', function (event) {
if (!event.target.validity.valid) {
notify.textContent = 'Please enter a valid postcode e.g. ST1, ST1 4BJ';
notify.className = 'error';
notify.style.display = 'block';
postcode.className = 'form-control invalid';
}
});
})();
</script>
HTML:
<form id="postcode-wrapper" class="form-horizontal">
<div id="postcode-lookup" class="form-group">
<label for="postcode-entry" class="col-sm-1">Postcode:</label>
<div id="postcode-entry-wrapper" class="col-sm-3">
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" />
</div>
<div class="col-sm-1">
<input id="search" type="submit" value="Search" class="btn btn-default" />
</div>
<div id="validation" class="col-sm-7"></div>
</div>
</form>
Just a quick note that may affect how the page is refreshing, this is inside an MVC Razor page and wrapped with Html.BeginForm - not sure if that makes a difference?
While debugging your code, i found that the event.target.validity.valid was returning false even if the input was valid e.g. 'ST6 1SA'. This was occuring because it does not update the custom validation for the new input and the previous state persists even after entering the valid input.
So to update and reset the previous validation, you have to reset setCustomValidity('') on input change, i.e. oninput="setCustomValidity('')"
Please replace this code:
<input type="text" pattern="^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y])))( {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2})?))$" oninvalid="setCustomValidity('Invalid Post Code Format ')" class="form-control" id="postcode-entry" placeholder="Enter your postcode" name="Postcode" oninput="setCustomValidity('')"/>

Validate only visible fields in a form

I am validating one form. when required fields are not entered it will return alert.its working fine.
Now I have hide some form fields by adding ng-class,when I click submit I don't want to validate hidden fields I want to validate only those fields which are not having hidden class.
These are my inputs:
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.name" />
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model="currentData.id"/>
</section>
<section>
<input class="required" type="text" ng-model='currentData.age'/>
</section>
<section ng-class="{'hidden':true}">
<input class="required" ng-model='currentData.gender'/>
</section>
<section>
<input class="required" ng-model='currentData.description'/>
</section>
Here am validating my fields :
$form.find('input.required').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
I have added `:visible` its working good.But that wont be a proper solution I guess.Because if there are multiple tabs which is not having `hidden class`means, it will validate only current tab user currently viewing.
$form.find('input.required:visible').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
Any other suggestions?
$('form').find('input.required').parent('*:not(".hidden")').each(function() {
var $this = $(this)
if ($this.val().trim() == '') {
alert("enter required fields")
}
})
assuming $('form') is <form></form>,
otherwise it should be something like
$('#form') for <div id="form"></div>
Got solution:
$form.find('section').not(".hidden").closest('input.required').each(function() {})
I just changed my elements order.

Printing text next to a form field in JavaScript

I'm having a bit of trouble with this assigment and would like your help.
We are meant to create a product registration form page with all the regular expressions and everything and display the correct error when the regexes don't match.
I am trying to print a tick or say OK next to a form field but I can't get the right function. My form right now looks like this: http://www.imageurlhost.com/images/98zrdmrmsvbxnwowrvsf.png
The "Please enter product ...." is activated by jquery with a slideUp and slideDown function with onblur on the text field.
So I want to display OK where the red circle is after you click away from it, and then if you change it to something that doesn't match the OK disappears and my alert shows up. So this is my code so far:
My html form:
<div>
<input type="text" class="name" placeholder="Name" name="name" onblur="return validateProductName()"> <p class ="p11" id="p1"></p>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
My css:
.p11 {
float: right;}
My jQuery:
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
});
And then my JavaScript:
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
So, it prints the OK in between the field on the right side, but I want it right next to the field like I showed in the picture and I can't get this to work! I want it to disappear if I go back to the form and put something wrong...
Thanks guys!
I assume, you have no problem with the jQuery itself, you have a problem of showing it next to input box. So,
Create a <span id='tick'> tag after the input field
And once it passes the validation, use jquery to show the tick
$('#tick').html('whatever you want');
EDIT: You dont have to include the float:left on span
Check out the fiddle link
EDIT:
In this validation function, just show and hide according to the validation results
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.myForm.name.value.trim().search(pName) == -1) {
document.getElementById("tick").style.display = 'none'; // to hide the OK text if enterd the wrong input
} else {
document.getElementById("tick").innerHTML = "OK"; //NOTE: This is for showing the ok text
document.getElementById("tick").style.display= "block";
}
}
Create a span wherever you want your tick to be displayed and they do this,
$("#btn").click(function() {
if ($("#txtname").val() == "") //can be any check
{
$("#g").attr("style", "display:block;width:20px");
} else {
$("#g").attr("style", "display:none;width:20px;");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="txtname" style="display:inline-block" placeholder="enter name" />
<img id="g" style="width:50px;display:none;" src="http://pixabay.com/static/uploads/photo/2014/04/02/10/19/check-303494_640.png" />
<br/>
<input type="button" id="btn" value="click to submit" />
This should work-
<script src="jq.js"></script>
<div>
<input type="text" class="name" placeholder="Name" name="name" id="input"> <span class ="p11" id="p1"></span>
<p class="name-help">Please enter a product name between 1-50 characters.</p>
</div>
<style>
p11 {
float: right;}
</style>
<script>
$(".name").focus(function(){
$(".name-help").slideDown(500);
}).blur(function(){
$(".name-help").slideUp(500);
validateProductName()
});
</script>
<script>
// Function to validate product name
function validateProductName() {
// if statement for product name
if (document.getElementById("input").value.trim() == "" || document.getElementById("input").value.length > 50 ) {
alert("Invalid product name. Please note: product name should have 1-50 characters.");
document.getElementById("p1").innerHTML = "";
} else {
document.getElementById("p1").innerHTML = "OK";
}
}
</script>

How to perform validation in multiple groups of inputs according to condition

I am creating a set of textboxes dynamically while pressing (+) button, by cloning the following HTML template:
<div id= "other_leaders" class="controls form-input">
<input type="text" name="other_leader_fname[]" class="input_bottom other_leader_fname" id="other_leader_fname" placeholder="First Name" value="'.$val[0].'" />
<input type="text" name="other_leader_lname[]" class="input_bottom other_leader_lname" id="other_leader_lname" placeholder="Last Name" value="'.$val[1].'" />
<input type="text" name="other_leader_email[]" class="other_leader_email" id="other_leader_email" placeholder="Email Address" value="'.$val[2].'" />
<input type="text" name="other_leader_org[]" class="other_leader_org" id="other_leader_org" placeholder="Organisation/College" value="'.$val[3].'" />
<span class="remove btn"><i class="icon-minus"></i></span>
</div>
I am able to do single textbox validation by following code:
$("input[name*='other_leader_fname']").each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
});
Now my question is how to do empty validation for all four textboxes, if any one textbox field is filled by the user in that particular textbox group.
for example: if i enter values in the <div> with id other_leader_fname, then it should perform empty validation for other three textboxes of this particular group.
how can i do it?
Try this , You can apply your validation rules to all the text box in the div by using following code:
$("#other_leaders :input[type='text']").each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
});
As you have just one element so there is no need to have a loop over it:
var $othLeader = $("input[name*='other_leader_fname']");
if($othLeader.val()=="" || !RegExpression.test($othLeader.val())){
$(this).addClass('custom-error');
fnameflag = 0;
}
And if you have form then you can validate this in your form's submit function.
You can iterate over the .controls using the each() and check for filled inputs in each group using filter for performing the validation as follows:
$('.controls').each(function(){
var $inputs = $(this).find('input');
var filled = $inputs.filter(function(){
return this.value != "";
});
if(filled.length){
$inputs.each(function(){
if($(this).val()=="" || !RegExpression.test($(this).val()))
{
$(this).addClass('custom-error')
fnameflag = 0;
}
})
}
});
Demo
side note: since the above is a template for dynamically generated content, You should remove the id and use class instead since id should be unique in a document.

Categories