angular set form data for all fields - javascript

I am still new in angular, I don't know how to make form when I want to update user to fill the form with his own data. I have controller like this:
// take data for organization from database
dataService.allOrganization().then(function (data) {
vm.allOrg = data;
});
// take data for user from database
dataService.getOneUser(theId).then(function(data) {
vm.oneUserUpdate = data;
});
$scope.user = {};
$scope.submitForm = function(theId) {
$scope.user.idUser = theId;
dataService.updateUserPost($scope.user).then(function (data) {
vm.oneUserInfo = data;//response from http request
})
}
And in view:
<form name="userForm" ng-submit="submitForm(userDataCtr.oneUserUpdate.identities[0].user_id)">
<div class="form-group">
<label>Encryption Key :</label>
<input type="text" class="form-control" name="encryption" ng-model="user.encryption" >
</div>
<div class="form-group">
<label>Admin :</label>
<select class="form-control" name="admin" ng-model="user.admin">
<option>Select...</option>
<option value="true">True</option>
<option value="false">False</option>
</select>
</div>
<div class="form-group">
<label>Organization ID:</label>
<select class="form-control" name="organization" ng-model="user.organization">
<option>Select...</option>
<option ng-repeat="org in userDataCtr.allOrg" value="{{org.id_org}}">
{{org.name_org}}
</option>
</select>
</div>
<div class="form-group">
<label></label>
<div class="checkbox">
<label><input type="checkbox" value="1" name="role_cro" ng-model="user.role_cro">ROLE_CRO</label>
</div>
<div class="checkbox">
<label><input type="checkbox" value="1" name="role_client" ng-model="user.role_client">ROLE_CLIENT</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And how, if is possible, to fill all data with user data, input field to have value, checkbox to be checked if they need, select option of organization to be selected, etc.
Thanks.

You have to update models. eg
dataService.getOneUser(theId).then(function(data) {
vm.user={};
vm.user.encryption = data.encryption;
vm.user.role_client = data.role;
});
On view
<div ng-controller="Mycontroller as my">
<div class="form-group">
<label>Encryption Key :</label>
<input type="text" class="form-control" name="encryption" ng-model="my.user.encryption" >
</div>
</div>
And so on... you have to use in your controller instance on your view.

Whenever you want to use data from a controller (or directive) inside a template, it has to be bound to the controller's $scope.
.controller('myFormController', function () {
dataService.allOrganization().then(function (data) {
// Populate our scope the required data
$scope.allOrg = data;
});
});
Now we can bind these variables to our form fields using ng-model.
<input type="text" name="firstName" ng-model="allOrg.firstName">
Not all form elements behave the same. You should take a look at the angular docs for more in depth examples of form binding.
Angular form documentation

Related

Form in HTML with button assigns the value of the last button, no matter which one was selected

I want to create a form with HTML with different types of inputs (such as name, surname, dates, and radio-button options), and when I want to print the object with the data inputted in the form on the console, the value from the radio-buttons is not stored correctly.
First of all, this is my first project on this area and also my first posted question on stackoverflow, so I would appreciate some suggestions on how to pose the question better if I'm forgetting some crucial data.
I have been following help from different resources (mostly youtube videos such as: https://www.youtube.com/watch?v=GrycH6F-ksY ) to create this form and submit the data with AJAX, and the code of my javascript application comes mainly from that video.
All the data is stored correctly and I can see it in the console, except from the data comming from the radio-buttons. No matter what option is selected (either "male" or "female"), the console always shows the value of the last button, which in this case is "female". I suppose I am doing something wrong when defining these buttons, and why they are not being "selected" (I suppose that's what is happening since the data shown is always the last default value) but I haven't been able to find out where I am doing something wrong.
I'm including the part of the code that I think might be relevant
<form action="ajax/contact.php" method="post" class="ajax">
<div class="form-row">
<div class="form-group col-md-6">
<label>Name</label>
<input type="text" class="form-control" name="inputName" required>
</div>
<div class="form-group col-md-6">
<label>Surname</label>
<input type="text" class="form-control" name="inputSurname" required>
</div>
</div>
<div class="form-group">
<label>Date of birth</label>
<input type="date" class="form-control" name="inputDate">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="inputEmail" required>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<label>Gender</label>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="male">Male</div>
</div>
<div class="form-group col-md-4">
<div class="radio-inline"><input type="radio" name="inputGender"
value="female">Female</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Number of children</label>
</div>
<div class="form-group col-md-6">
<input type="number" class="form-control" name="inputNumber">
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Javascript function
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
return false;
});
PHP file
<?php
if (isset($_POST['inputName'],$_POST['inputSurname'],$_POST['inputDate'],$_POST['inputEmail'],$_POST['inputGender'],$_POST['inputNumber'])) {
print_r($_POST);
}
In the console I'm getting this:
${inputName: "myName", inputSurname: "mySurname", inputDate: "2019-12-13",
$inputEmail: "myMail#gmail.com", inputGender: "female", …}
$inputDate: "2019-12-13"
$inputEmail: "myMail#gmail.com"
$inputGender: "female"
$inputName: "myName"
$inputNumber: "1"
$inputSurname: "mySurname"
$_proto_: Object
but I thought it would be showing:
$...
$inputGender: "male"
$...
when the male option is selected.
Thank you very much
The problem is in your JS. You're looping through everything with a name attribute, in order, and adding its value to your submit data. In the case of radio buttons, you have to check if they're selected and only add if so, otherwise, the last one always wins, as you're seeing.
And since you appear to be using jQuery, you can probably just let its serialize helper do this work for you.

How to change disable input placeholder every selected dropdown value

I'm making a form that have a group selected dropdown that consist of string stored from database (i did a #foreach loop through database via eloquent model to assign the dropdown value lists), on the below of the dropdown i have 3 disable inputs that are the column from database that have a correlation with the value of dropdown. I want that placeholder of disable input automatically change the value to be same as the record with the dropdown value's record from database once i select a value from dropdown. What should i do? What JS script should i use for?
blade.php
<form class="form-horizontal">
<fieldset>
<div class="control-group">
<label class="control-label" for="selectError2">Plat Nomor</label>
<div class="controls">
<select data-placeholder="Pilih Nomor Polisi" id="selectError2" data-rel="chosen">
<option value=""></option>
#foreach ($park as $p)
<option value="{{$p->id}}">{{$p->nopol}}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="disabledInput">Jenis Kendaraan</label>
<div class="controls">
<input class="input-large disabled" id="disabledInput" type="text" placeholder="{{$p->jenis}}" disabled="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="disabledInput">Kategori Kendaraan</label>
<div class="controls">
<input class="input-large disabled" id="disabledInput" type="text" placeholder="{{$p->kategori}}" disabled="">
</div>
</div>
<div class="control-group">
<label class="control-label" for="disabledInput">Waktu Masuk</label>
<div class="controls">
<input class="input-large disabled" id="disabledInput" type="text" placeholder="{{$p->created_at}}" disabled="">
</div>
</div>
You refer my sample code:
http://jsfiddle.net/18pa7m0q/11/
function change(select)
{
var value=select.options[select.selectedIndex].value;
$(".input-large").attr("placeholder",value);
}
Huh finally i got the answer from one of my friend.
First, add attribute id="your_id" on every input that corresponds with dropdown's record.
After that, add this line of <script>
`
// Transform PHP variable into json, so it can be cached into js variable
// Adjust the param with #json($your_table_name)
const park = #json($park);
function change(select) {
// Get the id (which is in the value) of the selected option
let id = select.options[select.selectedIndex].value
// Find the data in the cached json
let parkData = park.find(function (p) {
// Find it by id
return p.id == id
})
// For each fields to be shown in the page...
// Each member of array are the same id from the <input> tag
// In this case i want three columns to be shown in the page..
for (let field of ["jenis", "kategori", "created_at"]) {
// Put the data to the corresponding element
document.getElementById(field).value = parkData[field]
}
}
`
Voila! It changed the value of disabled input each time i select the value of dropdown.
It does only need the Plain JS with no jQuery or any other JS framework. So simple :D

How to assign values to control using angularjs

I have a detail view and from database only single record is comming, I need to assign data to controls. below is my code
var app = angular.module("MyProductApp", []);
app.controller("ProductsController", function ($scope, $http) {
var ProductID = #Html.Raw(Json.Encode(ViewData["ProductID"]));
$http.get('/api/Products/GetProductForEditOrDetail',{params: { ProductID : ProductID }}).
success(function(data){
$scope.Product = data;
}).
error(function(data){
alert("msg");
});
});
and below is html code
<div ng-app="MyProductApp" class="form-horizontal">
<div ng-controller="ProductsController">
<h4>Product</h4>
<hr />
<div class="form-group" >
<label class="control-label col-md-2">Product Name</label>
<div class="col-md-10">
<input id="txtProductName" type="text" class="form-control" name="txtProductName" disabled="disabled" Value="{{Product.ProductName}}" />
<input id="hdnProductID" type="hidden" class="form-control" name="hdnProductID" value="{{Product.ProductID}}" />
<input id="hdnCategoryID" type="hidden" class="form-control" name="hdnCategoryID" value="{{Product.CategoryID}}" />
</div>
</div>
</div>
</div>
You should use ngModel directive
The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
<input ng-model="Product.ProductName" />
ngModel is what you are looking for, read the docs !
You wanted to pass value with hidden fields, so ng-model would not work in that case, you could use ng-value in that case
<input id="hdnCategoryID" type="hidden" class="form-control" name="hdnCategoryID" ng-value="Product.CategoryID" />

How to store data/parameters in html using angular?

If I have a comment thread, and I want to reply to the comment thread I would have to
return $http.post('/reply/', {
user: username,
test: text ,
parent: parent
}).then(registerSuccessFn, registerErrorFn);
The html would be something in the line of
<form role="form" ng-submit="vm.reply()">
<div class="form-group">
<label for="user">User</label>
<input type="text" class="form-control" id="user" ng-model="vm.user" placeholder="ex. john" />
</div>
<div class="form-group">
<label for="text">text</label>
<input type="text" class="form-control" id="text" ng-model="vm.text" placeholder="text" />
</div>
<div class="form-group">
<label for="parent">parent</label>
<input type="text" class="form-control" id="parent" ng-model="vm.parent" placeholder="parent" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
But the thing is that parent, and the user should be dynamically generated, how do I generate the form dynamically so that each form in html correctly stores the parameter for parent and user such that it reflect the parent of the post and user comment on it?
You can bind the page the form is on (or alternatively just the form itself) to a controller e.g. MyFormController. Then when initially loading the page/form, make sure to load the parent and user information and store in your $scope.vm model.
NB - I'm of course assuming that you have the parent and user information in your database since you said they will be dynamically generated.
var loadData = function () {
$http.get(user_url).success(function (user) {
$scope.vm.user = user;
});
$http.get(parent_url).success(function (parent) {
$scope.vm.parent = parent;
});
};
loadData();
That's about all you'll need to do and the data will be binded to your form.
Cheers

How to $setdirty to a single input

I've got a little problem. I want to set to dirty a single input, I mean, because when I give a value automatically it stays in pristine class, doesn't change, and doesn't save the new value.
If I edit it, it works and change the class. I want to cancel that pristine class.
If anyone know please let me know.
<form class="form-horizontal" ng-repeat="studiant in studiants" name="form" id="form">
<input type="hidden" name="id" value="{{studiant.studiant_id}}" class="form-control" disabled>
<div class="form-group">
<label for="school" class="col-md-2 control-label">School</label>
<div class="col-md-1">
<input type="text" id="school" name="school" class="form-control" ng-init="studiant.school=studiant.studiant_school" ng-model="studiant.school">
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-2 control-label">Student's Name</label>
<div class="col-md-10">
<input type="text" id="name" name="name" class="form-control" ng-init="studiant.name=studiant.studiant_name" ng-model="studiant.name">
</div>
</div>
</form>
And the script:
document.getElementbyId('name').value = "anything";
Or, if I doing wrong and I have to change the value with ng-model or something, please help me.
http://plnkr.co/edit/bVoljJqiK3CLB2xqZ6Zm?p=preview
You can see a working example there.
Make sure you have the name attr set for the form and the input.
HTML Example:
<button id="dirty-button" ng-click="addText(); myForm.myText.$setDirty()">Make Dirty</button>
<hr>
<form name="myForm">
<input name="myText" id="myTextInput" type="text" ng-model="myText" required>
</form>
<br/>
<span ng-show="myForm.myText.$dirty">it's dirty now</span>
A simple function:
$scope.addText = function() {
$scope.myText = "now I'm dirty";
}
$scope.$on('$viewContentLoaded'){
$scope.form.fieldName.$dirty = true;
}
When your view is loaded then angular calls viewContentLoaded event is called. After that you can set the field dirty. And also if you want to call some method ,that should be executed after the content is loaded than you should call that method inside this $scope.$on('$viewContentLoaded'){..}
This should do the job
angular.element(document.querySelector('form')).scope().formname.fieldname.$setDirty()

Categories

Resources