I need help on populating an object with the value of a text input field in a dynamic created form. In my controller i declared $scope.models={}. The last input field in the form below which has a default value g.quant1 is populated by a value from the server but after submitting the form, the value is not passed. Viewing the object this way {{models | json}}shows empty, it only submits the last input value if the value is entered only then does models get populated with the value
<div class="list" ng-repeat="g in dcs | filter:{age:'26'}">
<div class="item item-input item-stacked-label">
{{g.zidname}} </br>L: <input type="text" id="lll{{$index}}" ng-model="models['l' + $index]" name="lf{{u.gidname}}"><p>{{$index}}</p>
</br>B: <input type="text" id="bbb{{$index}}" ng-model="models['b' + $index]" name="bf{{y.gidname}}">
<!--<p>data.b{{$index}}</p>-->
</br>D: <input type="text" id="ddd{{$index}}" ng-model="models['d' + $index]" name="df{{d.gidname}}">
<!--<p>data.d{{$index}}</p>-->
</br>NUM: <input type="text" id="nummm{{$index}}" ng-model="models['num' + $index]" name="numf{{y.gidname}}">
</br>Certified Rate: <input type="text" id="crrr{{$index}}" ng-model="models['cr' + $index]" name="cre{{y.gidname}}">
<input type="text" ng-model="models['quan' + $index]" ng-value="g.quant1" >
</div>
</div>
my controller
$scope.insert50=function(){
var link = 'http://...';
$http.post(link, {user: $scope.models
}).success(function(data){
alert(data);
});
}
I had a workaround with all your problems and created a separate plunker for the solution. I am not sure what you are doing with name. For validations of each field, you need to set unique name for it and you need to add required or ng-required attribute based on your requirement. In plunker, I included validation for the last field which you can refer. Can you check this and let me know whether everything is working fine as you expected?
Related
I have a few dropdownlist tag that is binding dynamic data, so I need to use [ngModelOptions]="{standalone: true}". I know that using ngModelOption means ignoring the form attribute, is there any more that can add the dirty attribute to text or dropdownlist.
HTML file
<form #form="ngForm">
<div #ngFor="let item of [].constructor(details.length); let i = index>
<input [(ngModel)]="person[i].age" id="age" name="age" [ngModelOptions]="{standalone: true}"/>
<kendo-dropdownlist [data]="personName" [(ngModel)]="person[i].name" id="name" name="name" [ngModelOptions]="{standalone: true}"></kendo-dropdownlist>
</div>
<input [(ngModel)]="city" id="city" name="city" />
<button (click)="checkDirty()">CHECK DIRTY</button>
</form>
typescript file
#ViewChildren('form', {static: true})
public form: NgForm;
details = ["one","two"];
personName=["A","B","C"];
city="";
person = [{"age":"", "name":""},{"age":"", "name":""}];
checkDirty(){
console.log(this.form.dirty);
// when i type something in the city input, and click check dirty button, it return true
// however, if i type anything in age input or select any value in name and click check dirty button, it always return false.
}
I know that adding [ngModelOptions]="{standalone: true} basically means ignore the attribute in form. Is there any way that can add the dirty attribute manually for the dropdownlist name and input age?
I have three input fields I am attempting to enforce validity on. Currently, I have them all set as required, but removing the modifier with Javascript on submit if one of them is filled out; essentially, one must fill out at least one, but not none of these fields.
Here is an example of the fields:
jQuery(function ($) {
var $inputs = $('input[name=Input1],input[name=Input2], input[name=Input3]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', $(this).val().length > 0 && $(this).val() != 0)
});
});
jQuery(function ($) {
$("#Input1, #Input2").oninvalid = (function() {
$(this).setCustomValidity("Please enter a valid Input1, Input2, or Input3")
});
});
var Input3default = document.getElementById('Input3')
if (Input3.value.length == 0) Input3.value = "0";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="input-group mb-3">
<form action="" method="get" autocomplete="off">
<div class="row" style="text-align:justify; width: 100%; display:inline">
<div class="">
<label for="text3">Input1:</label>
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" />
</div>
<div class="">
<label for="text4">Input2:</label>
<input type="text" id="Input2" name="Input2" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')"/>
</div>
<div class="">
<label for="text5">Input3:</label>
<input type="text" id="Input3" name="Input3" required placeholder="0" pattern="[0-9]*" onsubmit="Input3default" oninvalid="this.setCustomValidity('Please enter a valid Input3')"/>
</div>
</div>
<p>
<input type="submit" value=" Submit " />
</p>
</form>
</div>
</div>
This seems to work fine if I leave it default; I have Input1 and Input2 empty by default, and Input3 has a value of "0" by default. If I enter Input1 or Input2, my submission goes through just fine. However, the problems begin if I alter Input3.
Problem 1: Any time I enter Inputs 1 and 2 but leave 3 blank, it triggers invalidity; my Input3default never seems to trigger, and it is passed blank and caught by the oninvalid tag.
Problem 2: Along with that, if I do not specify an Input2 along with my Input1 while Input3 is blank, it triggers invalidity on Input2. Using Chrome Debugger, I can see that the Required tag is removed, but my OnInvalid pop-up still comes up no matter what is remedied.
Essentially, I am trying to solve the second problem: When I remove the required html tag from my input, after invalidating another input with a Javascript-enforced default, my inputs refuse to validate on the front end.
I appreciate any advice and conjecture as to why this may be the case, and believe that the two problems are connected.
EDIT: Upon adding an = to my original oninvalid JQuery function, I removed a JS error. It appears that my Input3 default function triggers on pageload, but not on submit; I added an onsubmit function to input3, but am still receiving oninvalid events for input2.
I was able to fix this issue on my own, using the OnInput event.
The setCustomValidity function, when triggered, does not allow a submission while a CustomValidity is set. In order to fix this, I edited my inputs as so:
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" oninput="this.setCustomValidity('')"/>
I still have a few kinks to iron out, but this fixed my main problem in that the validity of an input was not being reset.
I'll leave this answer unaccepted at first to allow others to pitch in.
I'm trying to render a validation summary on a page using AngularJS. Here's what I have so far:
<div ng-app>
<div ng-controller="ctrl">
<form name="userForm">
<fieldset>
<legend>User Info</legend>
<p><label>Name: <input type="text" required ng-maxlength="15" name="name" ng-model="name" /></label></p>
<p><label>Age: <input type="number" required name="age" ng-model="age" /></label></p>
<p><label>Favorite Color: <input type="text" required name="favColor" ng-model="favColor" /></label></p>
<p><input type="button" value="Submit" ng-click="submitForm()" /></p>
</fieldset>
</form>
<div id="validationSummary" ng-show="hasValidationErrors()">
<ul>
<li ng-repeat="error in validationErrors">{{ error }}</li>
</ul>
</div>
</div>
</div>
In my controller, I'm creating an array with all of the errors.
function ctrl($scope) {
$scope.hasValidationErrors = function () {
return $scope.validationErrors && $scope.validationErrors.length > 0;
};
$scope.submitForm = function() {
$scope.validationErrors = [];
for (var property in $scope.userForm) {
if ($scope.userForm.hasOwnProperty(property) && $scope.userForm[property].$invalid) {
$scope.validationErrors.push($scope.userForm[property].$name);
}
}
}
}
The thing I can't figure out is: how can I get more than just the name of each field that is invalid? I've noticed that there is also an $error property on each field. Outputting this instead of $name gives me the following:
{"required":true,"maxlength":false}
{"required":true,"number":false}
{"required":true}
So I can get the field name, and I can get an object that describes what is wrong with that particular field. How can I define an error message, so that if a field is required it will output "{name} is required"? It seems like this could be a data- attribute on the input element itself, although I don't know how I would access that attribute.
Of course, it's also possible that I'm making things entirely too difficult on myself. Is there a better way to approach this while staying in the "AngularJS" world?
Here's a link to the jsFiddle I've been working on.
A far easier and cleaner way is demonstrated here
Simply put (where form1 is your form name attribute):
<ul>
<li ng-repeat="(key, errors) in form1.$error track by $index"> <strong>{{ key }}</strong> errors
<ul>
<li ng-repeat="e in errors">{{ e.$name }} has an error: <strong>{{ key }}</strong>.</li>
</ul>
</li>
</ul>
A totally dynamic validation summary based on AngularJS 1.5.7 with ngMessages using field names that the user recognizes
A template with error messages:
<script type="text/ng-template" id="error-messages">
<span ng-message="required">This field is required.</span>
<span ng-message="email">Please enter a valid email.</span>
</script>
Display of the error summary (here for a form named "candidateForm"):
<div data-ng-if="candidateForm.$submitted && candidateForm.$invalid">
Please correct these fields and then try to send again:
<ul>
<li data-ng-repeat="field in candidateForm" data-ng-if="candidateForm[field.$name].$invalid">
<div>
{{ getValFieldName(field) }}
<span data-ng-messages="candidateForm[field.$name].$error" role="alert">
<span data-ng-messages-include="error-messages"></span>
</span>
</div>
</li>
</ul>
</div>
A helper function to get the name of the label associated with the input field (instead of displaying input field names or "internal ID codes" to users):
$scope.getValFieldName = function (field) {
return $("label[for=" + field.$name + "]").text(); // to get label associated with input field
// return $("#" + field.$name).attr("placeholder"); // to get placeholder of input field
};
You can reuse this set of standard error messages on multiple forms, ngMessages ensure only one error displayed per field, and looks like the fields are listed in the order they appear in the HTML.
Should probably be made into a directive instead of the jQuery-style helper function, and might even want to add a click-handler on each error message to scroll to the input field with the error. Maybe another will run with that idea?
Use below line to get values of every text box
var value = $scope.userForm[property].$name;
var vl =$('*[name="' + value + '"]').data('required-message')
$scope.validationErrors.push(vl);
I'm using a Kendo edit box that a user can enter the different parts of a SQL connection string (server name, database, user name and password). I also have a text box that will show the user the entire connection string as they type.
My question is how can I data-bind each of the four text boxes (server, database, user and password) to one text box as the user enters data into each one.
Also, the user requested seperate fields.
Thanks in advance,
Dan Plocica
Doing it using Kendo UI would be:
HTML:
<div id="form">
<label>Server : <input type="text" class="k-textbox" data-bind="value: server"></label><br/>
<label>Database : <input type="text" class="k-textbox" data-bind="value: db"></label><br/>
<label>User : <input type="text" class="k-textbox" data-bind="value: user"></label><br/>
<label>Password : <input type="password" class="k-textbox" data-bind="value: password"></label><br/>
<div id="connections" data-bind="text: connection"></div>
</div>
JavaScript:
$(document).ready(function () {
var model = kendo.observable({
server : "localhost:1521",
db : "database",
user : "scott",
password : "tiger",
connection: function () {
return this.get("user") + "/" +
this.get("password") + "#" +
this.get("server") + ":" +
this.get("db");
}
});
kendo.bind($("#form"), model);
});
In the HTML there are two parts:
The input files where I define each input to what field it is bound in my model.
A div where I found its text to connection function in my model that creates a string from the different values.
This is automatically updated and you can freely edit each input.
You might decorate the input as I did setting it's CSS class to k-textbox, that's optional. The only important thing is the data-bind="value : ...".
The JavaScript, is just create and Observable object with the fields and methods that we want.
Running example here: http://jsfiddle.net/OnaBai/xjNMf/
I will write solution using jQuery JavaScript library, and you should use jQuery because its much easier and easier to read and also to avoid errors in different browsers.
**HTML**
Server: <input type="text" id="server"/><br/>
Database: <input type="text" id="database"/><br/>
Username: <input type="text" id="username"/><br/>
Password: <input type="text" id="password"/><br/>
<br/>
Full CS: <input type="text" id="solution"/><br/>
JS
<script type="text/javascript">
var _template = 'Data Source=%server%;Initial Catalog=%db%;Persist Security Info=True;User ID=%user%;Password=%pass%';
$(document).ready(function(){
$('#server,#database,#username,#password').keyup(function(){ updateSolution();});
});
function updateSolution(){
var _t = _template.replace('%server%', $('#server').val()).replace('%db%', $('#database').val()).replace('%username%', $('#username').val()).replace('%pass%', $('#password').val());
$('#solution').val(_t);
};
</script>
I have 1 field that will be used for the users name, and another that will be used for the users URL
so if a user types john smith into the name input, i would like to automatically populate the URL input with john-smith since the url will end up being /personal-trainer-directory/john-smith
how do I do this automatically so the user doesnt have to fill out the url field?
Here is an example but there is some ExpressionEngine code, thats why there are curly brackets, but I figure this is more related to the code instead of the CMS so posting this here.
this is what I currently have:
<div class="formsection clearfix">
<label for="title">Name</label>
<span class="directions">The name you want to be displayed in your listing.</span>
<input type="text" name="title" id="title" value="{title}" size="50" maxlength="100">
</div>
<div class="formsection clearfix">
<label for="url_title">URL Title</label>
<span class="directions">Put a dash between first and last name. example: "john-smith"</span>
<input type="text" name="url_title" id="url_title" value="{url_title}" maxlength="75" size="50">
</div>
$("#title").change( function () {
$('#url_title').val('/personal-trainer-directory/'+$(this).val().toLowerCase().replace(/ +/g, '-').trim());
});
jsFiddle example
You can do something like this
$(function(){
$("#title").blur(function(){
$("#url_title").val('/personal-trainer-directory/' + $(this).val());
});
});
jsFiddle
or if you want it to be populated as you type
$(function(){
$("#title").keyup(function(){
$("#url_title").val('/personal-trainer-directory/' + $(this).val());
});
});
jsFiddle