How to clear text field automatically when enter minus value - javascript

`
<input type="number" id="qty">
<input type="button" onclick="add()" value="Add">
<script>
function add(){
qty = document.getElementById('qty').value
if(qty>0){
var tot = qty*25
document.write(tot)
}else{
qty = ""
alert("no")
}
}
</script>
'qty=""' is the correct way as mentioned on google. but not working for me.

Try
document.getElementById("qty").value = "";
and cast qty to number in your if
if(Number(qty) > 0)

Values of inputs are always string , try this one in your condition :
if(Number(qty)>0){
...
}

Use this below code to clear the input
qty.value = "";

The reason why qty = '' isn't working is that you've assigned the string value of the input to that variable. Setting it to an empty string won't make the value of the input change - you need to explicitly change the element's value.
So, a few things first:
It's often useful to cache your elements first.
Remove the inline JS and replace it with addEventListener and attach it to the button element (a more modern approach).
Use a <button> element instead of an <input type="button">
Assign the total to an element's text content/innerText instead of document.write for various reasons.
Then when the handler is called coerce the string value of the input to a number, and use that in the condition. If the number is less than zero assign an empty string to the input value.
// Cache the elements
const qty = document.querySelector('#qty');
const result = document.querySelector('#result');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', add);
function add() {
// Coerce the input value to a number
const val = Number(qty.value);
if (val > 0) {
// Instead of `document.write` assign
// the total to the text content of an element
result.textContent = val * 25;
} else {
// Set the value of the qty element to
// an empty string
qty.value = '';
console.log('no');
}
}
#result { margin-top: 0.5em; }
<input type="number" id="qty">
<button type="button">Add</button>
<div id="result"></div>

if you want to check in time when you enter a value (as I understood from the question), you must have a listener on <input type=" number" id="qty"> and event
'input'. qty.addEventListener('input', (e)=>{ // .... make your validation })

Related

Using Javascript, how to detect the value typed into a input box while it's being typed

I have this problem to solve
In this form a user types in a value. (Actually,
a scanner scans a number and virtually types it - without
sending extra keys like Enter)
I need to contantly check - while typing is going on - if the value in the input
box is a 8 digit number (starting with "4") and if it
is, fire the submit action.
I tried to log any changes. But the code below only logs changes after I leave the input box.
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" onChange="console.log(this.value);">
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
</form>
Is there a Javascript way to pass the value of the box to a function whenever a single letter is typed?
Note: While the form displays a "scan" button, the goal is to have that button automatically clicked as soon as 8 digits have been entered and been declared valid by a validator function.
It is generally not a good idea to use inline event handlers.
Actually, a scanner scans a number and virtually types it
So, as far as I understand you want to show the result of some scanning function that inputs values and check the input value. Looks like there's not really a need for a change handler. Here's a minimal reproducable example for a dummy scanning function. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function scan(i = 0) {
const inp = document.querySelector(`[name='boarding_id']`);
const showIt = document.querySelector(`#showIt`);
if (i < 1) {
inp.value = 4;
i += 1;
} else {
const nr = 1 + Math.floor(Math.random() * 9);
const currentValue = inp.value;
inp.value += nr;
}
if (i < 8) {
showIt.textContent = `Scanning ...`;
return setTimeout( () => scan(i + 1), 100)
}
showIt.textContent = `Done!`;
document.querySelector(`#scan`).removeAttribute(`disabled`);
}
function handle(evt)
{
if (evt.target.id === `scan`) {
evt.target.setAttribute(`disabled`, `disabled`);
return scan();
}
}
<input name="boarding_id" value="" width="600px" readonly>
<span id="showIt"></span>
<p><button id="scan">Scan</button></p>
const input = document.querySelector('input');
const demo_variable = document.getElementById('demo_variable');
input.addEventListener('input', updateValue);
function updateValue(e) {
demo_variable.textContent = e.target.value;
}
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" >
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
<p id="demo_variable"></p>
</form>
You can use the input event, which also triggers when editing happens without the keyboard (mouse drag/drop, context menu, other device...).
Use a regular expression to do the verification. You can access the form via the form property of the input element:
<input name="boarding_id" oninput="/^4\d{7}$/.test(this.value) && this.form.submit()">
It is however better practice to bind events not with HTML attributes, but with JS code. For that purpose give the form element an id attribute (like id="frm"), and then:
const form = document.getElementById("frm");
form.boarding_id.addEventListener("input", (e) => /^4\d{7}$/.test(e.target.value) && form.submit());
You can achieve this in multiple ways. I have shown one below
function myFunction() {
const userInput = document.getElementById("numberinput").value;
document.getElementById("displaynumber").innerHTML = "You typed: " + userInput;
}
function submtValue(value) {
const submitValue =document.getElementById("numberinput").value;
if(submitValue.length === 8) {
// do your validation
alert("Bingo..!!")
}
else {
alert("Minimum length required is 8")
}
}
<input type="number" id="numberinput" oninput="myFunction()">
<p id="displaynumber"></p>
<button type="submit" value="Submit" onclick="submtValue()">Submit</button>
You can add key event like onkeydown or onkeypress on input which will trigger everytime type inside input and once condition fulfilled submit form

Enable submit button if value greater or equal to the specified value

I'm trying to enable the submit button in the form only if the second text value is equal or greater than the first text box value. I have checked for the solution before posting. I don't know what I am missing. Please help me regarding the same.
I have added the JSfiddle code on which I worked changing
Form Code
<form method="post" action="order.php">
First Number
<input type="text" id="total1" />
<br>
Second Number
<input type="text" id="total2" />
<br>
<input type="submit" value="Submit" disabled title="Not Relevant">
</form>
Script
setInterval(function () {
if ($('#total1').val() >= ('#total2').val())
$(":submit").removeAttr("disabled");
else
$(":submit").attr("disabled", "disabled");
}, 1);
JSFiddle Code
Don't use setInterval to check the values. This will block the thread from doing anything else because you are basically creating an infinite loop.
You only need to know compare the values when you submit. Then either submit or prevent the submit from happening with Event.preventDefault().
let $form = $('form');
let $total1 = $('#total1');
let $total2 = $('#total2');
$form.on('submit', function(event) {
let val1 = Number($total1.val());
let val2 = Number($total2.val());
if (val1 < val2) { // If condition is NOT met.
event.preventDefault(); // Default submit from happening.
return false; // Stop function.
}
});
Additionally you can listen for the change event on the form when a value in one of the inputs has changed and check the values there. Then based on the evaluation set the disabled property in the input button.
let $submitButton = $(':submit');
$form.on('input', function(event) {
let val1 = Number($total1.val());
let val2 = Number($total2.val());
let isDisabled = val1 < val2; // Will return true or false.
$submitButton.prop('disabled', isDisabled);
});
If you want to compare numbers then change the input type to number. Otherwise you will be comparing strings.
<input type="number" id="total1" />
<input type="number" id="total2" />

Append number in textbox on submit

I want to add two zeros to any number entered in a textbox when submitted.
For instance, if i enter 34 in a textbox and click on submit, it should be saved as 3400.
Could this be done on the fly too?
Depends on what you want to do after the submit. Especially: Do you want to interpret this as a number and simply multiply by 100 (34 * 100) or do you want to simply append something to the value? ("34" + "00")?
In the first case you would do this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = parseInt(input.value) * 100;
}
</script>
In the second case this:
<input id="value" type="number" value="34"/>
<br>
<button onclick="submit()">Submit</button>
<script>
function submit() {
const input = document.getElementById("value");
const value = input.attributes.value;
input.value = input.value.toString() + '00';
}
</script>
A bit vague, but it sounds like you're looking for something like the following.
// Gather each element from the HTML, so you can access its input or update its display:
const input = document.getElementById('numberInput');
const button = document.getElementById('submit');
const display1 = document.getElementById('display1');
const display2 = document.getElementById('display2');
// Add a click event to the button, which gathers the text field value, ensures it's a number, and updates the display as requested:
button.addEventListener('click',() => {
const value = input.value;
// This if statement ensures that only numbers will be suffixed with be suffixed with two zeros:
if (isNaN(value)) {
alert('Please enter a valid number');
return;
}
// Update the display span's contents as requested. There are many ways of doing this. Here are a few;
// Here I'm taking the submitted value, and nesting it inside a string, alongside the two zeros. In cases of Infinity or .100, the result will still be the input suffixed with two zeros:
display1.innerHTML = `${value}00`;
// This method, on the other hand, will simply move the decimal to columns:
display2.innerHTML = value * 100;
});
<p>
Display 1: <span id="display1"></span>
</p>
<p>
Display 2: <span id="display2"></span>
</p>
<input type="text" id="numberInput">
<button id="submit">Submit</button>
You could always set an event listener that changes the number on exit of the form element, so something like this:
document.addEventListener('DOMContentLoaded', watchNums);
function watchNums() {
document.removeEventListener('DOMContentLoaded', watchNums);
Array.from(document.getElementsByClassName('number')).map(
number => {
number.addEventListener('blur', _ => {
number.value = parseInt(number.value) * 100;
})
}
)
}
<body>
<form action="/endpoint.htm" method="POST">
<input type="number" name="number-input" class="number">
<input type="number" name="other-number-input" class="number">
<button type="submit">Submit Numbers</button>
</form>
</body>

Comparing form input and span value for keyup function

I have a form that lists a remaining quantity of a product and below it an input field that lets you put a quantity into the form to submit for purchase.
I have the remaining quantity wrapped in a span with an ID.
On keyup, I want to compare the value of the span with the input entered into the field.
If the input is greater than the value in the span, on keyup, I want to change the value of the input to 0 or the equivalent of the span ID value.
Here is my javascript I am trying to use to accomplish this:
<script>
$(document).ready(function () {
document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);
function Qty_check(){
var QTY1check = document.getElementById('one_and_done_stool_QTY_check').value;
var QTY1remain = document.getElementById('one_and_done_stool_QTY_remain').innerHTML;
if (QTY1check.value > QTY1remain.innerHTML)
alert("NOPE");
{document.getElementById("one_and_done_stool_QTY_check").value = 0;}
};}
</script>
And here is the html:
<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">
Your main issue is in this line:
document.getElementById('one_and_done_stool_QTY_check').keyup(Qty_check);
You can rewrite:
document.getElementById('one_and_done_stool_QTY_check').onkeyup = Qty_check;
or you may use directly the input event:
document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);
or the jQuery way:
$('#one_and_done_stool_QTY_check').on('input', Qty_check);
The snippet:
document.getElementById('one_and_done_stool_QTY_check').addEventListener('input', Qty_check);
function Qty_check(e) {
var QTY1check = +document.getElementById('one_and_done_stool_QTY_check').value;
var QTY1remain = +document.getElementById('one_and_done_stool_QTY_remain').textContent;
if (QTY1check > QTY1remain) {
console.log("NOPE");
document.getElementById("one_and_done_stool_QTY_check").value = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="one_and_done_stool_QTY_remain">2</span>
<input id="one_and_done_stool_QTY_check" type="text" name="one_and_done_stool">

Find the Least count number and then divide that number to specific remaing

I am trying to check each value of text box value as a localstorage id and get the specifiv value of that id and then check that value is equal to or greater then a specific value in my example the value local storage's Total_thrisholdvalue1 value
In this example the if condition works
Expecting some thing in else condition
My problem is while checking if the value is not grater then or equals to then on else condition by using the value of text box's on each condition it should find least number by using the above textbox value as the localstorage id as it is doing in if condition then divide the number for the remaining localstorage data value and check if the value match's the Total_thrisholdvalue1 if matches then alert that value else eliminate another most least untill the value is equal to or greater then Total_thrisholdvalue1
JS:
localStorage.setItem('Total_thrisholdvalue1','4');
localStorage.setItem('A9AH98','3');
localStorage.setItem('16B9BH','2'); localStorage.setItem('CC9GHF','4');
localStorage.setItem('A9D9G5','5');
$(".candidateid").each(function () {
var data = $(this).val();
var candidates_count = localStorage.getItem(data);
var Total_thrisholdvalue = localStorage.getItem('Total_thrisholdvalue1');
if (candidates_count >= Total_thrisholdvalue) {
alert(data );
} else {
}
});
Html:
<input type="text" value="A9AH98" class="candidateid">
<input type="text" value="16B9BH" class="candidateid">
<input type="text" value="CC9GHF" class="candidateid">
<input type="text" value="A9D9G5" class="candidateid">
The values retrieved from localStorage are strings, so the > operator won't work as you might expect. Parse them to ints first:
var candidatesCount = parseint(localStorage.getItem(data), 10);
var totalThresholdvalue = parseint(localStorage.getItem('Total_thrisholdvalue1'), 10);
if (candidatesCount > totalThresholdvalue) {
// etc.
}

Categories