Best way to replace empty userinput with 0 - javascript

I have three user inputs which take any number. If a user leaves an input empty then clicks the submit button I would like that input to return 0.
What would be the best way to handle this?
I have created an if statement that individually looks for if input 1 or input 2 or input 3 is empty, but what if input 1 and 2 are empty or if input 3 and 1 are empty, this will lead to quite a long if statement
I wanted to know what would be the best way to go about solving this?
*.js
If( hours === 0 ){
hours = 0
}else if ( minutes === 0 ){
minutes = 0
}else if ( seconds === 0 ){
seconds = 0
}
// more if statement with different combination of minutes seconds and hours being 0

Create a function that does that work and then pass the input value to the function. Call the function for each input.
function checkInput(input){
if(!input.value){
input.value = 0;
}
}
// Find all the <input> elements and loop thorugh them
document.querySelectorAll("input").forEach(function(element){
checkInput(element); // Call the checkInput function and pass the current input
});
<input>
<input>
<input>
You can also avoid the JavaScript completely by using more precise HTML:
<input type="number" required value="0">
<input type="number" required value="0">
<input type="number" required value="0">

First off, You can make sure the user enters a value in the input using the required attribute.
<input type="text" required>
Also If it's inserting into the database, you just need to change the column data type which the value is inserting, to a data type of INT. That way the default is always going to be zero.
But if you still need to check...
if(#inputid.value === ""){
#inputid.value = 0;}
Also remember to get all the inputid using querySelectorAll("#inputid")
Then make it an array using var id = Array.from();
Then loop through id using foreach to check the if statement.

Related

How to get input text value and push it into array in jQuery?

I have a checkbox function that when user checked on one of the specified value it will display an input text that will ask user to input a number and there will be another input text based on the number that user has put.
This is the example output
if user enter 2, there will be 2 input text will appear.
Now I have problem with pushing the tier name into my temp array. Below is what I have tried. But I'm still not getting any value inside my temp.
< script >
let temp = [];
$(document).ready(function() {
$("#staff_tier").change(function() {
let m = $(this).val();
$('#tier').html('');
var tier_num = 1;
for (var i = 0; i < parseInt(m); i++) {
$('#tier').append(`<label><b><span style="color:#e60000;">*</span><i> Tier (${tier_num++})</i></b></label><br>
<div class="input-group-prepend">
<input class="from-control" type="text" placeholder="" id="tier_name" required >
</div>
`);
temp.push($('#tier_name').val());
}
console.log(temp);
});
}); <
/script>
What I'm trying to achieve is I want the input value got push into my temp. How do I fix this problem ?
There are a few things that you got wrong:
You're having a loop, but you always print an input field with the same id: <input id="tier_name">
You listen for a change on #staff_tier, but then you simply print some html code that is static. You need (after fixing #1) to add pieces (input fields), that also have listeners so that when they change - you get their value
After having separate inputs with listeners, you can have a global place where you store their values.
At this point, it would be much easier of you add any tiny reactive library (no need for React or anything huge). Search online, but any of the smaller ones would do the trick: Sinuous, Reef or even Preact.

Dynamically check value and display alarm popover

I want to validate user input so he only provides numbers from a certain range with 0,5 steps. But I want my website to do it every time user swaps to another input form, not after he sends the data to my view. Can you give a hint of how should it be done? I don't know Javascript but I know there is onfocusout DOM event. Is it correct approach to use it, check whether or not value is valid and display an alarm based on that?
In general, there's no problem using onfocusevent.
Here's a hint on how to do this:
Create the input field
Add the onfocusout event handler and assign it a JavaScript function
Define the JavaScript function responsible for the validation process (which is, the same function we talked about in step 2)
This function takes the value inside the field and compares it, if it's not inside the range you desire then you can show an alarm or something like this.
I made a demo that doesn't involve alarming the user but instead it colors the border with either green or red, when you get desperate pay it a visit:
<input type="number" id="field1" onfocusout="validateField(0, 100, 'field1')"/><br/><br/>
<input type="number" id="field2" onfocusout="validateField(200, 300, 'field2')"/><br/><br/>
<input type="number" id="field3" onfocusout="validateField(400, 500, 'field3')"/><br/><br/>
<script>
function validateField(min, max, id) {
const value = document.getElementById(id).value;
if (value < min || value > max) {
document.getElementById(id).style.borderColor = "red";
}
else {
document.getElementById(id).style.borderColor = "lime";
}
}
</script>

Do not show default value of the input field

I have an input field
<input id='spe_count' type="text" placeholder="number" class="form-control" data-original-title="" title="">
and as I need it to be by default with value -1 I am assigning it with jQuery
$("#spe_count").val('-1');
And I get this input field and see this value -1 inside it, but what I want is that this input is with value -1, but on the page it would be empty or with placeholder.
And when I am changing values, I'd like to do so, that deleting value, emptying the box means that it is default value -1 (not typing minus one , but simply deleting all the values mean this is minus one)
Is this possible?
#("#spe_count").click(function(){
var value= $(this).val();
if(value.length < 1){
$(this).attr("value", -1);
}
});
The above code will serve your purpose.

Javascript Validation for Positive Integer Only Input

I have two text boxes, in it will only be allowed positive integers.
If any alphabetical values or any other characters (e.g. %$&*£") are entered, an error message should be displayed and the values must not render a table.
<input type="button" value="total" name="B3" onclick="powerOf();">
This line allows for calculation to be made, how can this validation stop this from happening
when the incorrect values are entered?? As of now minus numbers are calculated and entering alphabets produces an empty table which is not quite what I was going for:
(no1== no1.match(/^-\d+$/) ? alert("First number must be positive"): no1 = no1 ? no1 : 0);
(no2== no2.match(/^-\d+$/) ? alert("Second number must be positive"): no2 = no2 ? no2 : 0)
var range1 = parseInt(no1);
var range2 = parseInt(no2);
Any ideas?
Note: you can do this simply via HTML5 form validation:
<input type="number" min="1">
Then you won't be able to submit the form unless the entered value is a number higher than 1. This only seems to work in Chrome though.
To answer your question, what you're looking for is event.preventDefault(). If you change your onclick function to:
<input type="button" value="total" name="B3" onclick="powerOf(event);">
then you can run event.preventDefault() in the powerOf function, and when you run that, the event will be "cancelled". For example:
function powerOf(event) {
if (!/^\d+$/.test(document.getElementById('input-1').value)) {
event.preventDefault();
}
}
that will cancel the click event when the value of the input with id="input-1" is not digits only.
See this demo for a working example.

Prevent changing the Textbox value in Jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
disable textbox using jquery?
How to prevent changing a textbox value using jquery in document.getElementsByName().
There is an option like this.
document.getElementById("Quantity").defaultValue;
Is there any option to stop my textbox's value from changing in document.getElementsByName().
After my alert, I want to make the value of textbox stay the same when the condition is not matched.
My code:
$(function () {
$('input[name=Quantity]').blur(allownumbers);
});
function allownumbers() {
var elements = document.getElementsByName('Quantity');
for (var i = 0; i < elements.length; i++) {
if (elements[i].value == '' || elements[i].value < 1) {
alert('Please enter a valid value');
return false;
}
else if (elements[i].value > 100) {
alert('There is no enough inventory for this product to fulfill your order');
return false;
}
}
return true;
}
<input id="Quantity" type="text" name="Quantity"/>
Any suggestions.
EDIT :
I tried using this code.
$("#textbox1").removeAttr("disabled");
If I enter 200. The alert appears and the textbox becomes disabled and so I cant even re-enter the correct value in textbox. How to bring back the defaultvalue of my textbox. ?
you would store the original value in a variable or hidden field then replace the value if the update failed. If the range is known when the page loads, you can use a range validation.
An alert is generally too obtrusive for a validation on blur.
Like adamb posted, you can just disable the input. The alternative is to set an attribute on the input (maybe defaultval='the default') and replace the value of the input with the defaultval attribute.
In your example, it may be best for your customers to have the input actually be set to the limit. For instance, you have a condition of 100 being the max, so if someone puts in a bigger number, say 200, it will change the box to the max possible, 100.

Categories