Get the input selector using this - javascript

I have set of input fields which are generated dynamically, hence I can't use an ID. For each of the input fields I have a focusout method which validates the value input by the end user.
If the validation fails, I would like to clear the value of the input and bring back the focus to the same input. When I tried to use this keyword scope seems to be set to the windows rather than the input control.
Input fields screenshot:
function validate(reg){
debugger;
if(isNaN(reg)==false){
return;
}
else
{
alert("The field should contain number");
$(this).val(""); //clear the value
$(this).focus();
}
}
In the above code, this keyword doesn't seem to work.

Pass the event to your validate() function, and then you can use event.target to target the input element.
function validate(reg, e){
debugger;
if(isNaN(reg)==false){
return;
}
else
{
alert("The field should contain number");
$(e.target).val(""); //clear the value
$(e.target).focus();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input onfocusout="validate(this.value, event)"/>
<input onfocusout="validate(this.value, event)"/>
<input onfocusout="validate(this.value, event)"/>

Another method:
$(document).ready(function () {
var inputs = document.querySelectorAll("input[type=text]");
for (i = 0; i < inputs.length; i++)
inputs[i].addEventListener("focusout", function () { validate(this); });
});
function validate(reg) {
if (isNaN($(reg).val()) == false) {
return;
}
else {
alert("The field should contain number");
$(reg).val(""); //clear the value
$(reg).focus();
}
}
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />
<input type="text" value="" />

Related

Listen for blank inputs and add a "disabled" attribute to a button until an input is noticed

I have a user input field that, if blank, I would like the submit button to be disabled until a key press in the input box is noticed. But, if they blank out the input box, then the button is disabled again.
So, I'd like to add the "disabled" attribute to this input button:
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
The input is from this HTML here:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
Note: I have onkeypress and oninput validation to prevent non-number inputs and allow only 2 decimal places.
I assume my JS would look like this to add the disabled attribute:
document.getElementById("mapOneSubmit").setAttribute("disabled");
My problem is, I can't find what event listener listens for "blank" inputs? Can you help me with that?
Thanks kindly!
Check this one as well.
function checkvalid(el)
{
//e.g i am preventing user here to input only upto 5 characters
//you can put your own validation logic here
if(el.value.length===0 || el.value.length>5)
document.getElementById("mapOneSubmit").setAttribute("disabled","disabled");
else
document.getElementById("mapOneSubmit").removeAttribute('disabled');
}
<input type='text' id ='inp' onkeyup='checkvalid(this)'>
<button id='mapOneSubmit' disabled>
Submit
</button>
Yet using the input event:
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this);updateSubmit(this.value)">
Then in js
function updateSubmit(val) {
if (val.trim() == '') {
document.getElementById('mapOneSubmit').disabled = true;
}
else {
document.getElementById('mapOneSubmit').disabled = false;
}
}
You can find the below code to find the blank inputs
function isNumberKey(event) {
console.log(event.which)
}
var value;
function validate(target) {
console.log(target);
}
<form>
<input type="text" id="mapOneUserInput" onkeypress="return isNumberKey(event)" oninput="validate(this)">
<input type="submit" id="mapOneSubmit" value="Submit" [add attribute "disabled" here]>
</form>
You can you set the enable/disable inside validate function.
function validate(elem) {
//validation here
//code to disable/enable the button
document.getElementById("mapOneSubmit").disabled = elem.value.length === 0;
}
Set the button disable on load by adding disabled property
<input type="submit" id="mapOneSubmit" value="Submit" disabled>
On your validate function just check if value of input field is blank then enable/disable the button
function validate(input){
input.disabled = input.value === "" ;
}
My problem is, I can't find what event listener listens for "blank" inputs?
You can disable the submit button at render, after that you can use the input event to determine whether the input value is empty or not. From there, you can set state of the submit button.
document.addEventListener('DOMContentLoaded', () => {
const textInput = document.getElementById('mapOneUserInput');
textInput.addEventListener('input', handleTextInput, false);
textInput.addEventListener('keydown', validateInput, false);
});
function handleTextInput(event) {
const { value } = event.target;
if (value) {
enableSubmitButton(true);
} else {
enableSubmitButton(false);
}
}
// Refer to https://stackoverflow.com/a/46203928/7583537
function validateInput(event) {
const regex = /^\d*(\.\d{0,2})?$/g;
const prevVal = event.target.value;
const input = this;
setTimeout(function() {
var nextVal = event.target.value;
if (!regex.test(nextVal)) {
input.value = prevVal;
}
}, 0);
}
function enableSubmitButton(isEnable) {
const button = document.getElementById('mapOneSubmit');
if (isEnable) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', '');
}
}
<input type="number" value="" id="mapOneUserInput">
<!-- Note that the input blank at render so we disable submit button -->
<input type="submit" id="mapOneSubmit" value="Submit" disabled>

Prevent multiple alert on "oninvalid" html

I was thinking, can i stop the alerts after the first?
I'll explain it better, every time I confirm the form, start an aler for every input that has oninvalid.
so if i have 10 inputs, i'll have 10 alarms. Is it possible to interrupt them after the first one?
<form>
<input type="text" oninvalid="alert('test1')" required />
<input type="text" oninvalid="alert('test2')" required />
<button>Send</button>
</form>
Fiddle: https://jsfiddle.net/9d1L5pxd/1/
You can consider doing something like I demonstrate below. Basically just add an event handler to the send button, which will call a validation function on your form each time it's clicked.
The validation function checks all the text type field values. If a text field with an invalid value is encountered, the function will return false (stop immediately).
If the function doesn't find any problems with the user input then it will return true. You can use the return value to determine if the form should be submitted or whatever if you need to.
var btnSend = document.getElementById('btnSend');
btnSend.addEventListener('click', function() {
var isValid = validateForm();
if (isValid)
console.log('Form is ready to submit.');
});
function validateForm() {
var formToValidate = document.getElementById('dataForm');
var elements = formToValidate.elements;
var i;
for (i = 0; i < elements.length; i++) {
if (elements[i].type == 'text') {
//replace this with your actual validation
var invalid = elements[i].value.length == 0;
if (invalid) {
alert(elements[i].id + ' is invalid.');
return false;
}
}
}
return true;
}
<form id="dataForm">
<input id="field1" type="text" required />
<input id="field2" type="text" required />
<input id="btnSend" type="button" value="Send">
</form>

Javascript - Enable Submit button when all input is valid

So I have a form with some inputs (First and last name, user name, birthday, password and email) with some validation conditions which I made like this for example :
function checkfnlname(field) {
curr = document.getElementById(field).value;
if ( curr.length > 0) {
updateCSSClass(field, 1);
return true;
}
else {
updateCSSClass(field, 0);
return false;
}}
This changes it's color and return true . I call these function using onKeyUp="". Now what I want to do is make the Submit button disabled until all the fields have been completed and validated by the functions up there. I wrote this function :
function formvalid() {
if (checkfnlname('fname') && && (all other fields)) {
document.getElementByID("submitinput").disabled = false;
}
else {
document.getElementByID("submitinput").disabled = true;
}
return 1;}
But I have no idea how/where to call it. (I tried a lot of things I found but nothing worked)
Is this the right way to do it ? if so how can I call this function ?
Here's a pure ES6 and HTML5 way.
You can watch your form for changes and then check to see if the form is valid.
const form = document.getElementById('form');
form.addEventListener("change", () => {
document.getElementById('submitBtn').disabled = !form.checkValidity()
});
I have modified an example from MDN to show this in action -> https://jsfiddle.net/denov/hxf3knob/2/
My approach:
function updateCSSClass(a, b) {
}
function checkfnlname(field) {
curr = document.getElementById(field).value;
if (curr.length > 0) {
updateCSSClass(field, 1);
return true;
} else {
updateCSSClass(field, 0);
return false;
}
}
window.onload = function () {
var btnSubmit = document.getElementById('submit');
// disable submit
btnSubmit.setAttribute('disabled', 'disabled');
// attach the keyup event to each input
[].slice.call(document.querySelectorAll('form input:not([type="submit"])')).forEach(function (element, index) {
element.addEventListener('keyup', function (e) {
// compute the number of invalid fields
var invalidFields = [].slice.call(document.querySelectorAll('form input:not([type="submit"])')).filter(function (element, index) {
return !checkfnlname(element.id);
});
if (invalidFields.length == 0) {
// reenable the submit if n. of invalid inputs is 0
btnSubmit.removeAttribute('disabled');
} else {
// disable submit because there are invalid inputs
btnSubmit.setAttribute('disabled', 'disabled');
}
}, false);
});
}
<form action="http://www.google.com">
First name:<br>
<input type="text" name="firstname" id="firstname"><br>
Last name:<br>
<input type="text" name="lastname" id="lastname"><br>
User name:<br>
<input type="text" name="username" id="username"><br>
Birthday:<br>
<input type="date" name="birthday" id="birthday"><br>
Password:<br>
<input type="password" name="password" id="password"><br>
email:<br>
<input type="email" name="email" id="email"><br>
<input type="submit" value="submit" id="submit">
</form>
It's simple, invoke button enable/disable function on within your type/value check function, something like this-
function checkfnlname(field) {
//here you can perform input check
curr = document.getElementById(field).value;
if ( curr.length > 0) {
updateCSSClass(field, 1);
return true;
}
else {
updateCSSClass(field, 0);
return false;
}
// to check button validations
formvalid();
}
Going this way, every time you type in the form it'll check it whether the condition for button matches or not, and will function accordingly.!
You need to call the validation function in the events.
// For example
<input type="text" onkeyup="validateForm()">
<select onchange="validateForm()"></select>
Second way:
Instead of using a submit button, use a normal button and call a function which checks your form items.
// Into the form or anywhere you want
<button type="button" onclick="validateForm()">Submit</button>
function validateForm() {
// Code to validate the form items
// if validated, send the form
// For example submitting a form with javascript
document.getElementById("myForm").submit();
}
The easiest way would be to call formvalid() onkeyup for every field. That function validates every field and shows the button if they are valid.
This should do the job, although it is not very efficient. It is a job in vain to check every field every time you type anything on any field. Ex: when you start on the first input there's no point in checking the last.
Instead you could have a check function that updates a global boolean variable when the field has valid data, and then the validate function to check the booleans instead of calling the check function. Then onkeyup in everyfield you should call both separately (first the check, then the validate).
Something like:
validFields=[];
function checkField(field) {
if (conditionIsMet) validFields[validFields.length]=field;
}
function validateForm() {
if (validFields.length==numberOfFields) ...
}
and
<input type="text" name="field1" value="" onkeyup="checkfield(this.name);validateForm()" />

JavaScript Form Validation Not Showing Alert or Changing Input Background Colour

I made this script to validate my forms however, when I leave a textfield blank nothing happens, there is no red background to the input box or alert message as I expected there to be.
function validateForm()
{
/* For all forms in the document */
for(var i in document.forms)
{
/* Get the forms inputs */
var inputs = document.forms[i].getElementsByTagName("input");
for(var j in inputs)
{
/* Make sure we don't try to validate the submit button */
if(inputs[j].type == "text")
{
if(inputs[j].value.trim() == "" || inputs[j].value.trim() == null)
{
inputs[j].style.backgroundColor = "red";
alert("Please ensure all boxes are filled in");
return false;
}
}
}
}
}
Here is one of my forms if that helps:
<form name="searchArtists" method="get" onsubmit="return validateForm()">
<input type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
<input type="submit" name="submit" value="Search"/>
</form>
Use placeholder attribute for placeholder text
<input type="text" name="artists" placeholder="Search Artists"...
Another issue I suggest to don't allow spaces as well
if(inputs[j].value.trim() == "") { ...
In your code i is a form and j is an input. Because of that, document.forms[i] and inputs[j] don't work.
Fixed JavaScript function:
function validateForm()
{
/* For all forms in the document */
for(var i in document.forms)
{
/* Get the forms inputs */
var inputs = i.getElementsByTagName("input");
for(var j in inputs)
{
/* Make sure we don't try to validate the submit button */
/* Trim value to not allow values with only spaces */
if(j.type == "text")
{
if(j.value == null || j.value.trim() == "")
{
j.style.backgroundColor = "red";
alert("Please ensure all boxes are filled in");
return false;
}
}
}
}
}
HTML:
<form name="searchArtists" method="get" onsubmit="return validateForm()">
<input type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
<button type="submit">Search</button>
</form>
Let's cut this down a bit, first add an ID to the element we want to validate, I also suggest changing your current "value" to a "placeholder", like so:
<input id="artistQueryInput" type="text" name="artists" placeholder="Search Artists" maxlength="255" size="32" />
Now on to the Javascript:
function validateForm(){
//Get element
var inputElement = document.getElementById('artistQueryInput');
//Get value
var rawArtistQueryString = inputElement.value;
//Strip all whitespace
var baseArtistQueryString = rawArtistQueryString.replace(/ /g, "");
//Validate string without whitespace
if((baseArtistQueryString == '') || (baseArtistQueryString == NULL) ||){
//Assuming j is artistQueryInput
inputElement.style.backgroundColor = "red";
alert("Please ensure all boxes are filled in");
return false;
}
}

Jquery validation of input array elements manually

<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
<input type="text" name="member_name[]" size="13" value="">
How do i validate these 4 fields so that they are not blank.. without using jquery validate plugin.?
You can cancel the form submission by registering a submit event handler and prevent the default behavior if one of your fields is empty:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]'][value='']", this).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
EDIT: As naveen correctly points out, the code above would still submit the form if the fields only contain whitespace. You can use $.trim() with filter() to fix the problem:
$("form").submit(function(event) {
if ($("input:text[name='member_name\\[\\]']", this).filter(function() {
return $.trim(this.value) == "";
}).length) {
window.alert("No member name should be empty.");
event.preventDefault();
}
});
$('input:submit').click(function() {
$('form').submit(function(e) {
$("input:text[name^='member_name']").each(function() {
if (!$.trim($(this).val()).length) {
alert('Name Field should not leave empty');
return false; // or e.preventDefault();
}
});
});
});
var valid = true;
$('input').each(function(){
if($(this).val() == "") {
valid = false;
}
});
// use valid here
var invalidInputs = $('input').filter(function() {
return $(this).val() == "";
});
var valid = invalidInputs.length == 0
Not most advance, but simple & clear method.
$("form").submit(function(event) {
var inputLength = $('input[type="text"]').val().length; // check for value length
if ($('input').val().length > 0) {
// submit if input value is length > 0
alert('Form submitted.');
}
else {
// error if input value is NOT length > 0
alert('Fill the form.');
event.preventDefault();
}
});

Categories

Resources