how to get ng-repeat checkbox values on submit function in angularjs - javascript

I have a form which has 10 checkboxes. By default angular js triggers on individual checkbox. I want to grab all selected check box values on submit action only. Here is my code...
<form name="thisform" novalidate data-ng-submit="booking()">
<div ng-repeat="item in items" class="standard" flex="50">
<label>
<input type="checkbox" ng-model="typeValues[item._id]" value="{{item._id}}"/>
{{ item.Service_Categories}}
</label>
</div>
<input type="submit" name="submit" value="submit"/>
</form>
$scope.check= function() {
//console.log("a");
$http.get('XYZ.com').success(function(data, status,response) {
$scope.items=data;
});
$scope.booking=function(){
$scope.typeValues = [];
console.log($scope.typeValues);
}
I am getting empty array.
Can somebody tell how to grab all selected checkbox values only on submit event.

<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.SELECTED" ng-true-value="Y" ng-false-value="N"/>
</div>
<input type="submit" name="submit" value="submit" ng-click="check(items)"/>
$scope.check= function(data) {
var arr = [];
for(var i in data){
if(data[i].SELECTED=='Y'){
arr.push(data[i].id);
}
}
console.log(arr);
// Do more stuffs here
}

Can I suggest reading the answer I posted yesterday to a similar StackOverflow question..
AngularJS with checkboxes
This displayed a few checkboxes, then bound them to an array, so we would always know which of the boxes were currently checked.
And yes, you could ignore the contents of this bound variable until the submit button was pressed, if you wanted to.

As per your code all the checkboxes values will be available in the typeValues array. You can use something like this in your submit function:
$scope.typeValues
If you want to access the value of 3rd checkbox then you need to do this:
var third = $scope.typeValues[2];

Declare your ng-model as array in controller, like
$scope.typeValues = [];
And in your template, please use
ng-model="typeValues[item._id]"
And in your controller, you will get this model array values in terms of 0 and 1. You can iterate over there.

Related

How to control related text input element with a button?

I have a list of text-field + button that gets rendered dynamically. The user hits the button and I want to control the input field when a button is clicked.
I figure you could do something like:
<input id="1"><button onclick="doSomething(1)">Something</button>
<input id="2"><button onclick="doSomething(2)">Something</button>
<!--...-->
<input id="3"><button onclick="doSomething(3)">Something</button>
But wonder if there's a different and more sophisticated solution because the code I'm modifying passes an an anonymous function to onclick and I can't pass a unique ID like the method above.
This is very easy to achieve in vanilla Javascript (as most things). No jQuery overhead required here.
let buttons = [...document.getElementsByClassName('inputbutton')]
function doSomething(i) {
console.log(i);
}
for (const button of buttons) {
button.addEventListener('click', (e) => {
const i = e.target.previousSibling.id
doSomething(i);
})
}
<input id="1"><button class="inputbutton" type="button">Something</button>
<input id="2"><button class="inputbutton" type="button">Something</button>
<!--...-->
<input id="3"><button class="inputbutton" type="button">Something</button>
If you modify your dynamic HTML like the following and add this jQuery, you will be able to access the value of the previous input field.
var buttons = $(".inputs-and-buttons #button-after-input-field");
buttons.click(function() {
console.log($(this).prev("input").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputs-and-buttons">
<input id="1" value="1"><button id="button-after-input-field">Something</button>
<input id="2" value="2"><button id="button-after-input-field">Something</button>
<!--...-->
<input id="3" value="3"><button id="button-after-input-field">Something</button>
</div>
You can generate dynamic Id for both input field and button with index or row number or you can add custom attribute for row number as below.
You can generate dynamic related control with specific Id for textbox and button as well. e.g. txtFirstName_1, txtLastName_1, btnAdd_1. here textbox and button distinguished by its id and number after Underscore "_" .
$(function(){
// Register click on button
//here you can pass specific class name for button if all are have same functionality
$("button").click(function(e){
console.log(this);
var btnId=$(this).attr("id");
//console.log(btnId);
// Way 1
//Split btnId with "_" e.g btn_1 will splited with ["btn","1"]
var rowIndex=btnId.split("_")[1];
console.log(btnId.split("_"),rowIndex);
$("#txt_"+rowIndex).val("Upate value by btn"+rowIndex); // Or fetch value
// Way 2
// You can directly use custom attribute data-row and do your work
var rowIndex1=$(this).attr("data-row");//$(e).prop("data-row");
console.log(rowIndex1);
//$("#txt_"+rowIndex1).val("Upate value"); // Or fetch value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txt_1" data-row="1"><button id="btn_1" data-row="1">Something</button>
<input id="txt_2" data-row="2"><button id="btn_2" data-row="2">Something</button>
<input id="txt_3" data-row="3"> <button id="btn_3" data-row="3">Something</button>

how to add ng-model to dynamically created input text fields

This is my angularjs code to create input text fields dynamically.
<form action="demo_form.asp" method="get">
//statically added textfields
value1:<input type="text" placeholder="Give inspection details. Eg. 10:00." ng-model="store.static1" required />
value2:<input type="text" placeholder="Give inspection details. Eg. 10:00." ng-model="store.static2" required />
//dynamically adding textfields
enter the number of new fields to be created:<input type="number" id="in_num" />
<button type="button" id="submit"> Create text fields </button>
<div id="dynamicInput" ></div></td>
//button to add values to the database
<button type="submit" ng-click="addValues($event)> add to database </button>
</form>
"ng-click="addValues($event)"" helps add these values to a mongodb database which i have already done.
javascript code used to make these fields is:
$(document).ready(function(e){
$('#submit').click(function(){
var inputIndex = $('#in_num').val();
for( var i=0; i<inputIndex; i++)
{
$('#dynamicInput').append('<input type=text id=id_'+ i +' style=width:100%; padding:12px 15px ng-model=store.value'+i+'/>');
}
});
});
On clicking the "add to database" button the values only from first and second textfields are geting added to the database but not the values added from the dynamically created textfields. Is there any way to do it?
Problem is that your dynamically added input fields do not have a click event when you add them with jQuery. Adding ng-click is not enough. You would have to use $compile to let angular parse this element.
However, the much smarter way is to not use jQuery at all and let the fields be generated by angular itself with ng-repeat.
angular
.module('app', [])
.controller('dynamicFieldsController', dynamicFieldsController);
dynamicFieldsController.$inject = ['$scope'];
function dynamicFieldsController($scope){
var vm = this;
vm.numOfFields = 0;
vm.fields = [];
vm.add = function() {
for (var i = 0; i < vm.numOfFields; i++) {
var index = vm.fields.length;
vm.fields.push(index);
}
}
}
input{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='dynamicFieldsController as vm'>
<input placeholder='num of fields' ng-model='vm.numOfFields'>
<button ng-click='vm.add()'>add</button>
<input type='text' ng-repeat='field in vm.fields' value='{{ field }}'>
</div>
In this example you can add any number of elements and bind ng-click events to them. They will work out of the box, since parsed with angular. Your addValues function now simply has to use vm.fields to actually add the values to database.
Why don't you go through Add new text box on click of a button in angular js
http://www.shanidkv.com/blog/angularjs-adding-form-fields-dynamically

accessing values from an input filed in html + jquery

here is my fiddle
I am looking at getting the values from an inpt form in html. for example I want to get the value that is entered in the Cat name: input form.
<div id="admin-form">
<form>
Cat name:<input id="admin-cat-name" type="text" name="cat-name" placeholder="10" value="10"><br>
Source: <input id="admin-source" type="text" name="source"><br>
Count: <input id="admin-count" type="text" name="count">
<button id="save-button" type="button">Save</button>
<button id="cancel-button" type="button">Cancel</button>
</form>
</div>
I am thinking along the lines of something like the below:
var form = $('form');
var form2 = $('form #admin-cat-name');
//alert(form)
console.log(form)
console.log(form2) // i think this is an array that has the value that I want?
but I just can't quite get the value from the input form. Can anyone advise how I do this? And if I am going about it the right way?
You are actually looking for .val(). Use the following code:
var form2 = $('form #admin-cat-name').val();
From the docs:
Get the current value of the first element in the set of matched elements or set the value of every matched element.
You can use this $("#admin-cat-name").val()

Angular not updating radio button selection

I have a small quiz application that I am converting into angular. It displays a question, and 4 possible answers that you select through radio buttons. You can move to the next question or back to the original and your selection is noted.
I am having problems reselecting the radio button when I want to go back to the question. The attribute for the button states that I have changed it to true, but it is not indicated. Only when I go back to the first question, and try to go back a second time does it update correctly. I am assuming that since it can't back back any further and can run again that there is some updating to the buttons going on and that is what is doing it.
The extra space appears to be a formatting issue with stack overflow, it isn't in my actual code base. I have since remove it.
Any help would be greatly appreciated. The code is rough right now as I just have everything thrown into the controller. Some structure will come later.
HTML
<div ng-controller="mainController" class="col-md-5 col-md-offset-5">
<div>
{{quizQuestions}}
</div>
<div ng-repeat="answers in quizAnswers">
<label>{{answers}}</label>
<input class="rad" type="radio" name="answer" ng-click="markAnswer($index)">
</div>
<div>
<label>Change the question</label>
<input type="button" ng-click="decrease()" value="Back">
<input type="button" ng-click="increase()" value="Next">
</div>
</div>
Angular
$scope.adder = 0;
$scope.answer = [];
$scope.markAnswer = function(index) {
$scope.answer.splice($scope.adder,1,index);
};
$scope.display = function(number) {
$scope.quizQuestions = allQuestions[number].question;
$scope.quizAnswers = allQuestions[number].choices;
};
$scope.decrease = function() {
if($scope.adder === 0) {
} else {
$scope.adder -= 1;
$scope.display($scope.adder);
}
document.getElementsByClassName('rad') [$scope.answer[$scope.adder]].checked = true;
};
$scope.display($scope.adder);
There is a syntax error in your "rad" class ng-click
<input class="rad" type="radio" name="answer" ng- click="markAnswer($index)">
you need to take out the space between ng- and click
For what your doing, you should look into the ng-model directive. Mind if take a look at your markAnswer() function?

How to check all checkboxs with angular

I have a checkbox that should check all checkboxes. The checkbox works as it should by checking all the checkbox's, however angular doesnt think they have been checked? The only way angular knows if they are checked is if i manually check each one. (The brackets and for loop are blade php from laravel)
<label class="checkbox-inline">
<input type="checkbox" ng-model="everyoneCheck"/> Everyone
</label>
#foreach($company->users as $tagIndex => $user)
<label class="checkbox-inline">
<input type="checkbox" ng-checked="everyoneCheck" ng-model="newDiscussion.notify_partners[{{$tagIndex}}]" ng-true-value="{{$user->id}}" /> {{ $user->first_name }} {{ $user->last_name }}
</label>
#endforeach
upon click of the submit button i proceed to $http.post to my server, i just pass in an object to the post function, this is the object.
var discussionData = {
'title': $scope.newDiscussion.title,
'discussion': $scope.newDiscussion.summary,
'company_id': company_id,
'notify_partners': $scope.newDiscussion.notify_partners
};
for some reason when i use the check all approach, nothing gets put into notify_partners, however when i manually click each checkbox, they will get entered and submitted properly.
Any help? I feel like its some sort of binding issue, where i just need to tell angular, hey its updated!
Here's a way to do it:
<p><input type="checkbox" ng-model="globalCheck" ng-click="toggleCheckAll()" /> Check All</p>
<ul>
<li ng-repeat="i in init">
<input type="checkbox" ng-model="checkbox[$index]" /> Checkbox {{ $index + 1 }} {{ checkbox[$index] }}
</li>
</ul>
Then in your controller:
function myControl($scope) {
$scope.globalCheck = false;
$scope.checkbox = {};
$scope.init = [0,1,2,3,4,5,6,7,8,9];
$scope.toggleCheckAll = function() {
var k, val = !$scope.globalCheck;
console.log(val);
for(k in $scope.init) {
$scope.checkbox[k] = val;
}
}
}
See JSfiddle for working example
ng-checked does not update the value bound in ng-model. It only affects the presence of the checked attribute on the element itself.
Your best bet is to use ng-change to execute some function and update all your models accordingly.
<input type="checkbox"
ng-model="everyoneCheck"
ng-change="toggleCheckAll()"/>
And in your controller, you can have toggleCheckAll() loop over your models and set them based on the value of everyoneCheck

Categories

Resources