Compare values in two input fields - javascript

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');
}

Related

Input type="text" currency validation

I currently have an input type="text" that I transform into a currency value on the "keyup" event. In order to keep this functionality (works fine), the input type has to be set to "text". At the same time, I would like to have a minimum value of "100.00" set to it.
Any way I can accomplish this? Also, would I able to customize my jquery validation message to say "Minimum Amount $100.00"?
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input required id="balance" name="balance" type="text" class="number" />
You can add this property in your input filed: minlength="5"
<input required id="balance" name="balance" type="text" class="number" minlength="5" />
And in your JS code you can add a 'if' statement to check that this input contain at least 5 char.
Furthermore you can add the same 'if' statement in your back-end to check it again.
Thank you all for your input.
I've ended up keeping the input type="text" for the number of digits users can type in and called a function to check the input value against the 100.
function checkAmount() {
var valueBalance = $("#balance").val();
var valueNumberBalance = parseFloat((valueBalance).replace(/[^\d\.]/, ''));
if (valueNumberBalance < 100) {
$("#balance").get(0).setCustomValidity("Minimum Amount of $100.00");
}
else {
$("#balance").get(0).setCustomValidity("");
}
}
A snippet created using the type="number" instead of type="text" on the input still allows the jQuery functionality to work.
The validation message is HTML5 and not jQuery as you did not provide that code. I did the following:
Changed to type="number"
Added min="100"
Added step="0.01" to handle currency stepping
$('input.number').keyup(function(event) {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
Text input (original): <input required id="balance" name="balance" class="number" type="text" /><br />
Number input: <input required id="balance" name="balance" class="number" type="number" min="100" max="99999" step="0.01" /><br />
<input type="submit" />
<small>Enter less than 100 and press 'submit' to see validations.</small>
</form>
you can try to currency validation using regex
<div class="col-sm-3 form-group">
<b>Premium :*</b><br>
<p><input type="text" class="form-control" oninput="this.className = ''" name="premium" id="premium" valideAtt="currency" title="Premium" onblur="defaultValidation(this)"></p>
<span id="er_premium" style="display: block; width:100%; float: left;"></span>
</div>
<script type="text/javascript">
var REG_CURRENCY = /(?=.*\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?(\.\d{1,2})?$/;
function defaultValidation(src){
var getAttributeValue=src.attributes.valideAtt.value;
if(getAttributeValue=="currency"){
if(!src.value.match(REG_CURRENCY)){
$("#"+src.id).addClass("invalid");
$("#er_"+src.id).html("<span style=\"color:red\">Please Enter Valide currency Value.<\span>");
return false;
}else{
$("#er_"+src.id).html("");
return true;
}
}
}
<script>

If any input field value entered zero then disable else enable [closed]

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.

Disable button unless specific fields have values

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.

How do I check to see if form inputs(x5) have not been left empty by the user, using JavaScript/JQuery?

I am working on this code below and have had a stab at writing a IF statement around the code with //* .
The if statement logic should say 'If all(x5) form input fields are empty then show alert message else do what's between //*
The user must modify at least one of the five input fields with a letter or number, for the form to be submitted.
$('.submit').live('click', function(){
// *
$('.submit').parent().find('form').submit();
alert('The form has been submitted!');
// *
});
HTML Structure:
<div style="margin:50px;">
<div id="search-prefix">
<form method="post" action="">
<input type="text" class="alpha-first default-value" name="" maxlength="1" value="?" />
<input type="text" class="numeric plate-divide default-value" name="" maxlength="3" value="???" />
<input type="text" class="alpha default-value" name="" maxlength="1" value="?" />
<input type="text" class="alpha default-value" name="" maxlength="1" value="?" />
<input type="text" class="alpha default-value" name="" maxlength="1" value="?" />
</form>
</div>
<span class="btn submit">Search</span>
</div>
Any help would be greatly appreciated, Thanks
You can use .filter and $.trim to determine how many fields have been left empty:
$('.submit').live('click', function(){
var emptyCount = $(this).closest("form").find("input").filter(function() {
return $.trim(this.value).length === 0;
}).length;
if(emptyCount === 5) {
alert("all 5 are empty");
} else {
$('.submit').parent().find('form').submit();
alert('The form has been submitted!');
}
});
Another way is to concate the values of each input fields together and check the length of the result string.
I use the jQuery Validation plugin. Quite fancy.
After looking at some of the answers I had another stab at doing it myself.
My approach was quite simple:
On keyUp if the value of form input is a '' empty string or nothing, then add a class to the submit button(which is a <span class="btn empty-fields">...</span>). Hence:
$('form input').keyup(function () {
if(!($(this).siblings().andSelf().hasClass('field-error'))){
if ($(this).val() == '') {
$('.btn').addClass('empty-fields').removeClass('no-submit submit');
$('.error-notify').hide();
}
else{ ...
When the user clicks on this element it triggers this response:
$('.empty-fields').live('click', function(){
alert('One field MUST be modified to use Search!')
});
Appreciate your effort guys, Thanks

use jQuery to move the cursor to another field when a certain character is typed?

I have two text fields in my web page. The user is supposed to enter two numbers seperated by a hyphen ("-") character. The numbers may be between 1 and 10 digits each. I need the cursor to move to the next field when the user presses the hyphen key.
I can easily move the cursor using $('#txtField2').focus(). However, I still have the problem that the hyphen character remains in the first text field. How can I easily supress the hyphen from appearing in the first text field?
HTML
<form>
<input type='text' class='num' />
<input type='text' class='num' />
</form>
JavaScript
$('.num:first').keydown(function (event) {
// check for hyphen
if (event.which === 189) {
event.preventDefault();
$(this).next('.num').focus();
}
});
Live demo
Assuming a simplified html of:
<form action="#" method="post">
<fieldset>
<label for="numOne">Number:</label>
<input type="text" id="numOne" name="numOne" />
<input type="text" id="numTwo" name="numTwo" />
</fieldset>
</form>
The following should work, or serve as an example:
$('#numOne').keypress(
function(e){
if (e.which == 45) {
$(this).next('input:text').focus();
return false; // prevents the '-' being entered.
}
});
JS Fiddle
Incidentally, I used $(this).next('input:text') rather than an id-based selector to allow for more general application and re-use.
References:
keypress(),
next().
I'd do it like this:
$('#input1').keypress(function(e) {
if(e.keyCode == 45) {
e.preventDefault();
$('#input2').focus();
}
});
see live example here: http://jsfiddle.net/wjNP3/2/
you could "listen" to that character and just focus the other field and prevent it from inputing
Maybe this can help you:
HTML
<div>
<p>Insert Your Number:</p>
<input type="number" value="" id="first" >
<input type="number" value="" id="second" >
<input type="number" value="" id="third" >
<input type="submit" id="submit">
</div>
jQuery
$("#first").on("keypress", function(){
if($("#first").val().length == 4){
$("#second").focus();
}
})
$("#second").on("keypress", function(){
if($("#second").val().length == 4){
$("#third").focus();
}
})
$("#third").on("keypress", function(){
if($("#third").val().length == 5){
$("#submit").focus();
}
})
OR you can check Live DEMO by CLICK HERE!

Categories