I have a row in my form for a user to enter a 6 digit unique ref. This is split up into 3 fields which each only allow 2 characters. What i'm after is that when the user has entered 2 characters, I want the focus to automatically move to the next field.
The functionality though also needs to support the use of tab back in case the user has entered an incorrect digit so they don't need to manually click in the field.
HTML
<div class="col-sm-5 form-inline">
<input name="RefBox1" type="text" class="form-control" id="RefBox1" style="width: 40px;" type="text" maxlength="2" ng-model="updateRef1" restrictinput="[^0-9\s]" required> -
<input name="RefBox2" type="text" class="form-control" id="RefBox2" style="width: 40px;" type="text" maxlength="2" ng-model="updateRef2" restrictinput="[^0-9\s]" required> -
<input name="RefBox3" type="text" class="form-control" id="RefBox3" style="width: 40px;" type="text" maxlength="2" ng-model="updateRef3" restrictinput="[^0-9\s]" required>
</div>
As I don't know how to do this I don't have any code in my controller.
This method of moving to the nextElementSibling on maxLength works with plain-old-javascript. I'm guessing that you could adapted it to your AngularJS controller. And to support older browsers (IE<9) see: Portability of nextElementSibling/nextSibling
<html>
<body>
<input onKeyup="autoTab(this)" maxlength=2>
<input onKeyup="autoTab(this)" maxlength=2>
<input onKeyup="autoTab(this)" maxlength=2>
<script type="text/javascript">
function autoTab( obj ) {
if ( obj.value.length >= obj.maxLength && obj.nextElementSibling )
obj.nextElementSibling.focus();
}
</script>
</body>
</html>
Related
The problem
I use a form on a webpage where users fill in all sorts of details. There are 3 fields which generate the input for another field. That field gets generated like this: Firstname + Lastname + Date of birth. However, when a validation error is thrown on the form and the page reloads, the generated input isn't the expected format anymore. Only the Date of birth is then in that input.
It looks like it isn't initializing the Firstname + Lastname field anymore after a validation error is thrown on the page. Any suggestions on how to make it so that the fields gets initialized constantly? Or is there maybe a better way to handle this?
This is the code I use for the generated input
window.onload = function() {
let studentNoField = document.getElementById('input_7_9');
let enteredDetails = {
name: '',
lastname: '',
date: ''
};
/* set value in the third input: Studentnummer */
function generateInput() {
let studentNumber = Object.values(enteredDetails).join('').toLowerCase();
studentNoField.value = studentNumber;
}
/* event listener for first input: Voornaam */
document.getElementById('input_7_1').addEventListener('input', function(event) {
enteredDetails.name = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Achternaam */
document.getElementById('input_7_25').addEventListener('input', function(event) {
enteredDetails.lastname = event.target.value.replace(/\s/g, '').slice(0, 8);
generateInput();
});
/* event listener for second input: Date */
document.getElementById('input_7_3').addEventListener('input', function(event) {
enteredDetails.date = event.target.value.replace(/-/g, '').slice(0, 4);
generateInput();
});
/* Get selected training and format it properly for the PDF */
jQuery('#input_7_23').change(function(e) {
var optionChange = jQuery('#input_7_23 option:selected').text().toUpperCase();
jQuery('#input_7_58').val(optionChange);
});
}
<html>
<body>
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen" onclick="if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; " onkeypress="if( event.keyCode == 13 ){ if(window["gf_submitting_7"]){return false;} window["gf_submitting_7"]=true; jQuery("#gform_7").trigger("submit",[true]); }">
</div>
</form>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Any help or suggestions is appreciated.
There were a few non-existing ids referenced in your code. In the following snippet I have tried to "correct" these errors, but I also went further: I removed all repetitions, thereby following the DRY principle "Don't repeat yourself". The "input"-event listener now works for all elements of the inps array. There is, however one differentiation: the first two elements are limited to 8 characters while the date is limited to 4: .slice(0,i<2?8:4).
const [stNr, ...inps]=[9, 1, 25, 3].map(n=> document.getElementById(`input_7_${n}`));
inps.forEach(inp=>inp.addEventListener("input",()=>
stNr.value=inps.map((el,i)=>
el.value.replace(/[\s-]/g,"").slice(0,i<2?8:4).toLowerCase()
).join(""))
)
<form method="post" enctype="multipart/form-data" id="gform_7" action="/budget/" _lpchecked="1">
<div>
<div id="gform_fields_7">
<div id="field_7_9">
<label for="input_7_9">Studentnummer</label>
<input name="input_9" id="input_7_9" type="text" value="" maxlength="20" aria-required="true" aria-invalid="false">
</div>
</div>
<div id="field_7_1">
<label for="input_7_1">Voornaam</label>
<div><input name="input_1" id="input_7_1" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_25">
<label for="input_7_25">Achternaam</label>
<div><input name="input_25" id="input_7_25" type="text" value="" aria-required="true" aria-invalid="false"> </div>
</div>
<div id="field_7_3">
<label for="input_7_3">Geboortedatum</label>
<div>
<input name="input_3" id="input_7_3" type="text" value="" placeholder="dd-mm-yyyy" aria-describedby="input_7_3_date_format" aria-invalid="false" aria-required="true">
<span id="input_7_3_date_format">DD dash MM dash JJJJ</span>
</div>
</div>
</div>
</div>
<div>
<input type="submit" id="gform_submit_button_7" value="Versturen">
</div>
</form>
I removed your jQuery statements at the end of your script, as they referred to non-existent ids. These statements can definitely also be re-written in Vanilla JS, if necessary.
And, as #CherryDT already mentioned: there is no validation code visible here. If it happens on the server then it is the server's responsibility to produce a suitable response that allows the client to render the page with the previously (possibly annotated) content.
I make my JSON script with a form and a button, but when I demo it on someone, they can press the submit button whenever they like. Here is my code:
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br>
</form>
All I need now is validation and how to lock or hide the button. I tried using <script> with function and getElementById but I simply do not know how to lock it. Here is the message that will be inputted when it is locked and the form isn't completed:
You have not finished the information input for the survey. Please
input "Your First Name" and "Your Last Name" to enter the survey.
When they finish, I will input a loading icon until fully loaded.
Code Language(s)
I use fiddles to make my code, so I use:
HTML
JSON
Pinch of jQuery (loading icon)
Answer Expectations
In my answers, I need:
Recommended Code Language
Code for note purposes
Crossed out attributes
Attributes before coding explanations
EDIT: I just noticed that I can use the disabled boolean attribute here, so all I need is validation to disable the boolean attribute so they can press the button.
Hello I recommend JavaScript but it is not secure at all. However its the most effective in this case. Here is the code: (Note that i changed the html too)
<form action="action_page.php" method="get" >
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="inputEntries()"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname" onkeyup="inputEntries()"><br><br>
<button type="submit" name="submit" id="submit_btn" disabled="true">submit</button>
</form>
<script>
var fname_var = document.getElementById("fname");
var lname_var = document.getElementById("lname");
var submit_btn_var = document.getElementById("submit_btn");
function inputEntries(){
if(lname_var.value != "" && fname_var.value != "")
submit_btn_var.disabled = false;
else
submit_btn_var.disabled = true;
}
</script>
What it does is that if both input fields are empty the button is not clickable but if both are it can be clicked. hope it helped!
You can use either pure javascript or jQuery to validate.
In the below code you would see we are first binding a change event to the input field and getting its values. If both values are present, the disabled attribute of the submit button is removed. Else the opposite.
<p id="msg">You have not finished the information input for the survey. Please input "*Your First Name*" and "*Your
Last Name*" to enter the survey.</p>
<form action="action_page.php" method="GET">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"<br><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"<br><br><br>
<button type="submit" id="btn-submit">Submit</button>
</form>
$(document).ready(function(){
('#btn-submit').prop('disabled', true);
$("input[type=text]").change(function(){
if ($('#fname').val() && $('#lname').val()) {
$('#btn-submit').prop('disabled', false);
$('#msg').hide();
} else {
$('#btn-submit').prop('disabled', true);
$('#msg').show();
}
});
});
Stackblitz - https://stackblitz.com/edit/jquery-kgzhuo?file=index.html
I have a some custom validation for a small input form, that checks if a field is required. If it is a required field it alerts the user, if there is no value. At the moment it will validate all inputs other than check boxes.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email"></input>
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value)
alert(field.name + ' is required');
});
console.log(fields);
}
</script>
If anyone can work out how to include validation of check boxes, it would be much appreciated.
Even though some answers already provide a solution, I've decided to give mine, that will validate every required input in your form, regardless of being a checkbox (maintaining your each loop).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label>Question: What is your name?</label>
<input type="text" name="name" id="name">
</div>
<div class="ss-item-required">
<label>Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label>Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label>Do you agree to out terms?</label>
<input type="checkbox" name="Check_0">
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
$.each(fields, function(i, field) {
field=$(field).find('input, select, textarea')[0]
if (!field.value || (field.type=='checkbox' && !field.checked))
alert(field.name + ' is required');
});
}
</script>
The problems were:
serializeArray() would try to get the value from your checkbox, and because it returned nothing, the checkbox input was never added to fields!
Checkboxes don't have a property value, instead they are checked
There is more than one way to determine this:
Check the length of the JQuery wrapped set that queries for only checked checkboxes and see if it is 1:
if($("input[name='Check_0']:checked").length === 1)
Check the checked property of the DOM element itself (which is what I'm showing below) for false. To extract the DOM element from the JQuery wrapped set, you can pass an index to the wrapped set ([0] in this case), which extracts just that one item as a DOM element and then you can use the standard DOM API.
if(!$("input[type='checkbox']")[0].checked)
NOTE: It's important to understand that all client-side validation can be easily bypassed by anyone who really wants to. As such, you
should always do a second round of validation on the server that will
be receiving the data.
FYI: You have some invalid HTML: There is no closing tag for input elements and for label elements, you must either nest the element that the label is "for" inside of the label or you must add the for attribute to the label and give it a value of the id of the element that the label is "for". I've corrected both of these things below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="userName" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
var fields = $(".ss-item-required")
.find("select, textarea, input").serializeArray();
$.each(fields, function(i, field) {
if (!field.value){
alert(field.name + ' is required');
}
});
// Check to see if the input is a checkbox and if it's checked
if(!$("input[type='checkbox']")[0].checked){
alert("You must agree to the terms to continue.");
}
}
</script>
Personally (and I'm far from alone on this), the use of JQuery is way overused in today's world. When it came out, the standard DOM API wasn't as mature as it is now and JQuery made DOM element selection and manipulation very simple. Back then, JQuery was a Godsend.
Today, the DOM API has matured and much of what we use to rely on JQuery to make easy, can be done just as easily without JQuery. This means you don't have to reference the JQuery library at all (faster page loading) and you're code follows standards.
If you're interested, here's your code without JQuery:
<form>
<div class="ss-item-required">
<label for="userName">Question: What is your name?</label>
<input type="text" name="name" id="userName">
</div>
<div class="ss-item-required">
<label for="email">Question: What is your email?</label>
<input type="text" name="email" id="email">
</div>
<div class="ss-item-required">
<label for="address">Question: What is your address?</label>
<textarea name="address" rows="8" cols="75" id="address"></textarea>
</div>
<div class="ss-item-required">
<label for="Check_0">Do you agree to out terms?
<input type="checkbox" name="Check_0">
</label>
</div>
Submit
</form>
<script>
function formcheck() {
// Get all the required elements into an Array
var fields = [].slice.call(document.querySelectorAll(".ss-item-required > *"));
// Loop over the array:
fields.forEach(function(field) {
// Check for text boxes or textareas that have no value
if ((field.type === "text" || field.nodeName.toLowerCase() === "textarea")
&& !field.value){
alert(field.name + ' is required');
// Then check for checkboxes that aren't checked
} else if(field.type === "checkbox" && !field.checked){
alert("You must agree to the terms to continue.");
}
});
}
</script>
This is my first post so don't judge me if i do something wrong because i'm still learning but i have a question i'm making a form and i have a problem. When i left the button without any extra stuff when i tested the form i got as many entries as many times i clicked the button so i used a code snippet from here in JS and made the button so it disappears, problem is when i don't fill the form correctly it doesn't send the entry, so the question is how can i add the condition in form so the button only disappears when every field is written correctly? I would add the whole html but it's houndreds of lines of code now since it's pretty much where i test things here is the form code though.
My other thought was to maybe try to edit the php code, but to be honest i have no knowledge of that because my friend made that.
I also searched google and here for some tips but couldn't find any, thanks for help in advance.
$("#hideme").click(function(){
$(this).hide();
});
<form method="post" action="thankyou.php" style="overflow:hidden" class="accident-form4">
<input type="hidden" name="lang" value="pl">
<div class="form-group required">
<label for="name">Imię i nazwisko<span></span></label>
<input type="text" class="form-control inputToUpper" name="firstname" placeholder="Andrzej Kowalski" required="required" pattern=".*\S+.*" title="Wpisz swoje imię">
</div>
<div class="form-group required">
<label for="email">Email<span></span></label>
<input type="email" class="form-control" required="required" name="email" placeholder="np. andrzej.kowalski#gmail.com" title="Wpisz poprawny adres email!" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$">
</div>
<div class="form-group">
<label for="tel">Numer telefonu<span></span></label>
<input type="text" name="tel" placeholder="079 1234 5678" class="form-control" required="required" size="12" value="">
</div>
<label for="hour">Preferowana godzina kontaktu</label>
<select class="form-control" name="hour" placeholder="" title="" />
<option>Dowolna</option>
<option>Rano</option>
<option>Po południu</option>
<option>Wieczorem</option>
</select>
<input type="submit" name="lead" class="send" id="hideme" value="ROZPOCZNIJ CLAIM →">
</form>
you can simply check the value of the required fields before hiding the button.
$("#hideme").click(function(){
if (document.getElementsByName('firstname')[0].value != '' &&
document.getElementsByName('email')[0].value != '' &&
document.getElementsByName('tel')[0].value != '') {
$(this).hide();
}
});
or use your RegExp in Javascript again.
$("#hideme").click(function(){
if (document.getElementsByName('firstname')[0].value.match (/.*\S+.*/) &&
document.getElementsByName('email')[0].value.match (/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$/) &&
document.getElementsByName('tel')[0].value.match (/[0-9]+/)) {
$(this).hide();
}
});
that should to the trick (but i didn't test it).
I'm new with Javascript and I'm learning by myself. I have a problem with a form on my page. I just want to test with a simple javascript code that I can manipulate my input "type=submit" by adding a function to it to console.log a string when the form is submitted (I watched it on a video and I wanted to do it by myself).
Here is my code:
(function() {
"use strict";
document.getElementById('enviar').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
and this is my HTML code:
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>
The problem that I'm having here is that is not working at all.. my ID element is selected properly but I don't know what is wrong with my code. I created a variable and console my ID selected to see if I was getting the right element from the DOM and I'm getting in the console the right input element. please if someone knows why is not working.
plus: On my text input field I have a regular expression but I'm not getting the output I want.. the goal is that the user has to write at least two names (First and Last), so when they write just one it will be incorrect.. the problem that I'm having with this regular expression if when someone writes more than two names (First, Middle and Last) I DON'T want to make that an incorrect answer because technically is correct. So I need to make a better regular expression to get that result (when the user writes two or more names, not just two) but I don't know too much about Regular Expressions.
You are getting the element with the id enviar which is the submit button element. You need to be querying based on the form's element id which is escribenos. Try running the snippet below and you can see that it has the expected outcome.
(function() {
"use strict";
document.getElementById('escribenos').addEventListener('submit', enviar);
function enviar(event) {
event.preventDefault();
console.log("you submitted the form");
}
})();
<form id="escribenos" method="post">
<label for="name">Nombre y Apellido</label>
<input type="text" name="name" id="name" pattern="[A-Za-z]+\s+[A-Za-z]+" required value=""/>
<label for="email">Correo electrónico</label>
<input type="email" name="email" id="email" required />
<label for="asunto">Asunto</label>
<input type="text" name="asunto" id="asunto" />
<label for="comentario">Mensaje</label>
<textarea maxlength="250" rows="5" name="comentario" id="comentario" style="resize:none;"></textarea>
<input id="enviar" value="enviar" type="submit" ></input>
</form>