How to enabled button, when the actual amount entered
lets say i have 100 minimum and 200 maximum
i want when user enters amount below 100 error comes actual amount needed and button reamins dsiabled
when user enters more than 200 do the same echo error
user has to enter 100 and above but not exceed maximum
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#Textfield').keyup(function(){
var textBox = $('#Textfield').val();
if((textBox >= 100) || (textBox <= 200) ){
$('.disabledButton').prop("disabled", false);
} else {
$('#error').text('actual amount needed');
return false;
}
});
</script>
There's a number of reasons your code is not working:
.val() is always text, so you are (would be) comparing "15" with 100 and 200 and it would pass, convert to an integer
you start with the button disabled, then (assuming everything else is working ok) you enable it, but never disable it again if the value changes again
same for the #error text, you don't clear it when the value is valid
The main issue is:
if((textBox >= 100) || (textBox <= 200) ){
if the textbox value is greater than 100 OR it's less than 200, well, all values follow this rule: eg 1 is less than 200, so passes, 3000 is more than 100, so passes.
This should be
if((textBox >= 100) && (textBox <= 200) ){
Giving updated snippet:
$('#Textfield').keyup(function() {
var textBox = $('#Textfield').val() * 1;
if ((textBox >= 100) && (textBox <= 200)) {
$('.disabledButton').prop("disabled", false);
$('#error').text('ok');
} else {
$('.disabledButton').prop("disabled", true);
$('#error').text('actual amount needed');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
If you are using html 5, you don't need JavaScript. The best way to do this is to set this field to a number, like
<input type="number" min="100" max="200" placeholder="value in 100-200" id="Textfield" />
By setting min and max values, the form will not submit if the value in this field is not in that range
$('#Textfield').on('keyup',function(){
//every time a key is pressed we count the total number of characters in the field
var charLength = $(this).val().length;
//if they are equal to or above 100 and equal to or below 200 we disable the disabled button property else we disable the button again
if(charLength >= 100 && charLength <= 200){
$('.disabledButton').prop('disabled',false)
}else{
$('.disabledButton').prop('disabled',true)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<input type="text" id="Textfield">
<button type="submit" class="disabledButton" disabled>Submit</button>
<p id="error"></p>
</form>
EDIT
Sorry, I guess I kinda just glossed over the question. Here's your working code))
<form>
<input type="text" />
<button type="submit" disabled>Submit</button>
<p id="error" style="color: red"></p>
</form>
<script>
const input = document.querySelector('input');
const button = document.querySelector('button');
const error = document.querySelector('#error');
const minVal = 100;
const maxVal = 200;
const setError = (current) => {
const message = `Please enter between ${minVal} and ${maxVal}. You entered ${current}`;
error.innerText = message;
error.style.display = 'block';
};
const hideError = () => {
error.style.display = 'none';
};
input.addEventListener('keyup', () => {
const enteredValue = parseInt(input.value, 10);
if (enteredValue >= minVal && enteredValue <= maxVal) {
button.disabled = false;
return hideError();
}
setError(enteredValue);
button.disabled = true;
});
</script>
previous edit: Edited to add dynamic error message
<form>
<input type="text" max="200" />
<button type="submit" disabled>Submit</button>
<p id="error" style="color: red"></p>
</form>
<script>
const input = document.querySelector('input');
const button = document.querySelector('button');
const error = document.querySelector('#error');
const minChars = 10;
const setError = (length) => {
const message = `Please enter ${minChars - length} more character(s).`;
error.innerText = message;
error.style.display = 'block';
};
const hideError = () => {
error.style.display = 'none';
};
input.addEventListener('keyup', () => {
const enteredLength = input.value.length;
if (enteredLength >= minChars) {
button.disabled = false;
return hideError();
}
setError(enteredLength);
button.disabled = true;
});
</script>
Related
I hope to cancel the disabled property of btn when there is a value in the input box, and increase disabled when the input box has no value,
but I have encountered a situation, when I delete the value in the input box, why the button still does not increase the disabled?
let inputDOM = document.querySelector('.input');
let BtnDOM = document.querySelector('.btn');
inputDOM.addEventListener('input', function() {
console.log(inputDOM.value)
if (inputDOM.value >= 0) {
BtnDOM.removeAttribute("disabled")
} else if (inputDOM.value == "") {
BtnDOM.setAttribute("disabled", "")
}
});
<input type="number" class="input">
<button class="btn" disabled>Enter</button>
let inputDOM = document.querySelector('.input');
let BtnDOM = document.querySelector('.btn');
inputDOM.addEventListener('input', function() {
console.log(inputDOM.value)
if (inputDOM.value.length > 0) {
BtnDOM.removeAttribute("disabled")
} else if (inputDOM.value.length <= 0 ) {
BtnDOM.setAttribute("disabled", "true")
}
});
<input type="number" class="input">
<button class="btn" disabled>Enter</button>
I have an Virtual keyboard with Javascript the keyboard is typing in two inputs after reached maxlength it is focusing to second input. my problem is when i want to type in first input i should clicked to first input to focus it than typing with keyboard numbers
My question is How i can typing using this keyboard without clicking inside input, the first input should start typing immediately after i clicked on the buttons numbers
const maxLength = 7;
const firstInput = document.querySelector("#pin");
const secondInput = document.querySelector("#key");
const changedEvent = new Event("change")
let activeInput;
firstInput.addEventListener("focus", (event) => {
activeInput = event.target;
});
firstInput.addEventListener("change", (event) => {
console.log("i'm changing!");
if (firstInput.value.length >= maxLength) {
activeInput = secondInput;
secondInput.focus();
}
});
secondInput.addEventListener("focus", (event) => {
activeInput = event.target;
});
function resetNumber() {
if (!activeInput) {
console.log("pin");
return;
}
activeInput.value = "";
}
function setNumber(number) {
if (!activeInput) {
console.log("pin");
return;
}
activeInput.value = activeInput.value === number ? "" : (activeInput.value += number);
// manually tell the input that it has changed, so that the event listener defined above gets called. this usually only will happen with actual keyboard input
activeInput.dispatchEvent(changedEvent);
}
<button onclick="resetNumber()">Reset</button>
<button onclick="setNumber(0)">0</button>
<button onclick="setNumber(1)">1</button>
<button onclick="setNumber(2)">2</button>
<button onclick="setNumber(3)">3</button>
<button onclick="setNumber(4)">4</button>
<button onclick="setNumber(5)">5</button>
<button onclick="setNumber(6)">6</button>
<button onclick="setNumber(7)">7</button>
<button onclick="setNumber(8)">8</button>
<button onclick="setNumber(9)">9</button>
<br />
<input type="text" id="pin" />
<input type="text" id="key" />
<button id="reset" onclick="resetNumber()">Reset</button>
<br />
<input type="text" id="pin" />
<input type="text" id="key" />
<script>
const maxLength = 7;
const firstInput = document.querySelector('#pin');
const secondInput = document.querySelector('#key');
const resetBtn = document.querySelector('#reset');
for (let i = 9; i >= 0; i--) {
const numBtn = document.createElement('button');
numBtn.className = 'number';
numBtn.innerText = i;
resetBtn.parentElement.insertBefore(numBtn, resetBtn.nextSibling);
}
const numberBtns = document.querySelectorAll('.number');
const resetNumber = () => {
firstInput.setAttribute('value', '');
secondInput.setAttribute('value', '');
};
const setVal = (e) => {
const num = parseInt(e.target.innerText, 10);
if (firstInput.value.length <= maxLength) return firstInput.setAttribute('value', firstInput.value + num);
secondInput.setAttribute('value', secondInput.value + num);
};
numberBtns.forEach((btn) => btn.addEventListener('click', setVal));
</script>
I want to get input from user, multiply it by 1.3 for example and output to window instantly, like as user types function is executing and displaying in it in HTML instantly. How do it do it?
Here my code
function calc() {
amount = document.getElementById("amount").value;
num2 = 1.3;
document.getElementById("result").innerHTML = amount * num2;
return result;
}
<input id='amount', type="text" >
<button onclick="calc()"> Buy Now! </button>
<p> Result is: <br>
<span id = "result"> </span>
<input type="text"onkeyup="calc()">
First off, you got some invalid HTML:
What's that comma?
<input id='amount', type="text" >
Attributes don't need any separator — just put a space:
<input id='amount' type="text" >
Getting rid of pointless spaces, a cleaner HTML fragment follows:
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Now, let's try to list some options:
The keydown and keypress events won't work because they're fired before value changes.
The keyup event, as suggested #Dmitri Usanov, will work only partially: it is called when the key releases (not as soon as the text is updated) and if you e.g. paste by right-clicking then it won't fire.
The input is the solution. Note that it requires HTML5.
Working demo:
function calc() {
// Let's convert the input text to a number.
const amount = +document.getElementById("amount").value;
// The number to multiply by.
const num2 = 1.3;
// The number of decimal places we wish to truncate at.
const precision = 2;
const scale = 10 ** precision;
return Math.round(amount * num2 * scale) / scale;
}
window.addEventListener("load", () => {
const outputSpan = document.getElementById("result");
document.getElementById("amount").addEventListener("input", () => {
outputSpan.innerHTML = calc(this.value);
});
});
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Try this
function calc(isEsc) {
const num2 = 1.3;
let result = document.getElementById("result"),
amount = document.getElementById("amount");
if (isEsc) {
result.innerHTML = 0;
amount.value = '';
} else {
result.innerHTML = amount.value * num2;
}
}
document.onkeyup = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Escape" || evt.key == "Esc");
} else {
isEscape = (evt.keyCode == 27);
}
calc(isEscape);
};
<input type="text" id="amount" />
<span id="result">0</span>
How to check value in input using loop for with onchange using javascript ?
first, When user fill char. It's will be show Your Price must be a number.
And if user fill number less than 1.5 It's will show Your Price must be at least $1.50 USD.
and click Add more link to add input.
I try my code , but not work, how can i do that ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form onsubmit="return checkform(this);">
Add more
<div id="p_scents_price">
<p>
<label>
<input type="text" class="price" id="price0" size="20" name="price[]" onchange="myFunction0()"/><p id="demo0"></p>
</label>
</p>
</div>
<input type="submit" name="submit" value="OK">
</form>
<script>
var list = document.querySelectorAll(".price");
for (z = 0; z < list.length; ++z) {
function myFunction'+z+'() {
var x = document.getElementById("price'+z+'").value;
var y = isNaN(x);
if(y === true)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be a number.";
}
else
{
if(x < 1.5)
{
document.getElementById("demo'+z+'").innerHTML = "Your Price must be at least $1.50 USD.";
}
else
{
document.getElementById("demo'+z+'").innerHTML = "";
}
}
}
}
}
</script>
<script>
$(function() {
var scntDiv = $('#p_scents_price');
var i = 1;
$('#addScnt_price').live('click', function() {
$('<p><label><input type="text" class="price" id="price'+i+'" size="20" name="price[]" onchange="myFunction'+i+'()"/>Remove<p id="demo'+i+'"></p></label></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt_price').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
}
return false;
});
});
</script>
I want my form submit button to be disabled/enabled depending on if the form is completely filled.
When the inputs are filled, the disabled button changes to enabled. That works great.
But I would like it to disable the button when an input gets emtied.
This is my script:
<script type="text/javascript" language="javascript">
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
}
</script>
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.
Just add an else then:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
Put it inside a table and then do on her:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";
function checkForm() {
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>JavaScript</title>
</head>
<body>
<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>
<form onkeyup="checkForm()" autocomplete="off" novalidate>
<input type="text" name="fname" placeholder="First Name" required><br><br>
<input type="text" name="lname" placeholder="Last Name" required><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</body>
</html>
Example explained:
We create a variable to store all the input elements.
var inp = document.getElementsByTagName("input");
We create another variable to store the button element
var btn = document.getElementById("btn");
We loop over the collection of input elements
for (var i = 0; i < inp.length; i++) {
// Code
}
Finally, We use the checkValidity() method to check if the input elements
(with a required attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
You can enable and disable the submit button based on the javascript validation below is the validation code.
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>