I have a zipcode checker which posts using ajax after the length of an input field is equal to 6. This works, except the ajax is posted twice. Why is that? I am using an api which has 1000 calls each month, so this behaviour already cuts that in half.
Maybe it would make sense to me that because of some bug it fires again when typing a 7th character, but that is not even the case, when I type exactly 6 characters the ajax is fired twice.
$("body").on("keyup", "#billing_postcode", function() {
var value = $(this).val();
var housenumber = $("#billing_streetnumber").val();
if (housenumber.length >= 1) {
if (value.length == 6) {
url = 'catalog/postcodecheck.php';
var $postcode = $('#billing_postcode').val();
var $huisnummer = $('#billing_streetnumber').val();
var posting = $.post(url, {
postcode: $postcode,
huisnummer: $huisnummer
});
posting.done(function(data) {
var content = $($.parseHTML(data));
$("#postcoderesult").empty().append(content);
});
} else {
}
} else {
alert('Vul eerst je huisnummer in voor dat je verder kan.');
$("#billing_postcode").val('');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-3">
<p class="single-form-row">
<label>Huisnummer <span class="required">*</span></label>
<input type="text" name="billing_streetnumber" id="billing_streetnumber" required>
</p>
</div>
<div class="col-lg-4">
<p class="single-form-row">
<label>Toevoeging (optioneel)</label>
<input type="text" name="billing_streetextra" id="billing_streetextra">
</p>
</div>
<div class="col-lg-5">
<p class="single-form-row">
<label>Postcode<span class="required">*</span></label>
<input type="text" name="billing_postcode" id="billing_postcode" required>
</p>
</div>
<div id="postcoderesult" class="col-lg-12">
<div class="row">
<div class="col-lg-6">
<p class="single-form-row">
<label>Straatnaam <span class="required">*</span></label>
<input type="text" name="billing_street" id="billing_street" disabled required>
</p>
</div>
<div class="col-lg-6">
<p class="single-form-row">
<label>Stad<span class="required">*</span></label>
<input type="text" name="billing_city" id="billing_city" disabled required>
</p>
</div>
</div>
</div>
Related
In the form I am making, there is a section that requires users to enter the amount of people in their family. After they provide it, the form generates enough input fields so that the user can enter information for each family member.
What I am having trouble with is none of the attributes that I am trying to apply to the input element actually work.
function addHouseMembers(that){
var family = document.getElementById("family-input-container");
while(family.hasChildNodes()){
family.removeChild(family.lastChild);
}
for(var i = 1; i < that.value; i++){
family.appendChild(document.createTextNode("Family Member " + (i+1)));
family.appendChild(document.createElement("br"));
//name
family.appendChild(document.createTextNode("Name: " ));
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i + "_name";
input.pattern = "/^[a-zA-Z ]*$/";
input.required = true;
family.appendChild(input);
family.appendChild(document.createElement("br"));
}
}
The parameter that refers to the input where the user would put in the number of people in their family.
And here is the relevant HTML:
<form>
<div class="form-group">
<label class="col-lg-3 control-label">What is the total amount of people living in your household?</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group">
<input type="text" class="form-control" name="household-size" required onchange="addHouseMembers(this);"/>
</div>
</div>
</div>
<div class="form-group", id="family-info">
<label class="col-lg-12">Information for other Family Members</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group" id = "family-input-container" required>
</div>
</div>
</div>
</form>
The element shows up as it should, and is submitted with the form when the user hits the submit button, but the regex pattern and required attributes are not enforced.
in addHouseMembers(that) the value of that is a string, not a number, and you have to check if is value can be 'translated' in an integer value.
use the "onchange" event on the input field household-size is not a good idea because this event is triggered each time a digit of the number entered, which has the effect of erasing and completely rewrite the family-input-container part
I Imagine you are looking for something like that ?
const myForm = document.getElementById('my-form')
, familyElm = document.getElementById('family-input-container')
, parserDOM = new DOMParser()
;
function newHouseMember(ref)
{
let div=
` <div>
Family Member ${ref}<br>Name: <br>
<input type="text" name="member${ref}_name" pattern="/^[a-zA-Z ]*$/" required >
</div>`
return parserDOM.parseFromString( div, 'text/html').body.firstChild
}
myForm.btPeoples.onclick=_=>
{
let nbPeoples = parseInt(myForm['household-size'].value)
if (!isNaN(nbPeoples) && nbPeoples > 0 )
{
familyElm.innerHTML = ''
for (let i=1; i<=nbPeoples; i++)
{
familyElm.appendChild( newHouseMember(i) )
}
}
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" >
<form id="my-form">
<div class="form-group">
<label class="col-lg-3 control-label">What is the total amount of people living in your household?</label>
<div class="col-lg-3 inputGroupContainer">
<div class = "input-group">
<input class="form-control" name="household-size" required value="" placeholder="number of peoples" pattern="\d*" />
<button name="btPeoples" class="btn btn-info" type="button" >check it!</button>
</div>
</div>
</div>
<div class="form-group", id="family-info">
<label class="col-lg-12">Information for other Family Members</label>
<div class="col-lg-3 inputGroupContainer">
<div class="input-group" id="family-input-container">
</div>
</div>
</div>
</form>
I wrote a code to add dinamically elements in a form with js. when i submit data, action page says that index of this element are undefined
I have this form:
<form action="testRicetta.php" method= "POST" >
[...]
<ul id ="passi" >
<li id ="li_passo0">
<div class="row">
<div class="col-25">
<label for="descrizione">Passo 0</label>
</div>
<div class="col-75">
<textarea id="passo0" name="passo0" placeholder="Descrivi
il passo" style="height:100px" required ></textarea>
<input type="file" id="immagine_0" name="immagine" >
</div>
</div>
</li>
</ul>
<button id="addMore" >Aggiungi passo</button>
This is the js code where appear the listener of button #addMore
var passi = 1;
$(function() {
$("#addMore").click(function(e)
{
e.preventDefault();
$("#passi").append(`<li id ="li_passo"`+passi+`>
<div class="row">
<div class="col-25">
<label for="passo"`+passi+`>Passo `+passi+`</label>
</div>
<div class="col-75">
<textarea id="passo"`+passi+` name="passo"`+passi+`
placeholder="Descrivi il passo" style="height:100px"
required ></textarea>
<input type="file" id="immagine_"`+passi+`
name="immagine" >
</div>
</div>
</li>`);
passi++;
},
$('.sel').chosen());
})
action page:
echo $_POST{passo0];
echo $_POST{passo1];
Result:
Notice: Undefined index: passo1
Furthermore, is possibile read data in a loop? i tried this
for($i = 0; isset($_POST['passo'+$i]);$i++)
echo $_POST['passo'+$i];
but i get this error:
Warning: A non-numeric value encountered in (the loop)
So how can i read this data, and how can do it with a loop?
When your adding the new field, you are concatenating the passi variable value outside the of name name="passo"'+passi+', it should be name="passo'+passi+'".
Try:
var passi = 1;
$(function() {
$("#addMore").click(function(e)
{
e.preventDefault();
$("#passi").append('<li id ="li_passo"'+passi+'>
<div class="row">
<div class="col-25">
<label for="passo"'+passi+'>Passo '+passi+'</label>
</div>
<div class="col-75">
<textarea id="passo"'+passi+' name="passo'+passi+'"
placeholder="Descrivi il passo" style="height:100px"
required ></textarea>
<input type="file" id="immagine_"'+passi+'
name="immagine" >
</div>
</div>
</li>');
passi++;
},
$('.sel').chosen());
})
And then:
echo $_POST[passo0];
echo $_POST[passo1];
I want to apply required field validation on text box group in which at least one text box group must contain value.
in bellow image, details of at least one bank must be filled.
I have used jquery-form-validator plugin from http://www.formvalidator.net/#custom-validators and created custome validator as bellow, but Its not working.
$("#txtBankDetails")
.valAttr('error-msg', 'select atlest 1 bankname.');
$.formUtils.addValidator({
name: 'data-text-group',
validatorFunction: function (value, $el, config, language, $form) {
debugger
var isValid = true,
// get name of element. since it is a checkbox group, all checkboxes will have same name
elname = $el.attr('data-text-group'),
// get checkboxes and count the checked ones
$textBoxes = $('input[type=textbox][data-text-group^="' + elname + '"]', $form),
nonEmptyCount = $textBoxes.filter(function () {
return !!this.value;
}).length;
alert(nonEmptyCount);
if (nonEmptyCount == 0) {
isValid = false;
}
}
});
// Setup form validation only on the form having id "registration"
$.validate({
form: '#registration',
modules: 'date, security, file, logic',
validateOnBlur: true,
showHelpOnFocus: true,
addSuggestions: true,
onModulesLoaded: function () {
console.log('All modules loaded!');
},
onSuccess: function ($form) {
form.submit();
alert("sucess")
return false;
},
onError: function () {
alert("Error")
}
});
html code is,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/theme-default.min.css"
rel="stylesheet" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="registration" method="post" action="#Url.Action("NewRegistration", "StaticPage")" enctype="multipart/form-data" class='has-validation-callback'>
<div class="container">
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname1" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankACNo1" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input class="nwresmainfild" name="BankAddress1" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname2" data-text-group="BankName" placeholder="01. BANK NAME" data-validation-error-msg="select atlest 1 bankname.">
</div>
<div class="col-md-4">
<input name="BankACNo2" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress2" placeholder="BANK ADDRESS">
</div>
</div>
<div class="row">
<div class="col-md-4">
<input id="txtBankDetails" name="Bankname3" data-text-group="BankName" placeholder="03. BANK NAME" >
</div>
<div class="col-md-4">
<input name="BankACNo3" placeholder="BANK A/C NO.">
</div>
<div class="col-md-4">
<input name="BankAddress3" placeholder="BANK ADDRESS">
</div>
</div>
</div>
<input value="PROCESS & PRINT" class="green-btn uppercase" type="submit" id="btnSubmit" />
</form>
I have tried many ways but when submit button is clicked it directly moves to next page without validating in client side through javascript. Please provide me the solution to this problem.
Here is the code:
function teacherValidateForm(){
var tuid=document.getElementById("tusername");
var tnme=document.getElementById("tname");
var tmail=document.getElementById("temail");
var tpsd=document.getElementById("tpssswod");
var tiname=document.getElementById("tiname");
function validateTID(tuid){
var message= "Username must start with a letter and must be of minimum 5 letters and '_' and '.' is allowed";
if((!tuid.match(/^[[A-Za-z][A-Za-z0-9/._]*]{5,}$/)) || tuid.value==""){
document.getElementById(uname).innerHTML=message;
return false;
}
else return true;
}
function validateTName(){
var message="Teacher's name muct not contain special characters and numbers";
if((!tnme.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value==""){
document.getElementById(name).innerHTML=message;
return false;
}else return true;
}
function validateTEmail(){
var message="Enter a valid email";
if((!tmail.match(/^[A-Za-z\._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}*$/) || tmail.value==""){
document.getElementById(email).innerHTML=message;
return false;
}else return true;
}
function validateTPass(){
var message="Password must contain special cahacters, one catital letter atleast and must be mininum 8 letters";
if((!tpsd.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/) || tpsd.value==""){
document.getElementById(password).innerHTML=message;
return false;
}else return true;
}
function validateTName(){
var message="Institute's name muct not contain special characters and numbers";
if((!tiname.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value==""){
document.getElementById(iname).innerHTML=message;
return false;
}else return true;
}
}
<body>
<div class="container-fluid" id="home">
<div class="text-center ">
<p></p><br/><br/><br/><br/>
<div class="container-fluid text-center">
<h4 style="font-family:sans-serif; color: #000; size: 60px; font-weight: bold">Registration form</h4></div>
</div>
<form name="teachersignup" class="form-horizontal" action="teacherLogin.jsp" method="POST">
<div class="form-group">
<label class="control-label col-md-4" style="color:#000; font-size:15px" >User Name: </label>
<div class="col-md-4">
<input type="text" class="form-control" id="tusername" /> <span class="error" id="uname"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" style="color:#000; font-size:15px" >Teacher's Name: </label>
<div class="col-md-4">
<input type="text" class="form-control" id="tname" /> <span class="error" id="name" ></span>
</div>
</div>
<div class="form-group">
<label for="email" class="control-label col-md-4" style="color:#000; font-size:15px" >Email: </label>
<div class="col-md-4">
<input type="email" class="form-control" id="temail" /> <span class="error" id="email"></span>
</div>
</div>
<div class="form-group">
<label for="pswd" class="control-label col-md-4" style="color:#000; font-size:15px" >Password: </label>
<div class="col-md-4">
<input type="password" class="form-control" id="tpassword" /> <span class="error" id="password"></span>
</div>
</div>
<div class="form-group">
<label for="iname" class="control-label col-md-4" style="color:#000; font-size:15px" >Institute's Name: </label>
<div class="col-md-4">
<input type="text" class="form-control" id="tiname" /> <span class="error" id="iname"></span>
</div>
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-success" onsubmit="teacherValidateForm();">Submit</button>
</div>
</form>
</div>
</body>
You have several errors there. first you have to return value from the function in the html markup:
Firstly use <form name="teachersignup" class="form-horizontal" action="teacherLogin.jsp" method="POST" onsubmit="return teacherValidateForm();>
Then you can try the below function.Assuming that all your regular expressions are correct the below function should work just fine.
function teacherValidateForm()
{
var tuid=document.getElementById("tusername");
var tnme=document.getElementById("tname");
var tmail=document.getElementById("temail");
var tpsd=document.getElementById("tpssswod");
var tiname=document.getElementById("tiname");
if(!tuid.match(/^[[A-Za-z][A-Za-z0-9/._]*]{5,}$/) || tuid.value=="")
{
var message= "Username must start with a letter and must be of minimum 5 letters and '_' and '.' is allowed";
document.getElementById(uname).innerHTML=message;
return false;
}
if(!tnme.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value=="")
{
var message="Teacher's name muct not contain special characters and numbers";
document.getElementById(name).innerHTML=message;
return false;
}
if(!tmail.match(/^[A-Za-z\._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}*$/) || tmail.value=="")
{
var message="Enter a valid email";
document.getElementById(email).innerHTML=message;
return false;
}
if(!tpsd.match(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/) || tpsd.value=="")
{
var message="Password must contain special cahacters, one catital letter atleast and must be mininum 8 letters";
document.getElementById(password).innerHTML=message;
return false;
}
if(!tiname.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/) || tnme.value=="")
{
var message="Institute's name muct not contain special characters and numbers";
document.getElementById(iname).innerHTML=message;
return false;
}
return true;
}
You are doing wrong.
var tuid=document.getElementById("tusername");
var tnme=document.getElementById("tname");
var tmail=document.getElementById("temail");
var tpsd=document.getElementById("tpssswod");
var tiname=document.getElementById("tiname");
Actually you are assigning those variable with the HTML input elements, but you need the values. So made some changes in these codes
var tuid=document.getElementById("tusername").value;
var tnme=document.getElementById("tname").value;
var tmail=document.getElementById("temail").value;
var tpsd=document.getElementById("tpssswod").value;
var tiname=document.getElementById("tiname").value;
I have a question like so.
I have HTML structure:
<form id="form">
<div class="row">
<div class="item-input">
<label for="A1">A1</label>
<input type="text" name ="A1" />
<span class="input-require">(*)</span>
<span class="info">(Enter A1)</span>
</div>
<div class="item-input">
<label for="A2">A2</label>
<input type="text" name ="A2" />
<span class="input-require">(*)</span>
<span class="info">(Enter A2)</span>
</div>
</div>
<div class="row">
<div class="item-input">
<label for="B1">B1</label>
<input type="text" name ="B1" />
<span class="input-require">(*)</span>
<span class="info">(Enter B1)</span>
</div>
<div class="item-input">
<label for="B2">B2</label>
<input type="text" name ="B2" />
<span class="input-require">(*)</span>
<span class="info">(Enter B2)</span>
</div>
</div>
...
</form>
Now I want to selected 'span' has class "info" behind input[type=text] each.
I try:
<script type="text/javascript">
$(document).ready(function() {
$("#form input[type=text]").each(function(){
var spanInfo = $(this).closest("item-input").next().find('span.info');
console.log(spanInfo.text()); // Result is empty
});
});
</script>
Why is empty? Help me please. How do I, thanks
var spanInfo = $(this).closest("item-input").next().find('span.info');
Should be
var spanInfo = $(this).closest(".item-input").next().find('span.info');
You are missing the . (dot, class)
Your mean is show "(Enter A2)" and "(Enter B2)" or show all 4 element value: (Enter A1), (Enter A2), (Enter B1), (Enter B2)
If only show 2 value then CODE HERE
else You want to show 4 value, you can code:
$(document).ready(function() {
$("#form input[type=text]").each(function(){
var spanInfo = $(this).closest(".item-input").find('span.info');
console.log(spanInfo.text());
});
});