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>
Related
I have 2 input fields one is enabled and one is disabled, on entering at least 6 characters in enabled field the second one (disabled field) should be enabled using javascript.
A different approach with an eventListener:
document.getElementById('enabled').addEventListener('keyup', function() {
if (this.value.length >= 6) {
document.getElementById('disabled').disabled = false;
} else {
document.getElementById('disabled').disabled = true;
}
});
<input type="text" id="enabled" placeholder="Type here...">
<input type="text" id="disabled" disabled>
$("#input1").keydown(function() {
if($(this).val().length > 6) {
$("#input2").attr('disabled', false)
}
});
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<form>
<input type="text" id="input1" />
<input type="text" id="input2" disabled />
</form>
To make this work you can use the input event handler on the first input, then use prop() to enable or disable the second input, based on the provided value.
It's possible to use keyup or keydown event handlers as an alternative, but be aware that they will not work when content is added or removed from the input using the mouse only.
Try this:
$('#enable').on('input', function() {
$('#disable').prop('disabled', $(this).val().length < 6);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputContainer">
<input type="text" id="enable" name="online-id" value="" class="focus sprite-clear_input_icns" placeholder="Online ID" />
</div>
<div class="inputContainer">
<input type="password" id="disable" class="masked" name="passcode" value="" placeholder="Passcode" disabled="true" readonly />
</div>
Use prop to enable disable your text with length.
$("#target1").keyup(function() {
var len = $('#target1').val().length;
if (len >= 6)
$("#target2").prop('disabled', false);
else
$("#target2").prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='target1' />
<input type='text' id='target2' disabled/>
I wrote a code to validate a form on client-side. Since I binded all the error messages on('input', function()) now the last case to take in consideration is when the user didn't even hit a required input leaving it empty.
If all the inputs in the form were required I could have used something like
$('#subButton').on('click', function(e) {
if (!$('#formName').val()) {
e.preventDefault();
alert("Fill all the required fields");
});
But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs.
Something like:
$('#subButton').on('click', function(e) {
if (!$('#formName.req').val()) {
e.preventDefault();
alert("Fill all the required fields");
}
});
In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent.
Just use .filter and check the length. Also, a simple ! check probably isn't good, what if someone enters 0?
var hasEmptyFields = $('#formName.req').filter(function() {
return this.value.replace(/^\s+/g, '').length; //returns true if empty
//Stole the above regex from: http://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
}).length > 0
if (hasEmptyFields) {
}
Use reduce
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
if (!submitAllowed) { ... }
Here is a simple demo:
<form action="dummy.asp" onSubmit="return handleSubmit()">
<p> You can only submit if you enter a name </p>
<br />
Enter name: <input class="req" type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function handleSubmit() {
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
return submitAllowed;
}
</script>
But since in my form there are required inputs (with class="req")
and non required inputs, I would like to know if there's a method to
perform the check only on the .req inputs
There is an HTML5 form boolean attribute required.
required works on:
<input type="text" />
<input type="search" />
<input type="url" />
<input type="tel" />
<input type="email" />
<input type="password" />
<input type="date" />
<input type="number" />
<input type="checkbox" />
<input type="radio" />
<input type="file" />
Example:
input {
display: block;
margin: 6px;
}
<form action="http://www.stackoverflow.com/">
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="submit" value="Press Me Without Filling in any of the Fields">
</form>
Peculiarly, the StackOverflow Snippet above doesn't seem to be working.
Here's a JSFiddle to demonstrate what it should be doing:
https://jsfiddle.net/a5tvaab8/
I'm trying to update a page by echoing the input of a user in real time through ajax. However, when a user types in something and clicks 'send' there is nothing echoed. But when I preset the input to a random word through html and click 'send' the word is shown. Why is this and how can I update the input value without manually doing so in html?
HTML
<input type="text" id="userName" name="typeit" value=""/>
<!-- Input containing preset value -->
<input type="text" id="userName" name="typeit" value="cindy"/>
<input type="button" id="text_value" value="send"/>
JQuery
// I used this to check if the actual input was being updated
$('#text_value').click(function() {
var text_value = $("#userName").val();
if(text_value=='') {
alert("Please enter a title first");
}else{
alert(text_value);
}
});
I think what you want is a keyboard event like keyup:
$('#userName').keyup(function() {
var text_value = $(this).val();
if(text_value=='') {
alert("Please enter a title first");
}else{
$("p").html(text_value);
}
});
Also id can only be used once on the page so you need to change one of them:
<input type="text" id="userName" name="typeit" value=""/>
<!-- Input containing preset value -->
<input type="text" id="somethingElse" name="typeit" value="cindy"/>
<input type="button" id="text_value" value="send"/>
<!--for my example-->
<p>Update</p>
FIDDLE
You have a mistake in your HTML as you define id="userName" twice. If you compare strings you always need the === identical operator. Try out this snippet:
// I used this to check if the actual input was being updated
$('#text_value').click(function() {
var text_value = $("#userName").val();
if (text_value === '')
alert("Please enter a title first");
else
alert(text_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="Uname" name="typeit" value="" />
<!-- Input containing preset value -->
<input type="text" id="userName" name="typeit" value="cindy" />
<input type="button" id="text_value" value="send" />
<div id="test"></div>
I would like to validate an input date with a null value like this
<input type="date" value="0000-00-00" id="date" />
On submit I have a this logical message 'Please enter a date.'
I found something like this http://jsfiddle.net/trixta/zRGd9/embedded/result,html,js,css/.
If you know how to do this, here is a sample http://jsfiddle.net/zRGd9/24/
This is simply not a date and depending of the browser implementation this value is either emptied or considered a badInput or a typeMismatch.
If you want to use this you have the following options:
Strictly empty it yourself:
$('input[type="date"]')
.on('change.empty', function () {
var val = $.prop(this, 'value');
if (!val || val == '0000-00-00') {
$.prop(this, 'value', '');
}
})
.trigger('change.empty')
;
Set a novalidate attribute:
```
<form novalidate="">
<!-- ... -->
</form>
Use a different input if you also want to allow non valid date:
```
<input type="number" min="0" max="31" />
<input type="number" min="0" max="12" />
<input type="number" min="0" max="9999" />
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