Textbox to accept value 100 and above - javascript

This is my textbox that I have:
This is the code for it :
<!-- Preferred credit limit -->
<div class="signup-card-section">
<h2 class="accordion-header boldtext">Tell Us Your Preferred Credit Limit</h2>
<div class="column-control no-padding twelve colgrid">
<fieldset>
<div class="row">
<p class="text-red">(Choose one)</p>
<p>My Preferred Credit Limit<span class="text-red">*</span></p>
<br>
<input type="radio" name="prefcreditlimit" checked="checked" value="yesprefcreditlimit" id="yesprefcreditlimit">
<span class="radiotextdeco">S$</span> <input type="text" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100"> <span style="font-size:12px;"> (Must be in multiples of 00’ and a minimum of S$100)</span><br><br>
<input type="radio" name="prefcreditlimit" checked="checked" value="noprefcreditlimit"> <span class="radiotextdeco">I dont have a preferred credit limit and agree to any credit limit determined</span><br><br>
<p><strong>Note:</strong> Principal applicant and Suplementary applicant will be granted the preferred credit limit of any limit determined by the bank, whichever is lower.</p>
</div>
</fieldset>
</div>
</div>
Error message to appear if value key in is not in multiples of 00’ or minimum of S$100: “Your Preferred Credit Limit must be in multiple of 00’ and a minimum of S$100.
Since I set the min value to 100. There's an error message appear when user enters less 100. The problem is now, I'm not sure how to check for the validation of 00'
Any help would be appreciated.

Use <input type="number"> along with the min and step attributes:
<input type="number" name="prefcreditlimitval" min="100" step="100">
If the user enters a value lower than the min or something that isn't a multiple of step, the browser's validation will prevent the form from being submitted. In browsers that don't support validation, you can use a polyfill (like this one).
You can test out the validation (though SO doesn't allow forms to run):
input:invalid {
border-color: red;
}
Input multiples of 100<br><br>
<input type="number" name="test" min="100" step="100">

Input tag also has 'pattern' attribute, where you can specify Regex pattern to check input.
So something like
<input type="text" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100" pattern="\d+00$">
should work!
Some info about input's pattern attr

As mentioned in other answers, you may use min and step attributes to limit value of input field. But these attributes were introduced as a part of HTML 5 standards and it is not supported in all browsers yet.
A generic solution using jQuery/JS to check input value and give error message if it does not meet your requirements can be written as follows.
function validate() {
var value = $("#prefcreditlimit").val();
if (isNaN(value) || value < 100 || value % 100 != 0) {
alert("Please provide a valid input");
$("#prefcreditlimit").val("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="radiotextdeco">S$</span>
<input type="text" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100" onblur="validate()"> <span style="font-size:12px;"> (Must be in multiples of 00’ and a minimum of S$100)</span>

You could add some validation in Javascript, checking whether the input is indeed a number, if so then check if it's also at least 100 and if so, check if the input is a multitude of 100. You can do it like this:
var val = parseInt($("#prefcreditlimit").val(), 10);
if (isNaN(val))
{
// ERROR; NOT A NUMBER
}
else if (val < 100)
{
// ERROR; VALUE IS LOWER THAN 100
}
else if (val % 100 !== 0)
{
// ERROR; VALUE IS NOT A MULTITUDE OF 100
}

It seems you want the value to be greater than 100 and a multiple of 100. Seeing as you have tagged the question with jQuery I have done a jQuery example for you.
I am listening for changes on the textfield using .change().
jQuery("#prefcreditlimit").change(function () { ... });
I am using jQuery(this).val(); or jQuery("#prefcreditlimit").val(); to get the current value of the textfield .val()
From your comments, I have updated to first check that the radio button is checked first using !jQuery("#yesprefcreditlimit").is(':checked') which says if the checkbox is not checked.
Then I use simple logic checks first checking if the value is a number isNaN(value) then if value < 100 is less than 100. Then if value % 100 > 0 if the modulus of the value is greater than 100.
There definitely a lot more you could go here, and a lot of different ways you could do this, this is just one way. For example you might not want the change part of this and instead do the validation on the submit of the form.
Note: In the stack snippet you need to click out of the textbox for the change event to be triggered.
jQuery(function () {
jQuery("#prefcreditlimit").change(function () {
var value = jQuery(this).val();
if(!jQuery("#yesprefcreditlimit").is(':checked')) {
jQuery("#warning").text("");
return;
}
if(isNaN(value)) {
jQuery("#warning").text("Value is not a number.");
return;
}
if(value < 100) {
jQuery("#warning").text("Value is less than 100");
return;
}
if(value % 100 > 0) {
jQuery("#warning").text("Value needs to be a multiple of 100");
return;
}
jQuery("#warning").text("Value: " + value + " is Okay!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>My Preferred Credit Limit<span class="text-red">*</span></p>
<br>
<input type="radio" name="prefcreditlimit" checked="checked" value="yesprefcreditlimit" id="yesprefcreditlimit">
<span class="radiotextdeco">S$</span> <input type="text" name="prefcreditlimitval" id="prefcreditlimit" min="100"> <span style="font-size:12px;"> (Must be in multiples of 00’ and a minimum of S$100)</span><br><br>
<input type="radio" name="prefcreditlimit" checked="checked" value="noprefcreditlimit"> <span class="radiotextdeco">I dont have a preferred credit limit and agree to any credit limit determined</span><br><br>
<p id="warning"></p>

If you have no problem using input type number you can use, step attribute
step = "any" or positive floating-point number NEW specifies the value granularity of the element’s value.
If step is not explicitly included, the value of step defaults to 1, as if it were included with step="1" (or step="100" in the case of type="time"), even if the default value or min value is a float.
<input type="number" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100" step="100">

Related

HTML input validity initial state [duplicate]

It seems the minlength attribute for an <input> field doesn't work.
Is there any other attribute in HTML with the help of which I can set the minimal length of a value for fields?
You can use the pattern attribute. The required attribute is also needed, otherwise an input field with an empty value will be excluded from constraint validation.
<input pattern=".{3,}" required title="3 characters minimum">
<input pattern=".{5,10}" required title="5 to 10 characters">
If you want to create the option to use the pattern for "empty, or minimum length", you could do the following:
<input pattern=".{0}|.{5,10}" required title="Either 0 OR (5 to 10 chars)">
<input pattern=".{0}|.{8,}" required title="Either 0 OR (8 chars minimum)">
There is a minlength property in the HTML5 specification now, as well as the validity.tooShort interface.
Both are now enabled in recent versions of all modern browsers. For details, see https://caniuse.com/#search=minlength.
Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)
http://jsfiddle.net/xhqsB/102/
<form>
<input pattern=".{5,10}">
<input type="submit" value="Check"></input>
</form>
Yes, there it is. It's like maxlength. W3.org documentation:
http://www.w3.org/TR/html5/forms.html#attr-fe-minlength
In case minlength doesn't work, use the pattern attribute as mentioned by #Pumbaa80 for the input tag.
For textarea:
For setting max; use maxlength and for min go to this link.
You will find here both for max and min.
I used maxlength and minlength with or without required and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
`
minlength attribute is now widely supported in most of the browsers.
<input type="text" minlength="2" required>
But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).
To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:
<input type="text" pattern=".{2,}" required>
There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:
<h3>In each form type 1 character and press submit</h3>
</h2>
<form action="#">
Input with minlength: <input type="text" minlength="2" required name="i1">
<input type="submit" value="Submit">
</form>
<br>
<form action="#">
Input with patern: <input type="text" pattern=".{2,}" required name="i1">
<input type="submit" value="Submit">
</form>
For example, in Chrome (but similar in most browsers), you will get the following error messages:
Please lengthen this text to 2 characters or more (you are currently using 1 character)
by using minlength and
Please match the format requested
by using pattern.
I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:
autocomplete="off"
<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />
The minLength attribute (unlike maxLength) does not exist natively in HTML5. However, there a some ways to validate a field if it contains less than x characters.
An example is given using jQuery at this link: http://docs.jquery.com/Plugins/Validation/Methods/minlength
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: {
required: true,
minlength: 3
}
}
});
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, Minimum length 3: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
</html>
Not HTML5, but practical anyway: if you happen to use AngularJS, you can use ng-minlength (or data-ng-minlength) for both inputs and textareas. See also this Plunk.
My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.
minlength.js
$(document).ready(function(){
$('form textarea[minlength]').on('keyup', function(){
e_len = $(this).val().trim().length
e_min_len = Number($(this).attr('minlength'))
message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
this.setCustomValidity(message)
})
})
HTML
<form action="">
<textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>
See http://caniuse.com/#search=minlength. Some browsers may not support this attribute.
If the value of the "type" is one of them:
text, email, search, password, tel, or URL (warning: not include number | no browser support "tel" now - 2017.10)
Use the minlength(/ maxlength) attribute. It specifies the minimum number of characters.
For example,
<input type="text" minlength="11" maxlength="11" pattern="[0-9]*" placeholder="input your phone number">
Or use the "pattern" attribute:
<input type="text" pattern="[0-9]{11}" placeholder="input your phone number">
If the "type" is number, although minlength(/ maxlength) is not be supported, you can use the min(/ max) attribute instead of it.
For example,
<input type="number" min="100" max="999" placeholder="input a three-digit number">
New version:
It extends the use (textarea and input) and fixes bugs.
// Author: Carlos Machado
// Version: 0.2
// Year: 2015
window.onload = function() {
function testFunction(evt) {
var items = this.elements;
for (var j = 0; j < items.length; j++) {
if ((items[j].tagName == "INPUT" || items[j].tagName == "TEXTAREA") && items[j].hasAttribute("minlength")) {
if (items[j].value.length < items[j].getAttribute("minlength") && items[j].value != "") {
items[j].setCustomValidity("The minimum number of characters is " + items[j].getAttribute("minlength") + ".");
items[j].focus();
evt.defaultPrevented;
return;
}
else {
items[j].setCustomValidity('');
}
}
}
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isChrome = !!window.chrome && !isOpera;
if(!isChrome) {
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testFunction,true);
forms[i].addEventListener('change', testFunction,true);
}
}
}
I wrote this JavaScript code, [minlength.js]:
window.onload = function() {
function testaFunction(evt) {
var elementos = this.elements;
for (var j = 0; j < elementos.length; j++) {
if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
evt.preventDefault();
};
}
}
}
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', testaFunction, true);
}
}
In my case, in which I validate the most manually and using Firefox (43.0.4), minlength and validity.tooShort are not available unfortunately.
Since I only need to have minimum lengths stored to proceed, an easy and handy way is to assign this value to another valid attribute of the input tag. In that case then, you can use min, max, and step properties from [type="number"] inputs.
Rather than storing those limits in an array it's easier to find it stored in the same input instead of getting the element id to match the array index.
I used max and min then required, and it worked for me very well, but what am not sure is if it is a but coding method.
<input type="text" maxlength="13" name ="idnumber" class="form-control" minlength="13" required>
If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:
// prefix="prefix_text"
// If the user changes the prefix, restore the input with the prefix:
if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
document.getElementById('myInput').value = prefix;
Following #user123444555621 pinned answer.
There is a minlength attribute in HTML5 but for some reason it may not always work as expected.
I had a case where my input type text did not obey the minlength="3" property.
By using the pattern attribute I managed to fix my problem.
Here's an example of using pattern to ensure minlength validation:
const folderNameInput = document.getElementById("folderName");
folderNameInput.addEventListener('focus', setFolderNameValidityMessage);
folderNameInput.addEventListener('input', setFolderNameValidityMessage);
function setFolderNameValidityMessage() {
if (folderNameInput.validity.patternMismatch || folderNameInput.validity.valueMissing) {
folderNameInput.setCustomValidity('The folder name must contain between 3 and 50 chars');
} else {
folderNameInput.setCustomValidity('');
}
}
:root {
--color-main-red: rgb(230, 0, 0);
--color-main-green: rgb(95, 255, 143);
}
form input {
border: 1px solid black;
outline: none;
}
form input:invalid:focus {
border-bottom-color: var(--color-main-red);
box-shadow: 0 2px 0 0 var(--color-main-red);
}
form input:not(:invalid):focus {
border-bottom-color: var(--color-main-green);
box-shadow: 0 2px 0 0 var(--color-main-green);
}
<form>
<input
type="text"
id="folderName"
placeholder="Your folder name"
spellcheck="false"
autocomplete="off"
required
minlength="3"
maxlength="50"
pattern=".{3,50}"
/>
<button type="submit" value="Create folder">Create folder</button>
</form>
For further details, here's the MDN link to the HTML pattern attribute: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern
You can use minlength in input tag or you can regex pattern to check the number of character or even you can take the input and check the length of the character and then you can restrict based upon your requirement.
Smartest Way for maxlength
$("html").on("keydown keyup change", "input", function(){
var maxlength=$(this).attr('maxlength');
if(maxlength){
var value=$(this).val();
if(value.length<=maxlength){
$(this).attr('v',value);
}
else{
$(this).val($(this).attr('v'));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" maxlength="10">
I've used the follow tag with numbers:
<input type="tel" class="form-control" name="Extension" id="Extension" required maxlength="4" minlength="4" placeholder="4 Digits" />
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />

Using JavaScript to get random 2-digit numbers in a specific range where both the 1st and 2nd digits are constrained

I've got a bit of an interesting mathematical puzzle to solve.
I'm writing a test to verify that values outside of a range of a field in a window are not allowed to be input. For the most part this is extremely easy.
I'm using a function like this:
function getRanInt(min, max)
{
let min = Math.ceil(min);
let max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
to set the range of "erroneous" values I want to test.
However, there is one field which throws a wrench in this method. One field has constraints on each digit. So the first digit can only be between 0-7 and the second digit can only be between 0-3.
My first thought was to simply concatenate two numbers together that I could separately constrain like this:
let m1_1;
let m1_2;
m1_1 = getRanInt(8,9);
m1_2 = getRanInt(4,9);
m1 = m1_1.toString() + m1_2.toString();
m1 = Number(m1);
until I thought about it for half a second and realized that this would only get me erroneous values > 83 but leave out an entire array of possible erroneous values like 24, 36, 18 etc...
I've been wracking my brain to try and come up with a solution that isn't massively convoluted but I've been drawing a blank. I thought I'd turn to you fine braniacs here and see if you could maybe help unstick my gears.
ADDITIONAL: If anyone's interested, the tool tip for the field in question explicitly says this:
2 Digits:
1st = 0 - 7
2nd = 0 - 3
To test all the incorrect values, you can combine solution that provided by you with the second set of values, that are accessible using your functions in the following way:
let result;
if(Math.round(Math.random()))
{
let m1_1;
let m1_2;
m1_1 = getRanInt(8,9);
m1_2 = getRanInt(0,9);
let m1 = m1_1.toString() + m1_2.toString();
result = Number(m1);
}
else
{
let m2_1;
let m2_2;
m2_1 = getRanInt(0,7);
m2_2 = getRanInt(4,9);
let m2 = m2_1.toString() + m2_2.toString();
result = Number(m2);
}
I just wonder why the users can fill in the wrong values in the first place.
You can stop this from happening either by restricting the numbers the user can put in an input, by using a number input, or a range slider.
I will show you how it can look like below, but you can go even further and override any input the user have done, based on a pattern or min and max value - or to check if the input validates.
The slider doesn't need extra code so that's probably the preferred way.
function updateLabel(rangeId, rangeValue) {
let labelElement = document.getElementById(rangeId + "label");
if (labelElement) {
labelElement.innerHTML = rangeValue;
}
}
label {
display: none;
font-size: 0.8rem;
}
input:invalid + label,
.range-container > label {
display: inline-block;
}
.range-container {
display: flex;
align-items: center;
}
<h4>Text Input</h4>
<div>
<input type="text" placeholder="0-7" maxlength="1" pattern="[0-7]{1}">
<label>A number between 0 and 7 is required.</label>
</div>
<div>
<input type="text" placeholder="0-3" maxlength="1" pattern="[0-7]{1}">
<label>A number between 0 and 3 is required.</label>
</div>
<hr/>
<h4>Number Input</h4>
<div>
<input type="number" placeholder="0-7" min="0" max="7">
<label>A number between 0 and 7 is required.</label>
</div>
<div>
<input type="number" placeholder="0-3" min="0" max="3">
<label>A number between 0 and 3 is required.</label>
</div>
<hr/>
<h4>Range Slider</h4>
<div class="range-container">
<input type="range" oninput="updateLabel(this.id, this.value)" id="first" min="0" max="7" value="0">
<label id="firstlabel">0</label>
</div>
<div class="range-container">
<input type="range" oninput="updateLabel(this.id, this.value)" id="second" min="0" max="3" value="0">
<label id="secondlabel">0</label>
</div>

validating a form using jQuery

I've tried, I've researched, and I still can't figure out how to validate this form using jQuery. I've even tried to check out the jQuery API and I had no luck with it. This shouldn't be as hard as it seems. There are a few id's that i'm not using yet because I want to get what I have so far working before I continue. The best I could find for validating emails is just straight up JavaScript. Here's my code.
$(document).ready(function(){
$("#sendForm").click(function(){
var validForm=true; //set valid flag to true, assume form is valid
//validate customer name field. Field is required
if($("#custName").val()) {
$("#custNameError").html(""); //field value is good, remove any error messages
} else {
$("#custNameError").html("Please enter your name.");
validForm = false;
}
//validate customer phone number. Field is required, must be numeric, must be 10 characters
var inPhone = $("#custPhone").val(); //get the input value of the Phone field
$("#custPhoneError").html(""); //set error message back to empty, assume field is valid
if(!inPhone) {
$("#custPhoneError").html("Please enter your phone number.");
validForm = false;
} else {
//if( !$.isNumeric(inPhone) || Math.round(inPhone) != inPhone ) //if the value is NOT numerice OR not an integer. Rounding technique
if( !$.isNumeric(inPhone) || (inPhone % 1 != 0) ) //if the value is NOT numerice OR not an integer. Modulus technique
{
$("#custPhoneError").html("Phone number must be a number.");
validForm = false;
} else {
if(inPhone.length != 10) {
$("#custPhoneError").html("Phone number must have 10 numbers");
validForm = false;
}
}
}
//ALL VALIDATIONS ARE COMPLETE. If all of the fields are valid we can submit the form. Otherwise display the errors
if(validForm) {
//all values are valid, form is good, submit the form
alert("Valid form will be submitted");
//$("#applicationForm").submit(); //SUBMIT the form to the server
} else {
//form has at least one invalid field
//display form and associated error messages
alert("Invalid form. Display form and error messages");
}
}); //end sendform.click
}); //end .ready
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
label {
width:150px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2></h2>
<h3>Form Validation Project - Complaint Form</h3>
<form id="form1" name="form1" method="post" action="">
<p>Please enter the following information in order to process your concerns.</p>
<p>
<label for="custName">Name:</label>
<input type="text" name="custName" id="custName" />
<span id="custNameError" class="errorMsg"></span>
</p>
<p>
<label for="custPhone">Phone Number: </label>
<input type="text" name="custPhone" id="custPhone" />
<span id="custPhoneError" class="errorMsg"></span>
</p>
<p>
<label for = "email">Email:</label>
<input type = "text" name = "emailAdd" id = "emailAdd" />
<span id = "emailError" class = "emailError"></span>
</p>
<p>Please Select Product Group:</p>
<p>
<label>
<input type="radio" name="custProducts" value="books" id="custProducts_0" />
Books
</label>
<br />
<label>
<input type="radio" name="custProducts" value="movies" id="custProducts_1" />
Movies
</label>
<br />
<label>
<input type="radio" name="custProducts" value="electronics" id="custProducts_2" />
Consumer Electronics
</label>
<br />
<label>
<input type="radio" name="custProducts" value="computer" id="custProducts_3" />
Computer
</label>
<br />
</p>
<p>Description of problem: (Limit 200 characters)</p>
<p>
<label for="custComplaint"></label>
<textarea name="custComplaint" id="custComplaint" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="button" id="button" value="File Complaint" />
<input type="reset" name="button2" id="button2" value="Reset" />
</p>
</form>
<p> </p>
$("#button").click(function(e){
e.preventDefault(); // you need to stop the initial event to have a chance to validate
var validForm=true;
// etc...
You can use jquery.validate.js to validate your forms , it will overcome all your manual efforts to create the validation rules also it is providing the various predefined rules like required,email, minlength and maxlength, etc. So, it will be easier for you to achieve what you need very easily.
https://jqueryvalidation.org/
I have a simple jquery form validation and submission package - see if that's of any help - it's easy to install and you can customise quite a few things: https://github.com/sebastiansulinski/ssd-form
Just to get you started, your submit control in the html has id "button", so you should use $('#button').click, not $('#sendForm').click.
Also, if you want to stay on the page (like to do validations, show errors, etc), you have to prevent the form from submitting automatically when the button is clicked. There are lots of ways to do this, but the easiest way is to just change your button type from submit to button. Ie, replace this:
<input type="submit" name="button" id="button" value="File Complaint" />
with this:
<input type="button" name="button" id="button" value="File Complaint" />
------
That should get you started, at least your code will run, you can use console.log to debug, etc. Good luck.
UPDATE
I should add that if you take my advice, the form will never submit on it's own - that is good if some validation fails and you want to stay on the page and give some error feedback to the user.
When you do want the form to submit, you have to make it happen yourself. Again, there are lots of ways to do this, but the simplest one is probably:
$('#form1').submit();

Input element that allowes only number with decimals, with AngularJS

I'm trying to create an input element that:
Holds a number (string or actual number doesn't matter).
You shall not be able to enter anything else but numbers and a dot(.).
You are allowed to enter two decimals.
If no decimals are entered, two decimals (i.e. .00) shall be added to the number when leaving the input element (on-blur).
I'm working with AngularJS (1.2) and watch $valid and $invalid on the containing form.
The input is valid when the value is a number with two decimals and the value is larger than 0.
I have tried to use:
<input ng-model="price" type="number" ng-blur="addDecimals()"/>
$scope.addDecimals = function(){
$scope.price = $scope.price.toFixed(2);
}
But then I can't add zeroes as decimals (.00). As toFixed() returns a string, the value is not allowed in the input and it becomes empty.
I have also tried to use
<input type="text" ng-model="price" ng-blur="addDecimals()" ng-change="changed()" />
$scope.changed = function(){
// removes all charachters but numbers and one dot (.);
// examples:
// if value is '1a.t9' it will be changed to '1.9'
// if value is 'qwe' it will be changed to ''
// if value is 4 it will not be changed.
$scope.price = removeAllCharsButNumbersAndDot($scope.price);
}
$scope.addDecimals = function(){
if(parseFloat($scope.price) > 0)
$scope.price = $scope.price.toFixed(2);
else
$scope.price = "";
}
With this solution [form].$valid will be set to true if the value '0' is entered. [form].$valid will be set to false only when the user leaves the input element (on-blur) which is kind of ugly.
I have tried to use ng-pattern="/^\s*(?=.[1-9])\d(?:.\d{1,2})?\s*$/", but then ng-change will not fire.
You can use https://github.com/angular-ui/ui-validate. Ui-validate is great for this. Example:
<input type="number" ng-model="priceModel" ui-validate=" 'checkPriceModel($value)' ">
//Controller:
$scope.checkPriceModel = function(value){
return value <= 0;
}
<form name="theForm" id="theForm">
<input ng-change="changed()" id="priceId" type="number" min="1" name="priceName" ng-model="priceModel" required />
</form>
is the easiest (without extra modules)
If i am getting it right, you can try following
<form name="appTest">
<div
ng-class="{ 'has-error': appTest.app.$touched && appTest.app.$invalid }">
<input type="text" ng-model="vm.text" name="app" ng-pattern={define your pattern}>
</select>
</div>
If its invalid, 'has-error' class will get applied.
You don't need ng-change for this. You can just rewrite your html like this.
<form name="theForm" id="theForm">
<input id="priceId" type="number"
name="priceName" ng-model="priceModel" required min="0" />
<span class="error" ng-show="theForm.priceName.$error.number">
Not valid number!
</span>
</form>
You can read more about it here: https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D

Dynamically Generated AJAX/JS calculator form

I am trying to make a form that generates a value based on weighted inputs. For example, if we had the following in the database
**Item** _|_**Weight**
sink | 1.5
toilet | 2.5
shower | 3
And a form that looked like this, built from the database, using AJAX (Has to be built using AJAX, because the inputs' names and the number of inputs varies depending on a user selection in a previous section of the form)
<form id="calculator">
...There are several field sets here...
<fieldset id="myFields">
<input type="text" class="iteminput" data-weight="1.5" name="sink" id="sink">
<input type="text" class="iteminput" data-weight="2.5" name="toilet" id="toilet">
<input type="text" class="iteminput" data-weight="3" name="shower" id="shower">
</fieldset>
</form>
If the user puts in that they have X sinks, Y toilets, and Z showers, I want to automatically calculate the total "value" of their plumbing system, in this case, X*1.5+Y*2.5+Z*3.
Where I am hung up is on how to get the value of each input. What I want to be able to do is loop through all of the inputs in #myFields, get the value of the field, as well as the value of the data-weight attribute, multiply them together, then add them to a running total. I would like to do all of this in a function attached to the onKeyUp event for each input.
Any help is appreciated, and more information can be provided if necessary.
Javascript only solution would be best, but I am not against using jQuery if it drastically simplifies the answer.
Here is a jQuery example:
You should be able to get the values of the inputs on a blur function. And then update the values by running an each function on the inputs. Something like this...
<ul>
<li>
<label>Number of X</label>
<input type="text" value="" id="x"/>
</li>
<li>
<label>Number of Y</label>
<input type="text" value="" id="y"/>
</li>
<li>
<label>Number of Z</label>
<input type="text" value="" id="z"/>
</li>
</ul>
<p>Total is: <span class="total"></span>
jQuery:
$('input').blur(function () {
var total = 0;
$('input').each(function() {
total += Number($(this).val());
});
$('.total').text(total);
});
DEMO:
http://jsfiddle.net/DYzsR/1/
This is what I ended up doing.
function calcFixtures()
{
var elements = [];
var total = 0;
elements = document.getElementsByClassName('fixtureinput');
for (var i=0; i<elements.length; i++) {
total += elements[i].value * elements[i].getAttribute("data-weight");
}
}
Logic being, get all elements with a certain class, loop through them, and for each element, get the value of the data-weight attribute and multiply it by the current form value for that element. Thanks to #Kris for the idea of doing it as a running total rather than a single calculation. That was really the breakthrough point.

Categories

Resources