Angular JS Form Validation - javascript

I'm working on an admin where users can add X amount of cells. Each cell consists of:
name
imageURL
destination link
User can bulk add cells (starts with 8, they could add 20 at once) or one at a time.
I need to validate each field to confirm that they are good. I had planned on using angular form validation for this. Unfortunately there is the requirement which states that should the user have X # of items, but only filled in half (leaves any entire cell empty) just disregard that cell as a whole.
The problem lies in that if there are 10 cells on load, the form (holds all the cells) is pristine / invalid. I fill in all 10 items, form is now dirty / valid. I add 5 more, form is dirty / invalid. fill out 2 of those cells and want to submit, form is still dirty / invalid when I would want it to be dirty / valid
Any thoughts on this?
Example plunkr: http://plnkr.co/edit/qwObH5LnxLvgJydJlJVS?p=preview
Bonus points on if I can do this without having to use a form tag.

It sounds like you want empty rows to be valid, but empty input fields in a non-empty row to be invalid.
To achieve this, you can add conditional requirements to each field using ng-required, so that it is only required if there is at least some text elsewhere in the row.
From your plunkr, you can replace required with ng-required on each input:
<li ng-repeat="cell in cells">
<input type="text" name="dest" ng-model="cell.dest" placeholder="Destination Link" ng-required="cell.src || cell.name"/>
<input type="text" name="src" ng-model="cell.src" placeholder="Image Link" ng-required="cell.dest || cell.name"/>
<input type="text" name="cellName" ng-model="cell.name" placeholder="Name" ng-required="cell.src || cell.dest"/>
</li>
To improve scalability, you could also define a method on the cell objects or the controller to evaluate whether a cell object is blank:
function cellCtrl($scope) {
...
$scope.isBlankCell = function(cell) {
...
}
}
and call that method from the template:
<li ng-repeat="cell in cells">
<input type="text" name="dest" ng-model="cell.dest" placeholder="Destination Link" ng-required="isBlankCell(cell)"/>
<input type="text" name="src" ng-model="cell.src" placeholder="Image Link" ng-required="isBlankCell(cell)"/>
<input type="text" name="cellName" ng-model="cell.name" placeholder="Name" ng-required="isBlankCell(cell)"/>
</li>

I saw your example on plunkr.
Adding a delete button, the user can delete the rows that do not want to fill. So the form comes back to the dirty/valid state.

Related

How do I make an html text input readonly but be able to update with a script?

I have these inputs that take the values of a from a in my table when I click on a row. I want to make it so that the user cannot change the input themselves but want to bring values into them when a user clicks a table row. I will be passing these inputs in as a form. I know that when the input is like this:
that it will not be updated. Is there any other way to do it with an input. Is there a different type of tag I can use that can be passed through a form?
Rather than a read-only <input>, I'd go with a combination of a display element and a hidden form element. Something like:
<div id="my-display">This is a value</div>
<input id="my-input" name="my-input" type="hidden" />
And in the code update both:
$('#my-display').text(yourValue);
$('#my-input').val(yourValue);
You can style the display to the user however you like and don't have to worry about whether or not it "de-activates" the form input.
If you really want it to be an inactive input, you can use the same approach:
<input class="my-input" type="text" disabled />
<input class="my-input" type="hidden" name="my-input" />
Which may even save you a line of code here, since both can now use .val():
$('.my-input').val(yourValue);
Try disabled keyword as here
<div id="my-display">This is a value</div>
<input id="my-input" name="my-input" type="text" disabled/>
You can change the value by javascript as below:
document.querySelector('#my-input').value = 'the value you want to enter by javascript';

Angular 2: Disable input field without removing from formgroup?

I am working on an Angular 2 project, where I am using forms and validation and have come to the following problem. I have a page with 3 fields:
height
weight
BMI
I would like ALL 3 fields to be in my form so I have done the following:
<input name="height" type="text" class="form-control" formControlName="height">
<input name="weight" type="text" class="form-control" formControlName="weight">
<input name="bmi" type="text" class="form-control" formControlName="bmi">
So far this works fine. Although, I want BMI calculated automatically. I have a function detecting changes on the two fields (height and weight) and calculates the BMI and outputs it in the BMI input field. This works as intended as well.
HOWEVER, I would like to disable the BMI input field in order to prevent the user from being able to type anything. So I have the 3 following criteria:
The input field here meant to serve as a read only field for the user.
I also want the BMI to be part of formgroup which I send to my database when all 3 fields are valid.
(optional, but very much wanted) I want the BMI field to be an input field with the result from height and weight as I have implemented it, not as plain text.
I have tried putting a [disabled]=true tag on the BMI input field which doesn't work and gives me a warning that I should add the disabled tag in the formgroup. When I do this or use this command: this.myForm.controls['BMI'].disable(); it DOES disable it as intended, but also removes it from the formgroup. This means when I submit my formgroup only the value of height and weight is sent, bmi is left out.
How can I do this?
Any help is greatly appreciated!
Have you tried placing a readonly attribute on the input?
<input name="bmi" type="text" class="form-control" formControlName="bmi" readonly>
Are you using some kind of UI framework at all?
http://semantic-ui.com/collections/form.html#read-only-field
formGroup.getRawValue() will return even the disabled fields,
Source

append required input into existing form

I've got a small-big problem with ajax. Let's describe the situation:
I've got a form with submit=javascript:function()
function will call AJAX with some values, and on success I want to append some content with 'required' input to existing form.
I was trying many things, most from: How to set HTML5 required attribute in Javascript? , but still cannot reach it.
example code:
<form id="myFormID" action="javascript:mycustomsubmit()">
<input type="text" id="add" style="margin:2px;" required>
<input type="submit" name="add" value="Add" class="btn btn-primary">
<textarea rows="5" id="custom_add"></textarea>
(...) on ajax success clear form values and insert new required input:
$("#add").val('');
$("#add").after('<input name="anotherinput" type="text" required>');
so after this my html code looks like this:
<form id="myFormID" action="javascript:mycustomsubmit()">
<input type="text" id="add" style="margin:2px;" required>
<input name="anotherinput" type="text" required="">
<input type="submit" name="add" value="Add" class="btn btn-primary">
<textarea rows="5" id="custom_add"></textarea>
</form>
And in fact it is (with this difference, that new input has required=""), but this new input is not required at all - I can send form even if this input is empty. I was trying to do it by append required, required="required", required=true, required="true", by append just input and then jQuery .prop or/and .attr, by JS examples from link - but it is still not working.
2nd question: After ajax append content and clear values I've got red border around required input field - is there any simple way to remove it (but to show this border and info if user will try to send form with this input empty) in FF,Chrome,IE ?
First post here...
Thanks in advance for any advices!
edit:
what is interesting: when I've submitted my form few times (so I've got few input fields) and I executed $("input").attr('required',true).prop('required', false); then obviously form haven't got any required inputs. However when I've executed it with prop "true" then only original input is really required, all added by append still can be empty...
This is a question consisting of multiple questions. So I'll try to identify and answer them separately.
How to append a new input field after your input field with ID "add" on submitting the form?
Try this instead (your selector was wrong):
$("#add").val('');
$("#add").after('<input name="anotherinput" type="text" required>');
How do I get rid of the red border?
I suggest that you use jQuery to handle the form submit (not tested):
$('#myFormID').submit(function(e) {
// Checking if all required fields are filled out.
if (!e.target.checkValidity()) {
// TODO: Not all required fields are filled out. Do something e.g. adding your new input field?
// Preventing form submit to continue. I think this should prevent the red border. Not tested though...
e.preventDefault();
}
else {
// Everything is OK. Do whatever is needed.
}
});
I'm not sure if I got your questions, but I hope it helps.
Try this,
$("input").attr('required',true);
or
$("#name_add").attr('required',true);

Is there a way to allow a checkbox to be marked only if there is data entered?

I have an ng-repeater with each row having an input of type checkbox, as well as 3 text fields. I want to allow the checkbox to be selected ONLY if the user enters some text in each of the 3 text fields. If the user tries selecting a checkbox without entering data first, I want to display a warning message.
I am assuming I have to do some checking for the three ng-models (for text fields) is null or undefined or something, but not sure how to do it in the HTML.
My HTML looks something like this:
<div ng-repeat="o in objects">
<input type="checkbox" class="myClass" ng-click="doSomething(argument)>
....
....
<input ng-model="model1">
<input ng-model="model2">
<input ng-model="model3">
EDIT: Found an answer here AngularJS - Form Custom Validation - Check if at least one input is empty
You could disable them and use ng-change to monitor that all 3 of the text inputs have value.
Sample html:
<input type="text" ng-model="data.item3" ng-change="update()"/>
<input type="checkbox" ng-model="data.model1" ng-disabled="checksDisabled"/>
Example Controller
.controller('MainCtrl',function($scope){
$scope.checksDisabled=true;
var data = $scope.data ={ };
$scope.update=function(){
$scope.checksDisabled = !(data.item1 && data.item2 && data.item3);
}
});
DEMO

How can I update an element attribute with a modified value?

I am working with MachForm and in it when using pricing features it adds this to an li tag:
<li id="li_273" data-pricefield="text" data-pricevalue="8.48" >
The form also has this field as well:
<input type="text" class="element text medium" id="element_273" name="element_273" size="30" value="" />
Now what happens is, the form has been converted to an ajax auto complete which is fine and works. But the problem is that the first reference:
<li id="li_273" data-pricefield="text" data-pricevalue="8.48" >
Isn't going to be the right price for the item selected. So what I need is to be able to re-write that data-pricevalue based on an onclick function. In the autocomplete you are able to execute an onclick javascript command like so:
'onclick' => 'alert(\'You clicked on the '.$name.' fruit!\');',
Now I have the rest of the javascript that should allow me to take the data-pricevalue from the id (ex: id="li_273") and then multiple it by the value entered into the text box. The ultimate goal is to get data-pricevalue * input text to update the on-screen total value. But I am not sure how to get that data-pricevalue to re-write the proper price.

Categories