Want to prevent a textbox from becoming empty with javascript - javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />

You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}

You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}

save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

Related

how to validate on blank input search box

how to get the search input to recognize that there is a string of input?
the code below works but even without entering any input it still does the search if I click search or enter. In other words even if the search input is blank it still searches. This is just a project, anyone has any ideas?
<input type="text" id="textInput" name="" class="query">
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
Simply check for a (valid) length, either greather than zero or greater than maybe three characters for any meaningful results (depends on your searches).
<script>
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function(){
if(query.value.trim().length){ // maybe length>3 ?
let url = 'https://www.google.com/search?q='+query.value;
window.open(url,'_self');
}
}
</script>
<script>
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
</script>
You have to check if the value of input exists or it is not empty.
You can also check:
input.value.length
input.value !== ""
input.value
let query = document.querySelector('.query');
let searchBtn = document.querySelector('.searchBtn');
searchBtn.onclick = function() {
let url = 'https://www.google.com/search?q=' + query.value;
window.open(url, '_self');
}
var input = document.getElementById("textInput");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13 && input.value) {
event.preventDefault();
document.getElementById("searchButton").click();
}
});
<input type="text" id="textInput" name="" class="query">
<button class="searchBtn">Search</button>
Working Fiddle
If you wrap your inputs in a <form></form> you can use HTML5's built in validation.
In my example:
pattern="[\S]+" means all characters except space are valid
required means the input length must be at least 1 valid character
Also, I'm toggling the button's disabled property based on the input's validity. In my opinion it makes for a better user experience letting the user know something is incorrect BEFORE clicking the button.
let button_search = document.querySelector('button.search');
let input_query = document.querySelector('input.query');
button_search.addEventListener('click', function() {
if (input_query.validity.valid) {
window.open('https://www.google.com/search?q=' + input_query.value, '_self');
}
});
input_query.addEventListener('keyup', function(event) {
button_search.disabled = !input_query.validity.valid; //visual indicator input is invalid
if (event.keyCode === 13) {
button_search.click();
}
});
<form>
<input class="query" pattern="[\S]+" required>
<button class="search" disabled>Search</button>
</form>
Last thought, unless there is a specific reason you need to run your code in separate scopes, you can put all of your code in a single <script></script>

Form Validation Vanilla JS

I'm building a multipage form and I have some unusual validation requirements. Here's what I'd like to do/what I have done so far.
What I Want to Do:
(1) As each form field is filled in, I want a function to run and check that the user-input has met certain conditions -- i.e. for first and last name, that there are no numbers and there is a space in between the names.
(2) Once each of the field are full and have passed as true, I want another function to run that re-enabled a previously disabled "Next" button that will move the user to the next page of the form.
What I Have Done
(1) Created a mini version of the form with two inputs:
One that takes a first name, a space and a last name
One that takes a phone number set up the following way xxx xxx xxx
(2) I've console.logged the results with pass/fail logic so I know when certain things are being input by the user, that the code is validating properly.
Where I am Stuck:
I do not know how to create the secondary code that will reenabled the previously disabled "next" button that will move the form to the next page.
What I would like to do is make it so when the "Next" button is reenabled, and clicked on, it's own onclick function hides the current page, looks for the next page in the sequence and changes its display:block and I believe I have that code worked out separately, but I don't know how to integrate it with my other needs.
function checkForm()
{
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
function checkFirstName()
{
if(firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
console.log("Put a first Name and Last Name");
}
else
{
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber()
{
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/))
{
console.log("Please Put in a proper phone number");
}
else
{
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
};
<form>
First Name: <input type="text" id="name" onblur="checkForm()" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" onblur="checkForm()" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
See below code.
It might be more user-friendly to use on keyup rather than onblur, as most users I know will try and click the disabled button, rather than pressing tab or focusing on another element.
function checkForm() {
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var phoneCanSubmit, nameCanSubmit = false;
function checkFirstName() {
if (firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
nameCanSubmit = false;
console.log("Put a first Name and Last Name");
} else {
nameCanSubmit = true;
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber() {
if (!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
phoneCanSubmit = false;
console.log("Please Put in a proper phone number");
} else {
phoneCanSubmit = true;
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
if (nameCanSubmit && phoneCanSubmit) {
document.getElementById("myButton").disabled = false;
} else {
document.getElementById("myButton").disabled = true;
}
};
<form>
First Name:
<input type="text" id="name" onblur="checkForm()" />
<label id="nameErrorPrompt"></label>
<br />Phone Number:
<input type="text" id="phone" onblur="checkForm()" />
<label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
The code below gives you what you want. I removed some extraneous checks to simplify the code and also moved the event handlers from he HTML to the JavaScript. I also pulled the field checks out of the larger checkForm function. This provides you the flexibility to use them one at at time if need be.
window.addEventListener('load', function(e) {
var nameInput = document.getElementById('name');
var phoneInput = document.getElementById('phone');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(e) {
e.preventDefault(); //Stop the page from refreshing
getNextPage('Next page shown!!');
}, false);
nameInput.addEventListener('blur', function(e) {
checkName(this.value);
}, false);
phoneInput.addEventListener('blur', function(e) {
//Uncomment below to make this responsible only for checking the phone input
//checkPhoneNumber(this.value);
/*You could do away with diasbling and check the form
on submit, but if you want to keep the disable logic
check the whole form on the blur of the last item*/
checkForm();
}, false);
}, false);
function getNextPage(foo) {
console.log('Callback fired: ', foo);
//Do something here
}
function checkPhoneNumber(phone) {
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
console.log("Please Put in a proper phone number");
return 0;
}
else {
console.log("Thank you name entered");
return 1;
}
};
//Removed a bit of over coding, no ned to check isNaN or empty string since using regex already
function checkName(firstAndLastName) {
if(!firstAndLastName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
console.log("Put a first Name and Last Name");
return 0;
}
else {
console.log("Thank You phone entered");
return 1;
}
};
function checkForm() {
var validCount = 0;
fieldCount = document.forms[0].elements.length - 1; //substract one for the submitbutton!
var phoneNum = document.getElementById('phone').value;
var name = document.getElementById('name').value;
var myButton = document.getElementById('myButton');
validCount += checkPhoneNumber(phoneNum);
validCount += checkName(name);
console.log(validCount + ' of ' + fieldCount + ' fields are valid');
if (validCount > 0 && validCount === fieldCount) {//Compare the inputs to the number of valid inputs
myButton.disabled = false;
}
else {
myButton.disabled = true;
}
}
HTML
<form>
First Name: <input type="text" id="name" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
How about you start by making the onblur for each input return a boolean indicating if the field is valid.
Then setting a cansubmit variable (= checkName && checkPhone) in the checkForm function and only moving on after that - then you don't need to enable and disable the button.
If you really want the button to enable you can use the same pattern, but do
document.getElementById("myButton").disabled = !canSubmit;
and you will always want to call checkForm on field blur like you are now.
Also note you aren't scoping canSubmit locally right now.

Intercept input entering

Is there a way to intercept the value the user inputs before it ever even appears in the element? I tried to use Object.defineProperty but it appears to not work for InputElement.value since
var value;
Object.defineProperty($('input')[0], 'value', {
get: function() {return value},
set: function(val) {console.log(val); value = val;}
});
doesn't appear to change any behavior. Or is oninput/onchange the only option? Since I'd rather have my code executes before the browser's.
http://jsfiddle.net/zpmu1xcu/
If you want to detect input before the text is entered by the browser, you can use the Element.onkeydown property. This event fires as soon as the key is pressed down, before the browser interprets the action.
var demo_i = document.getElementById('demo_i');
var demo_d = document.getElementById('demo_d');
demo_i.onkeydown = function(e) {
demo_d.textContent = e.which;
// Returning false stops the event from going any further
return false;
}
<input id="demo_i"><div id="demo_d"></div>
is this what you are looking for?
function InterceptInputValue($input) {
var value = $input.val();
// intercept value that changes and saved to value variable
$input.keydown(function(e) {
value += String.fromCharCode(e.keyCode);
return false;
});
this.getValue = function() {
return value;
};
}
var i = new InterceptInputValue($("input"));
$("input").blur(function() {
alert('input value is: ' + i.getValue());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
I think you're only option is keyup.
It is the only one that can capture the data and not leave any behind.
Using the snippet below, type test in each of the text boxes.
The code tries to reset the value to blank with each key stroke.
keyup is the only one that deletes the input with each stroke.
keydown clears the last character typed, once you leave the field.
keypress leaves the last character typed in the input field
var tbxKeyDown = document.getElementById('tbxKeyDown');
var tbxKeyUp = document.getElementById('tbxKeyUp');
var tbxKeyPress = document.getElementById('tbxKeyPress');
// [Jedi mind trick] ==> you entered nothing
tbxKeyDown.addEventListener('keydown', testKeyDown, false);
tbxKeyUp.addEventListener('keyup', testKeyUp, false);
tbxKeyPress.addEventListener('keypress', testKeyPress, false);
// Remove anything entered
function testKeyDown() {
tbxKeyDown.value = '';
}
function testKeyPress() {
tbxKeyPress.value = '';
}
function testKeyUp() {
tbxKeyUp.value = '';
}
KeyDown = <input type="text" id="tbxKeyDown" value="" />
<br/><br/>
KeyUp = <input type="text" id="tbxKeyUp" value="" />
<br/><br/>
KeyPress = <input type="text" id="tbxKeyPress" value="" />

Disable form button unless all text input fields are filled in

I have a form that has multiple text inputs, I don't want to add id to each one as they are generated from server side code - number of fields may differ etc. I just want to be able to disable the submit button until there is text entered into each text input.
I have gotten this far, but only disables button until text entered in to one text input field - I want it to stay disabled until text entered in to all text inputs.
<script>
$(function () {
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
$('#button').prop('disabled', this.value == "" ? true : false);
})
});
</script>
I have also tried $('input:text').each().keyup(function (){ - but does not make button clickable?
$('#button').attr('disabled', true);
$('input:text').keyup(function () {
var disable = false;
$('input:text').each(function(){
if($(this).val()==""){
disable = true;
}
});
$('#button').prop('disabled', disable);
});
Demo
The callback function for keyup now checks only that specific input field's value (this.value). Instead, this needs to loop through all input fields that need to be filled, and only when all have text do you change the the .prop value.
$('input:text').keyup(function () {
$('#button').prop('disabled', allFieldsAreFilled());
});
function allFieldsAreFilled() {
var allFilled = true;
// check all input text fields
$("#yourForm input:text"]).each(function () {
// if one of them is emptyish allFilled is no longer true
if ($(this).val() == "") {
allFilled = false;
}
});
return allFilled;
}
Try this:
$(function() {
var bool = true, flag = false;
$('#button').prop('disabled', bool); // use prop to disable the button
$(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs
$('input:text').each(function() { // loop through each text inputs
bool = $.trim(this.value) === "" ? true : false; // update the var bool with boolean values
if(bool)
return flag;
});
$('#button').prop('disabled', bool); // and apply the boolean here to enable
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='button' id='button' value='button' />

Input text form, using javascript to clear and restore form contents problem

I have this line of HTML
<input type="text" name="addQty" size="1"
class="addQty" value="0"
onclick="$(this).val('')"
onblur="itmQtyChk($(this).val())" />
the itmQtyChk function does this:
function itmQtyChk( qty ) {
if( qty == "") {
$(this).val("0");
} else {
$(this).val(qty);
}
}
My problem is I want it to return the original value to the input text if they exit the field and don't change anything, but it is not working.
Thank you for any help.
this in itmQtyChk function is not referring to the input but to the window object.
Change the function to accept the input as parameter:
function itmQtyChk(input) {
if (input.val() == "") {
input.val("0");
}
// the else part is not needed
}
with the onblur event also:
onblur="itmQtyChk($(this))"
Check this fiddle, it has lots of room for improvement, but it can help you:
http://jsfiddle.net/eDuKr/1/
$(function(){
var cacheQty;
$('.addQty').click(function(){
cacheQty = $(this).val();
$(this).val('');
}).blur(function(){
if ($(this).val() === ''){
$(this).val(cacheQty);
}else{
cacheQty = $(this).val();
}
});
});

Categories

Resources