Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to implement code in that if any of input value entered is zero then disable button otherwise enable. Its working fine when input value entered is zero but after I entered value other then zero it still disabled not enabling I am using counter and I have total nearly 40 text field to check so I am using input type with each statement.
following is fiddle which is I am implemented.
You need to initialize count value every time ,because you want to check that value is the statement of having 0 value or not.Put it that setting value in .change() function
$(document).ready(function() {
$('input').change(function() {
var count = 0;
$("input").each(function() {
if($(this).val() == "0")
{
count = 1;
}
});
if(count == 0)
{
$("#submitBtn").removeAttr("disabled","disabled");
}
else
{
$("#submitBtn").attr("disabled","disabled");
}
});
});
$(document).ready(
function() {
$('input').change(function() {
// $("input").each(function() {
if($(this).val()==0)
{
$("#submitBtn").attr("disabled","disabled");
console.log("Disable");
}
else{
$("#submitBtn").removeAttr("disabled","disabled");
console.log("Enable");
}
// });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<input type = 'number' class="inputBox" >
<button id="submitBtn" >Submit</button>
Here you go. This works on multiple fields as well
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == 0) {
empty = true;
}
});
if (empty) {
$('#submit').attr('disabled', 'disabled');
} else {
$('#submit').removeAttr('disabled');
}
});
})()
/* instead of form we can use the IDs of certain fields only. In case not all fields are mandatory */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Enter number<br />
<input type="number" id="user_input" name="number" /><br />
<input type="number" id="user_input2" name="number" /><br />
<input type="submit" id="submit" value="submit" disabled="disabled" />
</form>
<div id="test">
</div>
In your fiddle, you have all of your inputs of type number. When first onchange event happens, it evaluates all of the inputs. Even if some the inputs do not have values, because they are of type number, their default value is 0. And your code is working at first because you are not checking inputs until the first onchange event fires.
You can check this if you enter all input fields with a non-zero value, then your button should be enabled. If you remove a value from one of them, it should be disabled again.
Pure HTML version. It won't put a disabled attribute on the button but it will throw a native error if you try to submit the form if any input has a value less than 1. Good to put that min property on there in any case.
<form>
<input type="number" min="1"/>
<input type="number" min="1"/>
<input type="number" min="1"/>
<button type="submit">submit</button>
</form>
It working for me :
HTML:
<input type="text" class="form-input" id="input" >
<button id="fbtn">Submit</button>
JQuery:
<script type="text/javascript">
$('#input').on('keyup',function(){
var val = $('#input').val();
if (val == 0) {
$("#fbtn").attr("disabled","disabled");
}else{
$("#fbtn").removeAttr("disabled","disabled");
}
});
</script>
You should add validation for input field. i mean accept only number etc.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm sure someone has asked this question before and i have already seen code that works fine with input type text, but i want to know if it's possible to check if any Input, Textarea AND Radio Buttons are empty in a form, then disable the submit button.
I want to make sure the user fills out ALL the required fields in the form, which include textarea, text and radio buttons. Is there any way i can do that?
If you aren't using too many input fields i'd recommend something as follow:
<form id="myFormId">
<input type="text" name="d1" class="dat" placeholder="test">
<input type="text" name="d2" class="dat" placeholder="testie">
<textarea id="textareaARE"></textarea>
<textarea id="txt"></textarea>
<input type="radio" name="Rad" value="test">
<input type="radio" name="cad" value="tstt">
<input type="text" name="d3" class="dat" placeholder="testie">
<input type="text" name="d4" class="dat" placeholder="testie">
<input type="text" name="d5" class="dat" placeholder="testie">
<input type="text" name="d6" class="dat" placeholder="testie">
<input type="text" name="d7" class="dat" placeholder="testie">
<input type="text" name="d8" class="dat" placeholder="testie">
<input type="text" name="d9" class="dat" placeholder="testie">
<button id="submit" type="button">Submit</button>
</form>
function checkInputFields() {
$('#submit').on('click', function() {
let input = 0;
let radio = 0;
let text = 0;
$('#myFormId input[type="text"]').each(function(key, inputField){
if($(inputField).val() === '') {
//do nothing, or exit script early, whatever floats your boat
} else {
input++;
if (input === $('#myFormId input[type="text"]').length) {
input = true;
}
}
});
$('#myFormId input[type="radio"]').each(function(key, inputButton){
if(!$(inputButton).is(':checked')) {
//do nothing, or exit script early, whatever floats your boat
} else {
radio++;
if (radio === $('#myFormId input[type="radio"]').length) {
radio = true;
}
}
});
$('#myFormId textarea').each(function(index, textAr) {
if ($(textAr).val() === '') {
//do nothing, or exit script early, whatever floats your boat
} else {
text++;
if (text === $('#myFormId textarea').length) {
text = true;
}
}
});
console.log(input, radio, text);
if (input === true && radio === true && text === true) {
$('#submit').attr('type', 'submit');
$('#submit').click();
} else {
console.log('You forgot to fill out every required field my man.');
}
});
}
//document.read(function(){});
$(function() {
checkInputFields();
});
The reason I am saying: "If you aren't using too many input fields" is because your code will loop through all the elements in the form and then goes through every input or textarea. If these numbers were to be huge it could have performance issues (but that would probably mean you're doing something wrong).
EDIT: I made it such way that you do not need the submit button to become disabled. The moment your user clicks on it, it will either redirect the user (if everything is filled out correctly) or keep the user on the same page, in which you can decide what kind of error you would like to throw.
EDIT: I made a mistake, in which it would always result to true if the last value of an input field were to be inserted. I fixed it.
Yes, it is possible (the way of do this will depends on the framework you're using, so I recommend to read the docs).
One way is binding the value of your fields, and check if these values are empty (as I said, the way of doing this will depend on the framework).
Doing with the old and good Jquery:
<form id="sign-in">
<div class='input-group'>
<label for="username">Username</label>
<input id="username" type="text" />
</div>
<div class='input-group'>
<label for="password">Password</label>
<input id="password" type="password" />
</div>
<div class='submit-btn'>
<button type="submit" class="btn btn-success" value="Sign in" disabled="disabled">Sign in</button>
</div>
</form>
And, after doing your form, just listen to your inputs, checking if the user typed something in:
$(document).ready(function() {
$('.input-group input').on('keyup', function() {
var is_empty = false;
$('.input-group input').each(function() {
is_empty = $(this).val().length == 0;
});
is_empty ? $('.submit-btn button').attr('disabled', 'disabled')
:
$('.submit-btn button').attr('disabled', false);
});
});
Since onkeyup event is dispatched when the users type something and stop, you can listen to this action. If is_empty equals true your input fields continue disabled, else not.
Check this fiddle for testing: https://jsfiddle.net/s4bjqer5/
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have simple html form (2 text fields & 1 selection set & save button)
i want to set this button to disable till the text fields and selection set have values, if these fields have values button become active when clicked it show alert message (I need this using JavaScript)
Try this one to enable the button if the two fields have values through JavaScript using the querySelector() method for the DOM manipulation.
var submitBtn = document.querySelector('#submitBtn');
var nameInput = document.querySelector('#nameInput');
var addressInput = document.querySelector('#addressInput');
var myOption = document.querySelector('#mySelect');
function validateInputs() {
if (nameInput.value && addressInput.value && myOption.value)
submitBtn.disabled = false;
else
submitBtn.disabled = true;
}
function showData(){
alert("Data is :"+nameInput.value);
}
<form>
<label for="nameInput">Name</label>
<input id="nameInput" type="text" name="name" onkeyup="validateInputs();" required>
<label for="addressInput">Address</label>
<input id="addressInput" type="text" name="address" onkeyup="validateInputs();" required>
<br><br>
<select onchange="validateInputs();" id="mySelect">
<option disabled selected value> -- select an option -- </option>
<option>New York</option>
<option>Chicago</option>
</select>
<br><br>
<button id="submitBtn" onclick="showData();" disabled>Submit</button>
</form>
This worked for me.
var errors = 0;
$('#idOfYourSubmitButton').prop('disabled', true); //Make your button disabled
$('#idOfYourFirstTextField').keyup(function(){ //triggered when keyup is detected on the text field
if($(this).val().length < 0) { //Check if Text field is empty
errors += 1; //add an error
}
else { //if text field is not empty
errors -= 1; //remove error
}
);
$('#idOfYourSecondTextField').keyup(function(){ //triggered when keyup is detected on the text field
if($(this).val().length < 0) { //Check if Text field is empty
errors += 1; //add an error
}
else {
errors -= 1; //remove error
}
);
if(errors <= 0) { //check if there are any errors
$('#idOfYourSubmitButton').prop('disabled', false); //remove disabled from the button
}
If you want to go the jQuery route, you could do it this way
You'll notice that if you do it this way, the button will disable again if any of the form info is deleted.
$('.js-get-info').on('mouseover keyup', (event) => {
if ($('.js-name').val() && $('.js-age').val() && $('[name=sex]:checked').val()) {
$('.js-submit').prop('disabled',false);
} else {
$('.js-submit').prop('disabled',true);
}
})
<!doctype html>
<html>
<head>
</head>
<body>
<form class='js-get-info'>
<input class='js-name js-input' placeholder='Name'>
<br>
<input class='js-age js-input' placeholder= 'Age'>
<br>
<label for='female'>Female</label>
<input type='radio' class='js-input js-sex-input' id='female' name='sex'>
<label for='male'>Male</label>
<input type='radio' class='js-input js-sex-input' id= 'male' name='sex'>
<br>
<input type='submit' class='js-submit' disabled>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='index.js'></script>
</body>
</html>
Here's an example of how you could achieve this with JavaScript. This may not be the best way to do this, but as an example it's a good place to start.
http://plnkr.co/edit/LLg9DklQFMFFB7XRzX7t?p=info
<!DOCTYPE html>
<html>
<head>
<style>
button#submit:disabled {
color: #bbb;
background-color: #ddd;
}
</style>
</head>
<body>
<h1>Form Example</h1>
<form>
<div>
<label>Input 1</label>
<input type="text" required="required" name="input1" id="input1" onkeyup="validate()" />
</div>
<br />
<div>
<label>Input 2</label>
<input type="text" required="required" name="input2" id="input2" onkeyup="validate()" />
</div>
<br />
<button id="submit" type="submit" disabled>Submit</button>
</form>
<script>
var button = document.getElementById('submit');
button.disabled = true;
function validate() {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
if (input1.value && input2.value)
button.disabled = false;
else
button.disabled = true;
}
</script>
</body>
</html>
Note: The disabled attribute on the button element and the button.disabled = true are redundant. You should be able to remove either and the example still work as expected.
EDIT
If you want to use the onblur and onfocus events instead of onkeyup, the only change from the above example is to mark these attributes as using the validate function like so:
<input type="text" required="required" name="input1" id="input1" onblur="validate()" onfocus="validate()" />
See this updated plunk for the full example: http://plnkr.co/edit/lc0vO8kBnhMyKD3xgPxo?p=info
Please note the behavior here, however, is such that if you type in the first input, then move to the second, the submit doesn't become enabled until you leave the second. Similarly in reverse, if the user removed what they provided in either box after having been validated in this setup, if they did not trigger the blur event, the submit button would remain enabled. This, I think, could be confusing, and really suggests that you should also have onclick on your submit button if this is really what you need. This is the reason I initially suggested using onkeyup, as it catches the values as they are typed and avoids additional confusion or programming.
I have an ASPX form and I need to disable the submit button if any one of six specific fields are empty. I'm trying to do this via Javascript or jQuery, but so far I can only find examples of either a single field on the form being empty, or ALL fields on the form. In my case, I don't care about several fields - only the six specific ones.
So basically, I have six conditions and one action. I found one example, but it was stringing together six different IF statements. I'd like to find a more streamlined way if possible. So, for example, I might do THIS for a single field... but how to do it for field2, field3, field4, etc. as well?
$(document).ready(function(){
$('#submit_btn').prop('disabled',true);
$('#field1').keyup(function(){
$('#submit_btn').prop('disabled');
})
});
Using Javascript or jQuery, what's the most efficient way to disable an input button if any of six input fields is blank?
You can add the same class name to all the elements and then do a validation foreach class element. Like in below code, i added the same class name to all the input for which the validation is required using class="valid" and then use the jquery class selector and the keyup method that you used to control the state of the button.
(function() {
$('.valid').keyup(function() {
var isEmpty = false;
$('.valid').each(function() {
if ($(this).val() == '') {
isEmpty = true;
}
});
if (isEmpty) {
$('#button1').attr('disabled', 'disabled');
} else {
$('#button1').removeAttr('disabled');
}
});
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
1<input type="text" class="valid" /><br />
2<input type="text" class="valid" /><br />
3<input type="text" class="valid" /><br />
4<input type="text" class="valid" /><br />
5<input type="text" class="valid" /><br />
6<input type="text" class="valid" /><br />
<input type="button" id="button1" value="Test Me!" disabled="disabled" />
</form>
If your requirements will allow it, you can use HTML 5 field validation. The browser will not allow the form to submit.
<form>
<label for="choose">Foo</label>
<input name="bar" required>
<input type="submit" /> <!-- <--- This will generate an error message if the user clicks it when the field is empty -->
</form>
You have the start of it correct; create an array with six variables, one for each of the fields, and create a new function to validate everything that is called on each keyup. So you would have
var[] array
$('#field1').keyup(function() {
array[0] = $('#field1').val();
validate();
}
${'#field2').keyup(function() {
array[1] = $('#field2').val();
validate();
}
...create one each for each field
function validate() {
for (var i = 0; i < array.length; i++) {
if(!arrays[i]) {
$('#submit_btn').prop('disabled');
return;
}
}
$('#submit_btn').prop('enabled'):
}
What this does is it listens to the fields for changes and updates the array. A blank value is falsy so you can just go through the array and disable the button if it's blank or null or something. Break out of the for loop in that case; you don't care about whatever else. If nothing disables the button and breaks the for loop then it's valid and the button is enabled.
This approach is useful because it's easily extendable. You can just push extra things into the array if you want to check them without rewriting the validation function.
This assumes you do not want to just use standard form validation and do it manually.
Add a common class to each of the required inputs. Then check the length of that object against the length of a filtered object where value is not empty. Then you can use that condition to set the prop value of the button to true/false.
http://api.jquery.com/filter/
JQuery:
$('form .required-valid').on('input paste change', function() {
var $required = $('form .required-valid');
//filter required inputs to only ones that have a value.
var $valid = $required.filter(function() {
return this.value != '';
});
//set disabled prop to false if valid input count is != required input count
$('#submit_btn').prop('disabled', $valid.length != $required.length);
});
HTML:
<form>
<label>Field1</label>
<input type="text" id="field1" class="required-valid" />
<label>Field2</label>
<input type="text" id="field2" class="required-valid" />
<label>Field3</label>
<input type="text" id="field3" class="required-valid" />
<label>Field4</label>
<input type="text" id="field4" class="required-valid" />
<label>Field5</label>
<input type="text" id="field5" class="required-valid" />
<label>Field6</label>
<input type="text" id="field6" class="required-valid" />
<label>Field7</label>
<input type="text" id="field7" class="not-required" placeholder="not required" />
<button id="submit_btn" disabled>
Submit
</button>
</form>
Example:
https://jsfiddle.net/SeanWessell/q2msc80L/
$(document).ready(function() {
$('#submit_btn').prop('disabled', true);
$('#field1').keyup(function() { // on keyup
var value = $(this).val(); // retrieve the value of the input
if (value.length == 0) // if the value's length is 0 (empty)
$('#submit_btn').prop('disabled', true); // disable the button
else // if not
$('#submit_btn').prop('disabled', false); // enable it
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="field1"/>
<input id="submit_btn" type="submit"/>
</form>
Just note that the form can be submitted using enter key, so instead of checking on every keyup, it would be better if you check onsubmit instead.
I have two input fields and i am wondering how do i compare value's between these two fields.
<input id="start" type="numeric" value="" />
<input id="end" type="numeric" value="" />
In above input fields, if the value in input field with id='start' is greater than id='end', i want to display an alert.
I tried below but not working
if ($("#end").val() > $("#start").val()) {
//do something
}else {
alert('Wrong Input');
}
What am i doing wrong???
You should bind an event handler such as 'keypress' to one of the fields. When that even is triggered, you should compare the values of both the input fields and show alert if necessary.
Additionally, type="number" is correct not "numeric" .
Here's a working fiddle-
http://jsfiddle.net/pe2ZE/
Use type="number", As per my knowledge there is type as such numeric
Code
if (+$("#end").val() > +$("#start").val()) {
//do something
} else {
alert('Wrong Input');
}
Here I have use + to convert value to integer
you are comparing strings $("#end").val() > $("#start").val() so you have to compare in numbers, and dont forget about the radix
if(parseInt($("#end").val(),10) > parseInt($("#start").val(),10))
and type="numeric" is a wrong syntax, use type="number"
<input id="start" type="number" value="" />
You need to use type="number" to make the script work:
<input id="start" type="number" value="" />
<input id="end" type="number" value="" />
Demo
Or you can use input type text and then parse the input using parseInt(val) and compare them. somethink like this:
if (parseInt($("#end").val()) > parseInt($("#start").val())){
//rest code
}
you can't use type="numeric" to make input numeric only
to solve this proplem use this code
HTML
<input type="tel" name="name">
jQuery
// HTML Text Input allow only Numeric input
$('[type=tel]').on('change', function(e) {
$(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
keys = ['0','1','2','3','4','5','6','7','8','9','.']
return keys.indexOf(event.key) > -1
})
You have to type cast the value to int just like
if (parseInt($("#end").val()) > parseInt($("#start").val())) {
//do something
}else {
alert('Wrong Input');
}
I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do.
I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on
<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />
<script type="text/javascript">
function noNumbers(e) {
keynum = e.which;
if (keynum == 13)
document.getElementById("Text2").focus();
}
</script>
I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript
This will handle multiple input fields.
Here is the jQuery version:
http://jsfiddle.net/TnEB5/3/
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
Here is the pure javascript version:
http://jsfiddle.net/TnEB5/5/
(you probably want to get the sibling differently)
function tab(e) {
if (e.which == 13) {
e.target.nextSibling.nextSibling.focus();
e.preventDefault();
}
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
var input = inputs[x];
input.onkeypress = tab;
}
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
handle keypress instead and return false back to the browser:
http://jsfiddle.net/EeyTL/
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<script type="text/javascript">
document.getElementById('Text1').onkeypress = function (e) {
if (e.which === 13) {
document.getElementById("Text2").focus();
return false;
}
};
</script>
You'll need to explicitly set the tabindex property of the input fields for a generic solution. Something like
<input id="Text1" type="text" tabindex="1" />
<input id="Text2" type="text" tabindex="2" />
<script type="text/javascript">
$('input').keypress(function(e){
if(e.which==13){
$("[tabindex='"+($(this).attr("tabindex")+1)+"']").focus();
e.preventDefault();
}
});
</script>
this solution uses jquery to assign the event handler for all input type elements on the page, sets focus to the element with the next highest tabindex property, and prevents the form from submitting when enter is pressed using e.preventDefault(). Here's a jfiddle
<input type="text" value="" onkeyup="doNext(this);"> a <br>
<input type="text" value="" onkeyup="doNext(this);"> b <br>
<input type="text" value="" onkeyup="doNext(this);"> c <br>
function doNext(el){
if(event.keyCode=='13'){
var nextEl = el.form.elements[el.tabIndex+1];
if (nextEl && nextEl.focus) nextEl.focus();
}
}
Althought the post is old, I hope my answer can help someone in need. I have a smilar situation:
I have a very large form for an employee scheduler application with different types of input fields. Some of the input fields are hidden sometimes and not other times. I was asked to make the enter key behave as the tab key so the users of the form could use the 10-key when creating thier employees schedule.
Here is how I solved my problem:
$(document).ready(function () {
var allInputs = $(':text:visible'); //(1)collection of all the inputs I want (not all the inputs on my form)
$(":text").on("keydown", function () {//(2)When an input field detects a keydown event
if (event.keyCode == 13) {
event.preventDefault();
var nextInput = allInputs.get(allInputs.index(this) + 1);//(3)The next input in my collection of all inputs
if (nextInput) {
nextInput.focus(); //(4)focus that next input if the input is not null
}
}
});
});
What I had to do was:
Create a collection of all the inputs I want to consider when tabbing. in my case it is text inputs that are visible.
Listen for a keydown event on the inputs in question, in my case all text field inputs
When the enter is pressed on my text input, determine what input is next to be focused.
If that input is valid, bring it into focus.
I am using this code for advancing to next input field. I hate to press TAB key. And this solution works in IE & Firefox:
<script type="text/javascript">
function tabE(obj,e){
var e=(typeof event!='undefined')?window.event:e;// IE : Moz
if(e.keyCode==13){
var ele = document.forms[0].elements;
for(var i=0;i<ele.length;i++){
var q=(i==ele.length-1)?0:i+1;// if last element : if any other
if(obj==ele[i]){ele[q].focus();break}
}
return false;
}
}
</script>
HTML Content
<form id="main">
<input name="" type="text" onkeypress="return tabE(this,event)">
<input type="submit" value="Ok">
</form>
Here is a easy solution for you.
Basically you include the enter2tab.js file and then add the enter2tab class on each object where you want enter to be treated as js.
https://github.com/AndreasGrip/enter2tab
You can obviously look at the code to understand what it does and how..
I believe using e.preventDefault(); is safer than returning false.