How to count filled text box in angular 2 - javascript

I have six text boxes and I want to count the number of filled boxes
<input type="text" #tb1 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb2)" />
<input type="text" #tb2 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb2)" />
<input type="text" #tb3 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb3)" />
<input type="text" #tb4 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb4)" />
<input type="text" #tb5 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb5)" />
<input type="text" #tb6 placeholder="Weight" class="form-control"(ngModelChange)="counterfunc(tb6)" />
{{counter}}
counter: number = 0;
counterfunc(tb){
// need help here
if (tb.value != '') {
this.counter++;
}
}
I found this plunker plunkr but this is for checkboxes. how can I count the number of the filled text boxes? and a number of counts should decrease one if user empty the box. Thank you

I don't see the point of declaring seleveral variables for a component (well, input) that behaves exactly the same in any case. You should declare a list of inputs, not a variable for every input.
Use the children decorator for that
<ng-container *ngFor="let i of [0, 1, 2, 3, 4, 5]">
<input type="text" #textboxes placeholder="Weight" class="form-control" (input)="input()"/>
</ng-container>
<p>{{filledCount}}</p>
In your TS
filledCount: number = 0;
#ViewChildren('textboxes') textboxes: QueryList<ElementRef>;
input() { this.filledCount = this.textboxes.filter(t => t.nativeElement.value).length; }
Here is a working stackblitz.

try this and just take this as a key
counter: number = 0;
counterfunc(tb){
if (tb.value != '' && tb.value.length == 1) {
this.counter++;
}
if(tb.value == '')
{
this.counter--;
}
}

Create a form and add validation to the form. On every change count the valid or invalid fields

Related

Fill textboxes sequentially

I have 5 textboxes (With pre-populated data) representing address lines 1,2,...5 respectively. The requirement is to check if TEXTBOX 1 is empty, then shift data from textbox 2 to 1, textbox 3 to 2 and so, on. This is to make sure there aren't any empty textboxes in between the sequential textboxes. How do I achieve it in Jquery? If all textboxes are empty, I will show required field error.
Here I am just trying to save data in a variable.
custData.CustAddr1 = $("#txtCustAddr1" + value).val().trim() == "" ? $("#txtCustAddr2" + value).val() : $("#txtCustAddr1" + value).val();
In the above code I need to check all the 5 textboxes, If txtbox1 is empty, use data from textbox 2, else from 3 else 4 else 5.
Vanilla JavaScript (jQuery solution below)
Here is a solution that does not use jQuery. It uses linear time and does not update textbox values when this is not needed, so it is no problem to call this often.
The idea on a high level is to keep track of which is the first empty textbox and, while looping over all textboxes, move textbox values to this empty one as we encounter them.
You can display an error if at the end of this function, the first empty textbox is still the first one (firstEmpty === 0 in the below demo code).
function enforceSequential(selector) {
var firstEmpty = -1, current = -1,
textboxes = document.querySelectorAll(selector);
for (let textbox of textboxes) {
current++;
if (textbox.value === '') {
if (firstEmpty < 0) {
firstEmpty = current;
}
} else if (firstEmpty >= 0) {
textboxes[firstEmpty].value = textbox.value;
textbox.value = '';
firstEmpty++;
}
}
}
document.getElementById('run').addEventListener('click', () => enforceSequential('.box'));
input {
display: block;
margin: 0 0 1em 0;
}
<input type="text" class="box" value="foo" />
<input type="text" class="box" value="" />
<input type="text" class="box" value="bar" />
<input type="text" class="box" value="" />
<input type="text" class="box" value="" />
<input type="text" class="box" value="baz" />
<button id="run">Run script</button>
jQuery variant
Of course, if you want to use jQuery, you can.
function enforceSequential(selector) {
var firstEmpty = -1,
textboxes = $(selector);
textboxes.each((current, textbox) => {
textbox = $(textbox);
if (textbox.val() === '') {
if (firstEmpty < 0) {
firstEmpty = current;
}
} else if (firstEmpty >= 0) {
textboxes.eq(firstEmpty).val(textbox.val());
textbox.val('');
firstEmpty++;
}
});
}
$('#run').on('click', () => enforceSequential('.box'));
input {
display: block;
margin: 0 0 1em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="box" value="foo" />
<input type="text" class="box" value="" />
<input type="text" class="box" value="bar" />
<input type="text" class="box" value="" />
<input type="text" class="box" value="" />
<input type="text" class="box" value="baz" />
<button id="run">Run script</button>
I think the best method would be :
Get all textboxes values that are not empty as a JS array
If array is empty, display your error
Else, empty textboxes values
Then fill textboxes (in correct order) with array values

Prevent users from entering a value greater than 2 digits in an input field

I have a HTML form field to get the month from the user.
<input type="text" placeholder="MM" size="2" name="month">
I need the field to accept only 2 digits. I tried Form validation, but it allows the user to enter more than 2 digits and then display the validation message. I don't need any validation messages for the field, but the user should be restricted to enter only 2 digits max. Is there a way we can do this using jquery?
<input type="text" placeholder="MM" size="2" name="month" maxlength="2>
The maxlength attribute;
<input type="text" placeholder="MM" size="2" maxlength="2" name="month">
It limits the amount of text you can enter by straight up not allowing you to type more.
EDIT: added snippet
The easiest is using the type='number' attribute and setting max='12':
<input type='number' max='12' min='1'>
SNIPPET
input {
width: 4ex;
padding: 0 1px;
}
input:last-of-type {
width: 6.5ex;
}
<fieldset>
<legend>Enter Date</legend>
<label>Month:</label>
<input type='number' max='12' min='1'>
<label>Day:</label>
<input type='number' max='31' min='1'>
<label>Year:</label>
<input type='number' max='3000' min='2016'>
</fieldset>
This should help you out, whenever the user presses the key down it will check the lenght and then trim the extra chars if there are any:
$("input").keydown(function() {
var value = $(this).val();
if(value.length > 2) {
value = value.substring(0, 2);
$(this).val(value);
}
});

dijit ValidationTextBox how to add minlength and maxlength

I would like to know how (with simple working example) to add maxlength and minlength to input tag generated by
dijit/form/ValidationTextBox
Example of desired output:
<input maxlength="10" minlength="2" class="dijitReset dijitInputInner" data-dojo-attach-point="textbox,focusNode" autocomplete="off" name="title" type="text" tabindex="0" id="Image-1-title-LabelValidationTextBox" aria-required="undefined" value="Title text for image Image-1" aria-invalid="false">
try this example with regex constraint
<input type="text" value="someTestString" required="true"
data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="regExp: '[a-zA-Z0-9$%!_]{2,10}', invalidMessage: 'The value must be at least 2 character and maximum 10'" />
ValidationTextBox has the properties minLength and maxLength. They are used in the following why in a declarative manner.
<input data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="required:true,
maxLength:5,
minLength:2"
type="text"
name="exmaple" />
Here's another solution:
registry.byId("validationTextBox").validator = function(value, constraints) {
if(value) {
return value.length >= 2 && value.length <= 10;
}
return true;
}

Can't get JavaScript SSN Form Validation to work

I am new to JS and trying to get it so when someone enters a SSN number in a field, it gives them an alert telling them to NOT put a SSN number in there.
HTML:
<form name="card" action="#">
<input type="text" name="field" class="name social" size="60" placeholder="First and Last Name">
<input type="text" name="field" class="phone social" size="60" placeholder="Phone Number">
<input type="text" name="field" class="email social" size="60" placeholder="Email(name#example.com)">
<select class="select">
<option value="My card has not yet arrived">My card has not yet arrived
<option value="Direct Deposit">Direct Deposit
<option value="Suggest a Card">Suggest a Card
<option value="Issues with CARD.com">Issues with CARD.com
<option value="Other">Other
</select>
<textarea name="field" class="text social " cols="60" rows="5" placeholder="How can we help you?"></textarea>
<input type"submit" name="submit" class="subBtn" value="Submit" onclick="warnCC(document.card.field)">Submit</input>
</form>
JS:
<script>
function warnCC()
{
var ssn = document.getElementsByTagName("input");
// document.getElementsByClassName("social");
var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
if (ssn.value.match(pattern))
{
return true;
alert("Please Do Not Enter SSN Info Into This Form");
}
else
{
return false;
alert("yay!")
}
}
</script>
Any help on where I cam going wrong would be very helpful. I'd also prefer it was done on a "onfocusout" if anyone can give me advice on that.
getElementsByTagName and getElementsByClassName both return a list of elements. That list doesn't have a value property. Each of the items on the list has a value property, but not the list.
You'll want to loop through the list of inputs and handle each of them as appropriate, e.g.:
var list = /*...get the list using either method you have in your code...*/;
var index, input;
for (index = 0; index < list.length; ++index) {
input = list[index];
// input.value will be the value of this particular input
}
Side note: querySelectorAll has better support than getElementsByClassName (IE8 has it, for instance, but not getElementsByClassName), so if you want to get a list using a class, you're best off with:
var list = document.querySelectorAll(".the-class-here");
You should also do the alert() before returning from the function ... if you want the alert() dialog to be displayed.
I tweaked your function. You can see it inaction here: http://jsfiddle.net/tBqP2
function warnCC() {
var formElements = document.getElementsByTagName("input");
for (var k in formElements) {
// document.getElementsByClassName("social");
var pattern = /^[0-9]{3}\-?[0-9]{2}\-?[0-9]{4}$/;
if (formElements[k].value.match(pattern)) {
alert("Please Do Not Enter SSN Info Into This Form");
return false;
}
}
return true;
}

Javascript IF ELSE statement stopping short

So we have here my code for a GPA calculator. Ive got everything in line but I cant seem to figure out why my IF ELSE statement is stopping short and converting all letter grades to a value of "4".
I have tried putting the statement outside of the for loop that is handling the grades and pushing them to to gVals[] I have tried putting them completely outside of the function in their own function. I have tried alot of different things except apparently the thing that works.
I know there are simple ways of doing this but I am trying to execute this app with a minimalist mentality.
The code:
function calcGPA() {
//Variable Sections
var grades = document.querySelectorAll("#letGrade input[type=text]");
var contacts = document.querySelectorAll("#conHours input[type=text]");
var gVals = [];
var cVals = [];
var failGrade = "The Letter Grade input may only be capitol letters A,B,C,D or F";
var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
var checkGrade = /^[ABCDF]/;
var checkhours = /^[12345]/;
//Grab the Letter grades and process them
//Should validate all inputs in the letGrade div to capitol A, B, C, D or F
//Should Convert all inputs in the LetGrade div to A = 4,B = 3,C = 2,D = 1,F = 0
//Should push resulting conversion to gVals[]
for (var i = 0; i < grades.length; i++) {
if (!checkGrade.test(grades[i].value)) {
alert(failGrade);
return false;
}
if (grades[i].value == "A"){
gVals.push("4");
}
else if (grades[i].value == "B"){
gVals.push("3");
}
else if (grades[i].value == "C"){
gVals.push("2");
}
else if (grades[i].value == "D"){
gVals.push("1");
}
else if (grades[i].value == "F"){
gVals.push("0");
}
//Should validate all inputs in the conHours div to 1, 2, 3, 4 or 5
//Should push all resulting values to cVals[]
if (!checkhours.test(contacts[i].value)) {
alert(failHours);
return false;
}
cVals.push(contacts[i].value);
}
console.log(gVals, cVals);
document.getElementById("cumGPA").innerHTML = (gVals[0] * cVals[0]);
};
The issue I am having is that the IF ELSE statement to do the conversion from letter grade to quality point value is returning everything back as 4 instead of matching it with its resulting letter grade componant.
Thank you for any help with this in advanced and please if you could dont answer the question outright please explain where I went wrong so I can learn from this.
EDIT: ADDED HTML FOR PROSPERITY! AND "FIXED" JAVASCRIPT!
<div id="calcWrapper">
<form id="calc" name="calc" onsubmit="calcGPA(); return false;">
<div id="letGrade">
<input tabindex="1" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="3" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="5" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="7" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="9" type="text" maxlength="1" placeholder="Letter Grade..." />
<input tabindex="11" type="text" maxlength="1" placeholder="Letter Grade..." />
<label>Cumulative GPA:</label><output id="cumGPA" type="text" />
</div>
<div id="conHours">
<input tabindex="2" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="4" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="6" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="8" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="10" type="text" maxlength="1" placeholder="Contact Hours..." />
<input tabindex="12" type="text" maxlength="1" placeholder="Contact Hours..." />
<input type="submit" value="Calculate" />
</div>
</form>
</div>
The reason why it's not working is because in your if statement, you're using a single equals. A single equals is setting grades[i] equal to 'A' - it's not actually evaluating grades[i] == 'A'.
You want to change single = to == for comparison
if (grades[i] == 'A'){
Something like this in your code:
if (grades[i] == 'A'){
gVals.push("4");
}
else if (grades[i] == 'B'){
gVals.push("3");
}
else if (grades[i] == 'C'){
gVals.push("2");
}
else if (grades[i] == 'D'){
gVals.push("1");
}
else if (grades[i] == 'F'){
gVals.push("0");
}
Note:-
Double equality == is used for comparison and single = is used for assignment in Javascript.
Also as Andy well pointed that in comments that your both the for loops are using the same index i which may cause problem to you(atleast not a good practice). It would be better if you create a new variable for second for loop. It is unclear what you want to achieve with both the for loops but I think that it can be done with single for loop also.
As it was pointed in other answers you should use comparison operator == instead of assign operator = in if conditions, and also don't forget that grades[i] are DOM objects and not some plain values - so you have to compare with some property of this objects (if you want to compare with input's text use value property)
if (grades[i].value == "A"){
gVals.push("4");
}
else if (grades[i].value == "B"){
gVals.push("3");
}

Categories

Resources