Select checkbox from array values in AngularJS - html

I have created a page which contains some text boxes, radio buttons and check boxes. I am using this page to save new data or edit the existing one. I am able to save new data but for editing the data, the page should show some predefined values that it is getting from a variable. I am able to get and set the values for text boxes and radio buttons from that variable. But I am not able to check the check boxes. I have plenty of check boxes so I am using ng-repeat for the values to be displayed on page. I am setting the values of selected check boxes to an array and passing that value to my service layer.
Below are my code snippets:
HTML:
<div id="activityCheckboxList" class="checkboxList">
<div ng-repeat="activity in activities">
<label>
<input type="checkbox" ng-true-value="activity" ng-checked="selection.indexOf(activity) > -1" ng-click="toggleSelection(activity)"/>
<span>{{activity.activityName}}</span>
</label>
</div>
</div>
app.js:
$scope.selection=[];
$scope.getActivities(); //this sets values in $scope.activities which is a list coming from service layer
//Get Selected Activities from Check Boxes
$scope.toggleSelection = function toggleSelection(activity){
var idx = $scope.selection.indexOf(activity);
if(idx > -1){
$scope.selection.splice(idx, 1);
}
else{
$scope.selection.push(activity);
}
};
After this, while clicking on submit, I am passing $scope.selection which will contain my activity objects.
For editing the data, I can put the data in selection[]. But how to check the check boxes using that and after that user should be uncheck/check them again. I tried using foreach loop but it didn't help.
Thanks in advance

As "activity" is an object, indexOf is not right way to find the index. I have made few changes to your code
html
<input type="checkbox" ng-true-value="activity"
ng-checked="checkInSelectionList(activity)" ng-click="toggleSelection(activity)"/>
<span>{{activity.activityName}}</span>
js
$scope.checkInSelectionList = function (item) {
for(var i=0; i<$scope.selection.length;i++){
if($scope.selection[i]['ID'] == item['ID']){
return true;
}
}
}
You can also use underscore to find the index of an object.
https://jsfiddle.net/nors536b/

Related

AngularJS checkbox to toggle my filter on/off

Hi I am trying to get a filter to return instances that have a certain quantity but can't seem to get it to work. What I have in my HTML:
I would like my filter to apply when I hit this checkbox:
<input type="checkbox" value="true" ng-model='filterSales' >
Heres what I have:
<div class='col-md-12' ng-repeat='sku in value | QuantityFilter'>
I was just able to learn how to create a custom filter but now I am having trouble figuring out how to toggle it.
If you just want to know how you can see whether the checkbox is set or not, you can add a parameter to your filter function as shown in the example at the bottom of the documentation: https://docs.angularjs.org/api/ng/filter/filter
You would need to add :filterSales to your ng-repeat where you apply the filter.
<div class='col-md-12' ng-repeat='sku in value | quantityFilter:filterSales'>
In js you need to add another parameter, in this example "array" contains the array which is repeated (in your case "value") and toggleVar has the checkbox value.
"use strict";
app.filter("quantityFilter", function () {
function quantityFilter(array, toggleVar) {
if(!toggleVar){
return array;
}
let result = [];
// TODO: Build new array based on your criteria
return result;
}
return quantityFilter;
});

Checkbox always returning null in jsp

i am building a contact form and have a checkbox that looks like this:
<input type="Checkbox" name="infomaterial" value="test">send info material<br>
i am then using request.getParameter like this:
request.getParameter("infomaterial")
this is working fine with textboxes and textfields, but it is not working with checkboxes.
I always get null, no matter it is checked or not (i expect it being null when not checked?).. The checkbox is in the right position, too. Can someone tell me what i am doing wrong?
Use getParameterValues to get array of selected checkboxes:
Servlet:
String[] infomaterials= request.getParameterValues("infomaterial");
for (String infomaterial:infomaterials) {
System.out.println(infomaterial);
}
Also note, you will only get values for those checkboxes which are selected. If a checkbox is not selected, it's value will not be available in getParameterValues.
Thanks for your answers.
I found the problem. I have an "owasp SecurityWrapper" in my program. Somehow, this blocks everything except textfields and textboxes. If i turn it off, it works like expected. Still have to find out why it blocks those Checkboxes..
<input type="Checkbox" class="msgChk" name="infomaterial" value="test">send info material<br>
var checked = null;
var input = document.getElementsByClassName('msgChk');
for(var i=0; inputElements[i]; ++i) {
if(inputElements[i].checked) {
checked = inputElements[i].value;
break;
}
}
This is an old post, but please try
boolean infomaterialIsChecked= Boolean.parseBoolean( request.getParameter("infomaterial") );
or
boolean infomaterialIsChecked= request.getParameter("infomaterial") != null;
The Second Option is better. It worked for me

HTML Form - submit array of ID's of selected divs

I have an array of divs which can be selected (change background colour on click to signify that to the user).
I want a way to submit the ids of all of these divs to my app, though can't see a 'nice' way of doing this; at the moment the only thing I can see to do is have a button that onclick triggers a javascript function that gets the id's and sends them back to my server in a POST.
Is there a way of creating a multiple select input on a form which uses divs instead of checkboxes or a multi-select list, or a better way of doing what I'm attempting?
Assuming you add the class selected when a user 'selects' the div:
var data = {};
$(".classOfDivs.selected").each(function(){
data[$(this).prop('id')] = 'true';
}
$.ajax({
url : 'ajaxPage.php',
type : 'POST',
dataType : 'text',
cache: false,
data: data,
success : function(text){alert('Saved: '+text);},
error: function(){alert('Did not reach server');}
});
Use the success function to process the returned text as needed. dataType can be changed to html, JSON, etc. See the .ajax() documentation.
Have a hidden input for each div, all with the same name but with a different id. When a div is clicked update the corresponding hidden input with the id. Then when you submit through a standard form POST all of those values will be available through the name you specified.
Since this is an app, what you could do is store everything in HTML5 localstorage using the JQuery javascript library.
Here's how to do it step by step:
Create a jquery array
on click, get div id and store it in the array with a key/value pair
if clicked again, remove it from the array
have some event listener like a "submit" button to store the value of your array to localstorage
Here is a jsfiddle I had that has exactly what you are talking about: http://jsfiddle.net/CR47/bqfXN/1/
It goes into a little more depth but the jquery should be exactly what you need.
The reason this is better than submitting with POST or using ajax is because since you say this is an app, you will be able to use this method offline, where as post or ajax would require a connection to a server running php.
var skinCare=[]; //the array
$('.skinCare').click(function(){ //onclick
var value = event.target.className.split(" ")[0]; //get classname, you would get id
var index = skinCare.indexOf(value); //gets where the location in
//the array this code is
if($(this).hasClass('selected')){ //when a div is clicked it gets
//$('.skinCare').removeClass('selected'); //the class "selected" and adds
skinCare.splice(index, 1); //to array, then another click
} else if($.inArray(value, skinCare) == -1){ //removes it from array
skinCare.push(value);
}
});
$('.submitbutton').click(function(){
localStorage.setItem('Skin Care', JSON.stringify(skinCare));
});

Save input data to localStorage on button click

I am trying to build my first web application. In my app I need to have a settings panel, but I have no idea how to do it. I've been searching the web and came across a HTML5 localStorage, which I believe might be the best way to do the things. But the problem is I have no idea how to use it.
<input type='text' name="server" id="saveServer"/>
How can I save data from input to localStorage when user clicks the button? Something like this?
<input type='text' name="server" id="saveServer"/>
<button onclick="save_data()" type="button">Save/button>
<script>
function saveData(){
localStorage.saveServer
}
</script>
The localStorage object has a setItem method which is used to store an item. It takes 2 arguments:
A key by which you can refer to the item
A value
var input = document.getElementById("saveServer");
localStorage.setItem("server", input.val());
The above code first gets a reference to the input element, and then stores an item ("server") in local storage with the value of the value of that input element.
You can retrieve the value by calling getItem:
var storedValue = localStorage.getItem("server");
This worked for me. For setting I placed .value behind the var and called the var in the setItem:
var input = document.getElementById('saveServer').value;
localStorage.setItem('server', input);
For getting the text back:
document.getElementById('saveServer').value = localStorage.getItem('server');

How to: Update jQuery dialog div with new content from json

I am attempting to update the div of my dialog with new content from a json array and am encountering issues and am requesting some guidance.
I output a json array which has labels for a 'Name' and a 'Definition'. A user is presented with a list of radio buttons. When a user clicks a radio button which has the following structure:
<input type="radio" value="23" name="statistic" id="stat-23" />
I take the value of the radio button and use this to identify which 'Name' 'Definition' pair I am referring to from my json array.
I then use the 'Name' 'Definition' pair to populate a div which typically updates dynamically. To accomplish this I use the following code:
$('input[type=radio]').live( 'change', function(){
if ( ! $(this).is(':checked') )
return false;
var stat_id = $(this).attr( 'id' ).replace( /stat-/, '' );
refreshDefinition( stat_id );
} );
function refreshDefinition( stat_id ) {
var definition = definitions[ stat_id ];
var div = $("<div id='definition'>"+definition.name+": "+definition.definition+"</div>");
$('#definition').replaceWith( div );
}
This works fine without a dialog (it updates just fine as is), however, it would look a lot better if there were some way to incorporate a dialog so that when a user clicks a button, the dialog will appear and they can see the 'Name' 'Definition' pair and then can exit out of it when they are satisfied.
$('#definition').dialog();
I would like the above code to show the updated data, but it does not appear to allow it.
If you have any guidance on how I could go about solving this problem or any alternative approaches, I would really appreciate it!
Thanks.
Have you tried updating the dialogs content?
$('#definition').html(definition.name+": "+definition.definition);
Here's an example.
EDIT:
unnecessary .dialog('widget') made this answer wrong.