How can I do event on text box in Angular? - angularjs

I have a text box that show when I click on checkbox and I need to make an event on it that can make me bind it to object from DB
HTML:
<div ng-repeat="feture in featureEnumArray">
<input id="txtchkFet" type="checkbox" ng-model="feture.IsChecked" />
{{feture.DisplayText}}
<div ng-show="feture.IsChecked" >
<input class="form-control" type="text" ng-model="feture.Value" ng-change="getFeatureID(feture)" id="txtValue" placeholder="Type Feature Value" />
</div>
<div class="label label-danger" ng-show="feture.IsChecked && !feture.Value">
Type Value
</div>
</div>
And in Angular controller I did Like this :
$scope.getFeatureID = function (feture) {
if (feture.IsChecked) {
$scope.Planfeature = angular.copy(feture);
$scope.PlanFeatureTemp.FeatureID = $scope.Planfeature.ID;
$scope.PlanFeatureTemp.Value = $scope.Planfeature.Value;
$scope.Planfeature = [];
}
else {
var index = $scope.JAdminPlan.PlanFeatureValues.indexOf(feture);
$scope.JAdminPlan.PlanFeatureValues.splice(index, 1);
}
if (!$scope.$$phase) $scope.$apply();
};

Related

After uncheck the checkbox value is not inserted in mvc application

I have one checkbox and one textbox, now when I check the checkbox and write text in textbox at that time checkbox value and textbox value is inserted, but when I am uncheck the checkbox and write the text in textbox at that time textbox value is not inserted in database.
Here is my code
I used enum value for checkbox and textbox
Here is the enum code
public enum ChassisJobTypeEnum
{
LinerChange = 1,
ChainSetChange = 2
}
Here is the view design code
<div class="form-group row">
<label class="col-sm-3 col-form-label">Change Linear</label>
<div class="col-sm-3">
<input type="checkbox" class="form-group" id="ChassisJob#((int)ChassisJobTypeEnum.LinerChange)_Checked" placeholder="" />
</div>
<div class="col-sm-3">
<input type="text" class="form-group" id="ChassisJob.#((int)ChassisJobTypeEnum.LinerChange)_OtherJob" placeholder="" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Change Chain Set</label>
<div class="col-sm-3">
<input type="checkbox" class="form-group" id="ChassisJob#((int)ChassisJobTypeEnum.ChainSetChange)_Checked" placeholder="" />
</div>
<div class="col-sm-3">
<input type="text" class="form-group" id="ChassisJob.#((int)ChassisJobTypeEnum.ChainSetChange)_OtherJob" placeholder="" />
</div>
</div>
<div class="form-group row">
<div class="col-sm-12">
<button type="submit" class="btn btn-primary" id="submit-form">Submit</button>
</div>
</div>
Now, when submit the form at that time ajax is calling to the controller
$('form').submit(function (event) {
event.preventDefault();
var chassisJobs = [];
chassisJob = {
ChassisJobsTypeId: #((int)ChassisJobTypeEnum.LinerChange),
Checked: $("#ChassisJob#((int)ChassisJobTypeEnum.LinerChange)_Checked").prop('checked'),
OtherJob: document.getElementById("ChassisJob.#((int)ChassisJobTypeEnum.LinerChange)_OtherJob").value,
};
chassisJobs.push(chassisJob);
chassisJob = {
ChassisJobsTypeId: #((int)ChassisJobTypeEnum.ChainSetChange),
Checked: $("#ChassisJob#((int)ChassisJobTypeEnum.ChainSetChange)_Checked").prop('checked'),
OtherJob: document.getElementById("ChassisJob.#((int)ChassisJobTypeEnum.ChainSetChange)_OtherJob").value,
};
chassisJobs.push(chassisJob);
var serviceJobData = {
'Id': document.getElementById("Id").value,
'ChassisJob': chassisJobs
};
$.ajax({
type: "POST",
url: '/ServiceJob/AddUpdate',
data: serviceJobData,
dataType: "json",
success: function (data) {
if (data.success == true) {
alert("Data has been update successfully");
//RefreshTable();
location.reload(true);
// set focus on edit form
document.getElementById("service-job-list").scrollIntoView();
//reste form
var frm = document.getElementsByName('service-job-form')[0];
frm.reset();
}
else {
alert("Unable to insert data")
}
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to add Detail.');
}
});
});
Here is the controller in which the addupdate method is calling at submit button.
[HttpPost]
public IActionResult AddUpdate(ServiceJobModel model)
{
ServiceJob serviceJob = new ServiceJob();
bool iSInsertData = true;
var chassisJobs = _Db.ChassisJob.Where(x => x.ServiceJobId == model.Id).ToList();
if (chassisJobs.Any())
{
_Db.ChassisJob.RemoveRange(chassisJobs);
_Db.SaveChanges();
}
return Json(new { success = true });
}
Now, this is code which I tried.
For more clear, let see task image.
When I check the checkbox and enter the value in textbox at that time insert data properly and at the fetch time it shows the checkbox and textbox value properly.
now, when I uncheck the checkbox and enter the value in textbox at that time data is not inserted and at the fetch time it does not show any thing.
If you any issue to understand the question then feel free to ask.

Issue with nested ng-controller in Angularjs

I am stuck with strange issue. Actually I am fetching the data from ajax and showing it on text boxes.
So, basically I have 3 text box (City, City1, City2). By default City textbox is visible rest will show if they have data from Ajax.
User can add city by clicking + button or remove by click on - button.
I am able to fetch and show the data properly on textboxes.
But when I want to add/show City1 or City by clicking on + button. It is simply executing form submit event.
Here is code for Ajax call.
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_job_city.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
$scope.formData.city1 = data.city1;
$scope.formData.city = data.city;
$scope.formData.city2 = data.city2;
}
});
})
Code for form save and show hide city textboxes.
var formApp = angular.module('formApp', []);
formApp.controller('formProfile1', function($scope,$http){
$scope.secondcity1city1 = false;
$scope.thirdcity2 = false;
$scope.hidecity1 = function() { $scope.secondcity1 = false; }
$scope.hidecity2 = function() { $scope.thirdcity2 = false; }
$scope.showcity = function() { $scope.secondcity1 = true; }
$scope.showcity1 = function() { $scope.thirdcity2 = true; }
$scope.formData = {};
$scope.formprofile1 = function() {
$scope.ajaxload = true;
var allData={'formData': $scope.formData, 'uid': uid}
$http({
method : 'POST',
url : 'city_update_exec.php',
data : allData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers
})
.success(function(data) {
$scope.ajaxload = false;
if (!data.success) {
$scope.errorcity = data.errors.city;
$scope.errorcity1 = data.errors.city1;
$scope.errorcity2 = data.errors.city2;
}else{
alert('City has been updated.');
}
});
};
})
HTML codes are below.
<div class="container" ng-controller="formProfile1">
<form name="formProfile1" method="post" id="formProfile1"
ng-submit="formprofile1()" role="form">
<div ng-controller ="getprofile">
<div id="firstcity">
<div class="col-xs-10">
<div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity }">
<input name="city" id="city" type="text"
class="form-control textbox1 txt-auto"
required="required" placeholder="Job Location* "
ng-model="formData.city">
<div class = "errorba" ng-show="errorcity">{{errorcity}}
</div>
</div>
</div>
<div class="col-xs-2">
<!--<button class="remove" ng-click="removeChoice()">-</button>-->
</div>
<button class="addfields" ng-click="showcity()">+</button><br>
</div>
<div ng-show="secondcity1">
<div class="col-xs-9"><div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity1 }">
<input name="city1" id="city1" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* " ng-model="formData.city1">
<div class = "errorba" ng-show="errorcity">{{errorcity1}}
</div>
</div>
</div>
<div class="col-xs-3">
<button class="remove" ng-click="hidecity1()">-</button>
<button class="addfields" ng-click="showcity1()">+</button><br>
</div>
</div>
<div ng-show="thirdcity2">
<div class="col-xs-10"><div class="topjob_resumetitle"
ng-class="{ 'has-error' : errorcity2 }">
<input name="city2" id="city2" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* "
ng-model="formData.city2">
<div class = "errorba" ng-show="errorcity2">{{errorcity2}}
</div>
</div>
</div>
<div class="col-xs-2">
<button class="remove" ng-click="hidecity2()">-</button>
</div>
More text boxes are here
</div>
The problem is that you have not set a type for your buttons, and therefore are defaulting to submit types, which will submit the first parent form found in the DOM when clicked. To allow your custom click handlers to execute properly, change your button types to "button" like so:
<button type="button" class="addfields" ng-click="showcity()">+</button><br>
Remove method="post" and add novalidate on form tag it will stop html5 validation
<form name="formProfile1" novalidate id="formProfile1"
ng-submit="formprofile1()" role="form">
Also if its still not works then change all your button to
<input type="button">//for rest of the buttons
<input type="submit">//for submit button
To make an http request you don't need to use the separate controller. Use factory method in your code for ajax and inject it as a dependency in your controller. Refer Angular Factory method

add and remove text field dynmaically in angularjs

I want to add and remove text fields in angularjs with an add button click. And in the right side of the text fields, which were added there should be a remove option. While I click on the remove the text field should delete.
I would solve this using ng-repeat. Have a look at this example:
Edit updated the code:
angular.module("module",[])
.controller("ctrl",function($scope){
$scope.inputList = [];
$scope.add = function(){
$scope.inputList.push({content:""});
};
$scope.remove = function(input){
var idx = $scope.inputList.indexOf(input);
$scope.inputList.splice(idx,1)
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="module" ng-controller="ctrl">
<div ng-repeat="input in inputList">
<input type="text" ng-model="input.content">
<input type="button" ng-click="remove(input)" value="remove">
</div>
<input type="button" ng-click="add()" value="add">
</div>
You can use ng-repeat to achieve this functionality.
You'll have to add an object in a $scope object's array everytime the user presses Add button and removing the object when the user presses - button.
Here's the code sample.
<span ng-click="addTextBox()"> + </span>
<div ng-repeat="textBox in textBoxes">
<input type='text' />
<span ng-click="removeTextBox(textBox.id)"> - </span>
</div>
The controller goes like this
$scope.textBoxes = [];
$scope.addTextBox = function() {
$scope.textBoxes.push({id: $scope.textBoxes.length +1});
}
$scope.removeTextBox = function(id){
var indexToRemove;
for(i = 0; i < $scope.textBoxes.length; i++){
if($scope.textBoxes[i].id === id){
indexToRemove = i;
}
$scope.textBoxes.splice(indexToRemove, 1);
}
}
You can use this simple way:
HTML
<span ng-repeat="hobby in hobbies track by $index">
<div class="form-group">
<input type='text' ng-model='hobbies[$index]' class="form-control pull-right"/>
<button ng-click = "addHobby()" ng-show="$last">+</button>
<button ng-click = "removeHobby($index)" ng-show="hobbies.length > 1">-</button>
</div>
</span>
Angular Controller
$scope.hobbies = [''];
$scope.addHobby = function() {
$scope.hobbies.push('');
}
$scope.removeHobby = function(index) {
if(index >= 0){
$scope.hobbies.splice(index, 1);
}
}

ngRepeat and checkbox

I have a div with ng-repeat:
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="this.value" ng-checked="false">{{fruit.code}} - {{fruit.short_name}}
</div>
Here furits is array object and which contains the field code, short_name.
furits: {
{
code : code_value1,
short_name :short_name_value1
},
{
code : code_value2,
short_name :short_name_value2
},...
{
code : code_value..,
short_name :short_name_value..
},
}
I would like to get the code of checked checkbox after submit button click and insert those codes in new array.
And also send the same array to server to complete the task.
Please help me to solve this issue.
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="fruit.isSelected" />{{fruit.code}} - {{fruit.short_name}}
</div>
<input type="button" ng-click="sendServer()" value="Submit" />
And your controller methods are like ,
$scope.sendServer = function(){
$scope.checkedFruits = [];
for(i = 0; i < $scope.fruits.length; ++i){
if ($scope.fruits[i].isSelected)
$scope.checkedFruits.push(fruit.code);
}
$scope.postData();
}
//Send array to server via web service with parameter FruitsCode
$scope.postData = function () {
$http.post('http://your.webservice/', {FruitsCode:$scope.checkedFruits}).success(
function(data){
$scope.response = data
})
}
Hopes this will help you !
<div ng-repeat="fruit in fruits">
<input type="checkbox" ng-model="fruit.isChecked" />{{fruit.code}} - {{fruit.short_name}}
</div>
<input type="button" ng-click="save()" value="SAVE" />
And inside your controller :
$scope.save = function(){
var myFruits = [];
for(i = 0; i < $scope.fruits.length; ++i){
if ($scope.fruits[i]. isChecked)
myFruits.push(fruit.code);
}
}

Angular directive for horizontal Bootstrap form

I'm trying to build a directive for my Angular to help with the integration of form fields. I've implemented Scott Allens solution from his Angular playbook, and it works fine for a normal stacked form.
I need however to adapt it to a horizontal form instead. Here's my code:
Markup
<div form-group>
<label for="name">Name</label>
<input type="text" id="name" ng-model="vm.name">
</div>
formGroup directive
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
var label = element.querySelector("label");
label.classList.add("control-label");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
}
element.classList.add("form-group");
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
The output becomes:
<div form-group="" class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
And that's fine for stacked form. Since I need a horizontal form, my output needs to look like this:
<div form-group="" class="form-group">
<label for="name" class="control-label col-sm-3">Name</label>
<div class="col-sm-9">
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
</div>
I've tried many solutions and I can get it work with single elements like an input, textarea or a select. It becomes much more tricky when I have something like two radio buttons inside my markup like this:
<div form-group>
<label>Active</label>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
The desired output of the above mentioned code should be:
<div form-group class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
</div>
Please notice that the input(s) in the form-group is not fixed. It can be either a single input, textarea, select, a group of radio buttons or checkboxes. I'm lost for how I can make that happen. Any help is appreciated. Thanks!
UPDATE
I made some small changes to Mark Veenstra's code to make it (sort of) working:
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label", "col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
angular.element(input).wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelector("div[class='radio']");
angular.element(div_radio).wrap(angular.element('<div class="col-sm-9"></div>'));
}
This does not work completely as intended with multiple radio inputs since it only wraps the <div> on the first radio input element.
The output from radio button example in my original post using Marks code is:
<div form-group="" class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active" value="true"> Yes
</label>
</div>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active" value="false"> No
</label>
</div>
</div>
SOLUTION
Check out the Plunker with the final result: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview
In the angular.element documentation you can find the method wrap() to be able to wrap HTML around a selected element. Or see this direct link.
So what you could do in your directive is change the setupDom() function to match your requirements per type of form element.
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
input.wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelectorAll("div[class='radio']");
div_radio.wrap(angular.element('<div class="col-sm-9"></div>'));
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
NOTE: This code is not tested, maybe there are some minor mistakes, but I guess you'll get the point now.
Mark's suggestion came close, but it didn't solve my problem completely. I ended up using the following code in my formGroup directive:
(function (module) {
"use strict";
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var children = angular.element(element).children();
var labels = children.splice(0, 1);
// Set label classes
labels[0].classList.add("control-label", "col-sm-3");
// Wrap children in div
angular.element(children).wrapAll(angular.element("<div class='col-sm-9'></div>"));
// Handle inputs
var inputs = element.querySelectorAll("input, textarea, select");
for (var i = 0, len = inputs.length; i < len; i++) {
var input = inputs[i],
type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox") {
input.classList.add("form-control");
}
}
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
module.directive("formGroup", formGroup);
}(angular.module("app.core")));
Check out this Plunker to see it in action: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview

Resources