i am facing an issue in javascript. i want to do user enter number of seconds in input field.
but the condition is that users can't enter number of seconds less than zero.
how can a make the code logic?
function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds">
<button onclick="sec()">Click</button>
</form>
what should i do? anyone help me?
Add your expectation about the input value as attributes on your input:
Specifically required min="0" would meet your needs.
function sec(){
//your code logic is here
console.log("number of seconds is not less than");
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds" required min="0">
<button onclick="sec()">Click</button>
</form>
With JavaScript you can convert your user's input to a Number then check its value with an equality condition.
E.g. you could fill out your sec() function like this:
function sec() {
const seconds_str = document.getElementById("seconds").value;
const seconds_num = parseInt(seconds_str, 10); // note: you could use parseFloat for decimal fractions
let result = "";
if (seconds_num < 0) {
result = "Is less than zero :'(";
} else {
result = "Is NOT less than zero :)";
}
console.log("User input = " + seconds_str);
console.log("Converted to integer = " + seconds_num);
console.log(result);
}
<form>
<label for="seconds">Number of seconds:</label>
<input type="number" id="seconds" name="seconds">
<button onclick="sec()" type="button">Click</button>
</form>
It would be up to you what you do when you detect a number less than zero. E.g. prevent form submitting, show an error message etc...
Related
I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.
Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
I want to book a ticket with a free offer, these are the rules:
One person can buy 1 or more tickets, but limited to 4
He can make a minumum offer of 1 euro, but no limit, for tickets. So if he buys 4 tickets the offer will be at least 4 euros.
The check (validate()) happens after page loading and on every change or keyup event. All seems ok when I increase tickets to buy from 1 to 2, the offer increase from 1 to 2, as expected.
My issue:
When I leave "ticket" (first input) on 2 and I increase the offer, it does not exceed 9, at 10 it set the input value back to same value that is in the ticket input.
Also, if I hold arrow up to increase number until 50, for example, it's ok.
What's wrong?
My code is:
validate();
$('.input_data').on('change keyup', validate);
function validate() {
control_tick = $("input[name='ticket']").val();
if ((control_tick < 1) || (control_tick > 4)) {
control_tick = 1;
$("input[name='ticket']").val(control_tick);
} else {
$("input[name='ticket']").val(control_tick);
}
control_off = $("input[name='offer']").val();
if (control_tick > control_off) {
control_off = control_tick;
$("input[name='offer']").val(control_off);
console.log('prezzo minore di ticket');
}
if (control_off => control_tick) {
$("input[name='offer']").val(control_off);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Ticket number (max 4):</label><br>
<input class="w3-input w3-center input_data" type="number" name="ticket" value="1" min="1" max="4" step="1">
<label>Offer €:</label>
<input class="w3-input w3-center input_data" type="number" name="offer" value="1" min="1" max="1000" step="1">
Cause
When you get the value of a field using .val(), that value is always of type string. Therefore when you compare the values using if (control_tick > control_off) {, you're comparing two strings, not two numbers. And in the rules of string comparison, "2" is considered to be "greater" than "10", because it compares each character one at a time, rather than the whole string, and clearly it regards "2" as greater than "1".
(Regarding holding the up arrow to 50, this will be ok because "50" (or rather, "5" is greater then "2" in string comparisons, just as it is in numeric comparisons. But if you hold it all the way to 100 it'll reset again - I'm sure you can work out why, by now.)
Solution
You need to parse your values as numbers before you attempt to compare them. Since these will always be whole numbers, we can use parseInt. This will ensure it does a numeric comparison instead.
See the demo below for a working example.
(Note also that removed the last if statement - apart from the slight syntax error (=> should be >=, although it doesn't cause a syntax error because it's valid, (but useless) as an arrow expression) it seemed redundant, because you're just populating the field with the same value you got from it a moment earlier. The else after the first if is also redundant for the same reason.)
validate();
$('.input_data').on('change keyup', validate);
function validate() {
control_tick = parseInt($("input[name='ticket']").val());
if ((control_tick < 1) || (control_tick > 4)) {
control_tick = 1;
$("input[name='ticket']").val(control_tick);
}
control_off = parseInt($("input[name='offer']").val());
if (control_tick > control_off) {
control_off = control_tick;
$("input[name='offer']").val(control_off);
console.log('prezzo minore di ticket');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Ticket number (max 4):</label><br>
<input class="w3-input w3-center input_data" type="number" name="ticket" value="1" min="1" max="4" step="1">
<label>Offer €:</label>
<input class="w3-input w3-center input_data" type="number" name="offer" value="1" min="1" max="1000" step="1">
Hello I want to create a custom error alert in HTML
here I want to custom in( required) and another for ( max and min number)
<div class="form-group">
<label for="durationdays">Days</label><br>
<input type="number" name="duration" max="5" min="1" class="form-control" style="width:50%" required oninvalid="InvalidMsg(this);" oninput="InvalidMsg(this);">
</div>
and this is a javascript code
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity
('Required');
} else if (textbox.validity.typeMismatch) {
textbox.setCustomValidity
('ONlY number');
} else {
textbox.setCustomValidity('');
}
return true;
}
I want if the user clicks on send button with empty value show this(Required)
and if enter letter value show (ONLY number)
and if enter less than 1 or more than 5 show (should be less than or equal 5)
You can use textbox.setCustomValidity(`Max: ${textbox.max} Min:${textbox.min}`); to get the min and max values, then it's possible to show the numbers. The other ones should work fine.
I've just started beginning to code in JavaScript (my first attempt at any so please be patient!), so have just set myself a simple project just to create a input box, and was hoping upon clicking the calculate button to generate a "Even" or "Odd" output that shows up below the box. But somehow I can't get anything to show up. Any ideas what I'm doing wrong?
function myFunction() {
// define var num
var num = document.getElementById("number").value;
//use of if function as number is odd or even (modulo = 0 or 1)
if (num % 2 === 0) {
document.writeIn("Even");
} else {
document.writeIn("Odd");
}
}
<table id="number">
Number: <input type="number" name="name">
<input type="button" onclick="myFunction()" value="Calculate"></table>
You need to take an input with type 'text' and an id of 'number'.
Then get this value of the input and assign to another element the result, because document.writeln does not work after the page is rendered by the user agent.
function myFunction() {
var num = document.getElementById("number").value;
document.getElementById("type").innerHTML = num % 2 ? "Odd": "Even";
}
Number: <input type="text" id="number">
<input type="button" onclick="myFunction()" value="Calculate">
<div id="type"></div>
I have this code in HTML:
<input type="number" step="0.1" class="form-group">
I want the user to be able to enter a 3-digit decimal number like 1.234 but step needs to be 0.1 and it throws an error and prevents the form from submitting.
I've already tried step="0.100" but the result was the same.
I also need to validate other inputs so I can't use no validate in the <form> tag.
What needs to be done?
I'd write a small customized built-in custom element doing just that:
class MyInput extends HTMLInputElement {
constructor(step = 0.1, value = '') {
super();
this.type = 'number';
this.step = this.getAttribute('step') || step;
this.value = this.getAttribute('value') || value;
this.addEventListener('input', (e) => {
this.value = parseFloat(this.value) + 0.034;
})
}
}
customElements.define('my-input', MyInput, { extends: 'input' });
let input = new MyInput(0.1, 1);
document.body.appendChild(input);
<!-- if you want to use declaratively: -->
<input is="my-input" step="0.1" value="2" />
<hr />
This definitely needs some tweaking, e.g. if the user types in the input, but this should serve you well as a starting point.
One thought is you could remove the step attribute, disable the +/- slider buttons, and implement your own +/- buttons. Then, when a user clicks those buttons, a JavaScript function is called that retrieves the value in the input area, converts it to a number, and performs the desired step.
You might run into precision issues with using a step like 0.1. In the below snippet I just fixed the number of decimal places to two.
function stepUp(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num + step).toFixed(2);
}
function stepDown(step) {
let num = Number(document.getElementById('value').value);
document.getElementById('value').value = (num - step).toFixed(2);
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
<button onclick="stepDown(0.1)">-</button>
<input id="value" type="number" value="0.00">
<button onclick="stepUp(0.1)">+</button>
You can use novalidate and write your own validation in js for other form fields
<form novalidate>
<input type="number" step="0.1" class="form-group" >
<button>submit</button>
</form>