How to set default value of input if value is empty? jQuery - javascript

Example, i have input where default value is 5.
But user remove it using backspace, so after that i want to set default value again.

Lets say your input is having a id test you can do like below
$('#test').on('change blur',function(){
if($(this).val().trim().length === 0){
$(this).val(5);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" type="text" value = "5" />

Use defaultValue to get the default value if set originally:
$(':text').on('blur', function(e){
this.value = this.value.trim() || this.defaultValue;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='5'>

I'd suggest not using keyup, as that would prevent the user from deleting the default value and then updating with a new value (since after keyup is triggered by the backspace key there will be no value).
Instead I'd suggest using change and blur, to give (assuming that the relevant element is held in the selector variable):
$(selector).on('change blur', function() {
// sets the value of the element based on the current-value;
// if the value is equal to an empty string ('') once the
// leading and trailing white-space is removed (using
// String.prototype.trim()) then we set the value to the
// defaultValue (the value held by the <input> on page-load)
// otherwise we set it to the current-value:
this.value = this.value.trim() === '' ? this.defaultValue : this.value;
});
If you wanted to implement the same functionality in plain JavaScript ā€“ again assuming the relevant element is held in the selector variable ā€“ you could use the following:
function defaultIfEmpty(){
let el = this;
el.value = el.value.trim() === '' ? el.defaultValue : el.value;
}
selector.addEventListener('change', defaultIfEmpty);

It would be better to use blur instead of keyup, and here's why.
What happens if the user wants to enter in a number (only one digit), but it's not 5, let's say it's (3). If the user backspaces the default number, which is (5) in this case, and wants to enter a single digit, the user will never be able to.
$('#test').on('blur',function(){
if($(this).val().trim().length == 0){
$(this).val(5);
}
})
Note: You should also use a keyup function to check if the value is an integer, !isNaN

A more generic solution:
HTML
<input type='text/numeric/etc' data-default='defaultValue' value='defaultValue' />
JavaScript
$('input[data-default], textarea[data-default]').on('change blur',function(){
if($(this).val().length == 0) {
$(this).val($(this).attr("data-default"));
}
}
Any input or textarea with the data-default attribute set will fallback to the default once it's emptied.

<input class="test" type="text" value = "5" />
JS
//get default value
val = $('.test').val();
$('.test').on('change blur', function() {
//check if change
if ($(this).val().trim().length === 0) {
$(this).val(val);
}
})

Related

How to block +,-,e in input type Number?

When I'm giving input type number the letter e and special charecters are also displaying in input field. I want to display only digits. How to block them?
<input type="number">
Try preventing the default behaviour if you don't like the incoming key value:
document.querySelector(".your_class").addEventListener("keypress", function (evt) {
if (evt.which != 8 && evt.which != 0 && evt.which < 48 || evt.which > 57)
{
evt.preventDefault();
}
});
// 0 for null values
// 8 for backspace
// 48-57 for 0-9 numbers
<input type="number" class="your_class">
A simple solution which I used in React.
onKeyDown={(evt) => ["e", "E", "+", "-"].includes(evt.key) && evt.preventDefault()}
You can block entering those chars with keydown event
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
but the user can still enter them if s/he does a copy/paste (or through the console). To prevent copy/paste, you can do a replace on the entered value [*].
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"+",
"e",
];
inputBox.addEventListener("input", function() {
this.value = this.value.replace(/[e\+\-]/gi, "");
});
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />
* You can't really get the entered value on an input field with type set to number. You can get the entered value as long as it is a number, that is, the value passes the internal number check. If the user copy/paste 1e, suggested solution will fail.
What happens when you enter 1e is that, input field checks if it's a number, and if it's not (1e is not) it throws a warning:
The specified value "1e" is not a valid number. The value must match to the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
and the value property is set to "".
If you check the field's properties, you'll find valueAsNumber property. If the entered value is a number, input field parses the value and stores it in valueAsNumber. Since 1e is not a number, it evaluates to NaN, and NaN is assigned to valueAsNumber and value is set to "". Though you still see 1e on the input field.
I've asked a question related to this problem, but no solution yet.
Get the entered value on number input field, not the parsed
Instead on trying to block values, you can try to replace values that are non numeric.
If you choose to handle keycodes, you will have to handle numKeys, numPad, shift +, crtl + etc and trying to refresh while focus is inside textbox will also fail. Prevent Default will stop lot more than incorrect values.
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
Following form from the answers above, most of the examples above cover it, i just noticed that when inputting "E" this is still allowable so i think its best to add this into the array. I am using Jquery 3.3.1 in this example.
Also that way whatever you enter into the array will be prevented from being keyed in into the input box
Note - take the 'elementid' as the id of the element you want to apply this to
similarly if you want to apply this to all inputs that are type number in JQuery --> $("input[type='number']")
var invalidChars = ["-", "e", "+", "E"];
$("input[type='number']").on("keydown", function(e){
if(invalidChars.includes(e.key)){
e.preventDefault();
}
}):
This sample above should work on all inputs with a type of number and prevent the characters "-", "e", "+" and "E" from being keyed into the input.
UPDATE
Just also notices that you are able to enter '.' as they represent decimal points which is valid for numbers. I was using this validating a telephone number and obviously (for UK) there is no '.' so that may also be another character to add to your array.
Here's a pretty concise solution using jQuery based on some of the other solutions:
$("input[type=number]").on("keydown", function(e) {
var invalidChars = ["-", "+", "e"]; //include "." if you only want integers
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
You can do it easily using jQuery
Try this code
$(function() {
$("#input").keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
$(".alert").html("Enter only digits!").show().fadeOut(2000);
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" />
<div class="alert"></div>
$("#input").on("input", function() {
var nonNumReg = /[^0-9]/g
$(this).val($(this).val().replace(nonNumReg, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="input" />
<div class="alert"></div>
You can check it if it's a number or not.
// Restrict e, -, + for html input number
$(document).on('keypress', ':input[type="number"]', function (e) {
if (isNaN(e.key)) {
return false;
}
});
Since OP's question was tagged with 'angularjs', the cleanest solution would probably be to use a directive. Several solutions for this approach have previously been explained here:
angularjs: allows only numbers to be typed into a text box
JQuery
You can also use the following code if you want to accept decimals(.)
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key)!=-1){}
else if (e.key=='.' && this.value!='' && (this.value.match("\.") || []).length==0){}
else{e.preventDefault();}
});
Here is React solution, hope it will help somebody
const numberInputInvalidChars = ['-', '+', 'e'];
<input
type="number"
onKeyDown={(e) => {
if (numberInputInvalidChars.includes(e.key)) {
e.preventDefault();
}
}}
></input>
With onKeyUp, onKeyPress or onKeyDown events the same can be restricted.
onKeyDown = {
(e) => ["e", "E", "+", "-"].includes(e.key) && e.preventDefault()
}
Yo can Block by using some JQuery codes
$('input[Type="Number"]').keypress(function (e) {
if ('0123456789'.indexOf(e.key) == -1) {
e.preventDefault();
}
});
This will affect on all Numeric typed Input
I'm not sure the details of your use case, but you may not need to do a lot to handle these yourself. For starters, you can set a min, which can be used to prevent negatives, as well as a max value and a step value if that's useful. It turns out the default step is 1, so it requires integers unless you specify a decimal step value.
When it comes to dealing with the "e" in numbers, you can use Number() to convert text to a number, and it'll automatically convert the "e", as well as any "+" sign:
> Number("5e3")
5000
> Number("+42")
42
If you really need the submitted value to be normalized, you can convert it back in place. I think probably the most user friendly time to do it would be on blur:
input.addEventListener('blur', () => {
if (input.value !== '' && input.checkValidity()) {
input.value = Number(input.value);
}
});
in the input of numeric type the events for characters with value different from [0-9] is an object
with
event.target.value: ""
so just prevent events that have no value
if (!event.target.value) {
event.preventDefault();
};
If you want + sign in your phone number field then you can use this code.
var inputBox = document.getElementById("inputBox");
var invalidChars = [
"-",
"e",
];
inputBox.addEventListener("keydown", function(e) {
if (invalidChars.includes(e.key)) {
e.preventDefault();
}
});
<input type="number" id="inputBox" />

Prevent Text Box Value Update if Invalid Data

I have implemented a handler for several text boxes (<input type="text">) on my form.
$(popUp).on('change', 'input', function (e) {
}
All values must be numeric and I call $.isNumeric($(this).val()) to ensure that the new value complies.
If the value is not numeric, however, I will display a message. But I would also like to restore the text box value to its original value to ensure the form data remains valid.
Is there any automated way to prevent the text box value from being updated?
What about this approach for reverting to initial value if the new value is numeric:
$(popUp).on('change', 'input', function (e) {
if (!$.isNumeric(this.value)) {
this.value = $(this).attr('value');
}
else {
$(this).attr('value', this.value);
}
});
http://jsfiddle.net/pLok67xh/
Another option could be to block non-numeric input all together, not sure if you need this though.
as I said in the comments, if you prevent the user from typing any non-numeric character in the first place, all the problems are solved:
$('input:text').keydown(function( e ) {
if(!/([\d ,\$])+/.test(String.fromCharCode(e.which)))
return false;
});
you can add keydown event.
$(popUp).on('keydown', 'input', function (e) {
var unicode=e.keyCode? e.keyCode : e.charCode
if unicode >= 48 && unicode <= 57 {
return true;
}
else{
return false;
}
});

Prevent keyup event from firing when input box selected

I have an event that I want to fire whenever R or SPACE is pressed, with the exception of when in an input field.
Specifically, I'm worried about <input id='nameInput' type='text'> that I dynamically create when I click in a div and remove onchange/onblur. That's why I tried checking if( !$('#nameInput') ), but $('#nameInput') is a jQuery object, so its boolean value is always true (and hence !$('#nameInput') == false).
$(window).bind('keyup',
function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 32 || code == 82){
if( !$('#nameInput') ){
roll();
}
}
}
);
I have a solution that utilizes a global boolean variable getting set in onfocus of the input field, but I'd like a solution that doesn't require a global variable if it's possible.
Is there a way to determine what element currently has focus?
You can use document.activeElement to know wich element currently has focus.
if (!$(document.activeElement).is('input, textarea')) {
roll();
}
You could also make use of the :focus selector.
if (!$(':focus').is('input, textarea')) {
roll();
}

Capturing the value of the proper input if one is a checkbox

Given the following markup:
<input name="active" type="hidden" value="0" />
<input id="active" name="active" type="checkbox" value="1" />
When the checkbox is unchecked and the form is submitted the server will get a value of "0" for the "active" param. When the checkbox is checked and the form is submitted the server will get a value of "1" for the "active" param. This works just fine.
What I want to do is capture the proper value in JavaScript based upon that. The trick, however, is I don't know if the input is a checkbox or not. As far as my script is concerned it is just acting on a set of inputs.
I have created a JSFiddle here: http://jsfiddle.net/bcardarella/5QRjF/ that demonstrates the issue.
TL;DR I want to ensure the value I capture from each input is the actual value sent to the server.
Don't know if you actually want to check for the checkbox or not, but this code works:
$(function() {
var getCheckBoxValue = function() {
if ($('[name="active"]:checkbox').attr("checked")) {
return $('[name="active"]:checkbox').val();
} else {
return $('[name="active"]').val();
}
}
var result = $('#result');
result.append($('<p/>', {text: 'Expected value 0, got: ' + getCheckBoxValue()}));
$(':checkbox')[0].checked = true;
result.append($('<p/>', {text: 'Expected value 1, got: ' + getCheckBoxValue()}));
});
Basically if the checkbox is checked, use that, otherwise, go with the default value from the hidden input.
Edit
Turned my comment into a fiddle, I've also added another field, a text field, to show better the idea behind it: http://jsfiddle.net/45qup/
Hope it helps!
Write up the click event for the checkbox..
$('#active').on('click', function(){
var isChecked = this.checked;
var val = 0;
if(isChecked){
val = 1
}
});
Try somthing like
$("form#formID :input").each(function(){
if ($(this).attr() == 'checkbox') return $(this).checked();
else return $(this).val();
});
Not sure if if Iā€™d go with this ;) , but it works:
var getCheckBoxValue = function() {
var values = $('[name="active"]')
.filter(':checked, :hidden')
.map(function(){
return parseInt($(this).val(), 10);
}
);
return Math.max.apply(Math, values);
}
http://jsfiddle.net/Xc5H7/1/
Inspired by #Deleteman's idea, this is a slightly simpler way of doing it:
var getCheckBoxValue = function() {
var input = $('[name="active"]');
return $(input[1].checked ? input[1] : input[0]).val();
}
This assumes there's only two fields with this name, which is a sane assumption for what you're trying to do.
It also assumes the hidden field always comes before the checkbox, which again, since this is, I assume, for Rails, is a sane assumption :)

Disabling/enabling a button based on multiple other controls using Javascript/jQuery

I have a bunch of controls:
When a user clicks the Generate button, a function uses all of the values from the other controls to generate a string which is then put in the Tag text box.
All of the other controls can have a value of null or empty string. The requirement is that if ANY of the controls have no user entered value then the Generate button is disabled. Once ALL the controls have a valid value, then the Generate button is enabled.
What is the best way to perform this using Javascript/jQuery?
This can be further optimized, but should get you started:
var pass = true;
$('select, input').each(function(){
if ( ! ( $(this).val() || $(this).find(':selected').val() ) ) {
$(this).focus();
pass = false;
return false;
}
});
if (pass) {
// run your generate function
}
http://jsfiddle.net/ZUg4Z/
Note: Don't use this: if ( ! ( $(this).val() || $(this).find(':selected').val() ) ).
It's just for illustration purposes.
This code assumes that all the form fields have a default value of the empty string.
$('selector_for_the_parent_form')
.bind('focus blur click change', function(e){
var
$generate = $('selector_for_the_generate_button');
$generate.removeAttr('disabled');
$(this)
.find('input[type=text], select')
.each(function(index, elem){
if (!$(elem).val()) {
$generate.attr('disabled', 'disabled');
}
});
});
Basically, whenever an event bubbles up to the form that might have affected whether the generate button ought to be displayed, test whether any inputs have empty values. If any do, then disable the button.
Disclaimer: I have not tested the code above, just wrote it in one pass.
If you want the Generate button to be enabled as soon as the user presses a key, then you probably want to capture the keypress event on each input and the change event on each select box. The handlers could all point to one method that enables/disables the Generate button.
function updateGenerateButton() {
if (isAnyInputEmpty()) {
$("#generateButton").attr("disabled", "disabled");
} else {
$("#generateButton").removeAttr("disabled");
}
}
function isAnyInputEmpty() {
var isEmpty = false;
$("#input1, #input2, #select1, #select2").each(function() {
if ($(this).val().length <= 0) {
isEmpty = true;
}
});
return isEmpty;
}
$("#input1, #input2").keypress(updateGenerateButton);
$("#select1, #select2").change(updateGenerateButton);
The above assumes that your input tags have "id" attributes like input1 and select2.

Categories