I have a html template with one ng-repeat nested inside a parent ng-repeat. The parent ng-repeat contains radio button where the user can select 'Satisfied' or Unsatisfied' which correspond to values 1 and 0 respectively. If a user selects Unsatisfied, a detailed list of options is displayed so they can select more radios for further info. Here's the html;
<div class="group" ng-repeat="group in Groups">
<table>
<tr>
<td>{{group.Description}}</td>
<td><input type="radio" value="1" name="{{group.Id}}" ng-model="group.SatisfactionLevel" /></td>
<td><input type="radio" value="0" name="{{group.Id}}" ng-model="group.SatisfactionLevel" /></td>
</tr>
</table>
<div class="group-detail" ng-class="{'hidden': group.SatisfactionLevel != 1}">
<table>
<tr ng-repeat="item in group.Details">
<td>{{item.Description}}</td>
<td><input type="radio" value="1" name="{{item.Id}}" ng-model="item.SatisfactionLevel" /></td>
<td><input type="radio" value="0" name="{{item.Id}}" ng-model="item.SatisfactionLevel" /></td>
</tr>
</table>
</div>
The json returned from the server looks like this;
"Groups": [
{
"Id":"AA",
"Description":"Service",
"SatisfactionLevel":1,
"Details":[{"Id":"AA1","Description":"Cleanliness","SatisfactionLevel":1},
{"Id":"AA2","Description":"Timeliness","SatisfactionLevel":1}
]
},
{
"Id":"AB",
"Description":"Food",
"SatisfactionLevel":1,
"Details":[{"Id":"AB1","Description":"Price","SatisfactionLevel":1},
{"Id":"AB2","Description":"Portion","SatisfactionLevel":1}
]
}
]
Everything works except that the radio buttons in the nested ng-repeat are not checked. I can see in fiddler that the Satisfactionlevel property contains values. Anybody see where I'm going wrong? Thanks
UPDATE
There was really nothing wrong with the code. It turns out different items in Groups can contain the same Details items. Since I'm using name="{{item.Id}}" for the name attribute, other radios in other group details with the same name but different values were causing previous radios with the same name to get unchecked.
This was my fix;
<td><input type="radio" value="1" name="{{group.Id}}-{{item.Id}}" ng-model="item.SatisfactionLevel" /></td>
since group ids are unique.
First, you have the same value in both inputs - I'm guessing this is a typo?
Second, if you use value="1", it is interpreted as a string "1", but your model is an integer 1.
Instead, use ng-value:
<input type="radio" ng-value="0" name="{{item.Id}}" ng-model="item.SatisfactionLevel">
<input type="radio" ng-value="1" name="{{item.Id}}" ng-model="item.SatisfactionLevel">
Related
I have a large table of inputs and on click event I need to extract the input values of each row to send them to the server.
I need to ask if there is a better way to do it to prevent all that hard coding.
My below code works somehow, but I haven't checked if the input has type radio, so I need to write more code to finalize it.
I am not sure if am doing well or if you can share a better way on this.
Here is what I do below:
Iterate over each table row and assign each row id to the object as a
key.
Iterate over that object to get each row's input values
Save the input to the object as values seperated by _ to be splitted as an array
Live Demo
<!DOCTYPE html>
<html>
<body>
<table>
<tbody id="dynamic_form_tbody">
<tr id="123">
<td><input type="text"></td>
<td><input type="date"></td>
<td><input type="radio" name="choice" value="yes"> <input type="radio" name="choice" value="no"></td>
</tr>
<tr id="1256">
<td><input type="text"></td>
<td><input type="date"></td>
<td><input type="radio" name="choice" value="yes"> <input type="radio" name="choice" value="no"></td> </tr>
<tr id="1212">
<td><input type="text"></td>
<td><input type="date"></td>
<td><input type="radio" name="choice" value="yes"> <input type="radio" name="choice" value="no"></td> </tr>
</tbody>
</table>
<input type="button" id="log" value="console.log data">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
var $btn = $('#log')
$btn.click(e => {
var table_tbody = $('#dynamic_form_tbody')
var dynamic_form_data = {}
//collect each row's id
table_tbody.find("tr").each(function (e) {
console.log('tr found with id: ' + $(this).attr('id'))
id = $(this).attr('id')
dynamic_form_data[id] = ""
})
for (let id in dynamic_form_data) {
$(`tr#${id} input`).each(function (e) {
let $this_val = $(this).val() || null
dynamic_form_data[id] += [$this_val + '_']
})
}
console.log(dynamic_form_data)
})
})
</script>
</body>
</html>
Some issues:
Your radiobuttons all have the same name, so that you can only select one in the whole table. I suppose you should be able to select one in each row.
$(this).val() || null: null is not useful, as an empty string is fine. If you decide to produce a string instead of an array, then null becomes "null", which is indistinguishable from an input that really has those characters. I would therefore drop || null.
[$this_val + '_'] converts a string to an array, but then that array is immediately converted back to a string when assigned with +=.
+ '_' will add also an underscore after the last value.
Both radio button values (yes, no) are always added to the result, without taking the selection into account. You should only take the one that is checked
To avoid that neither of the two radio buttons is selected, provide a default in the HTML definition, using the checked attribute
There seems no reason to not do the job in one cycle instead of two. You can select all the inputs that are not radio buttons, plus the checked radio buttons.
$(() => {
$('#log').click(e => {
var dynamic_form_data = {};
$('#dynamic_form_tbody').find('tr').each(function () {
var $inputs = $(this).find(':checked,input:not([type="radio"])');
dynamic_form_data[$(this).attr('id')] = $inputs.map(function() {
return $(this).val();
}).get(); // Chain `.join("_")` if you want a string instead of array.
});
console.log(dynamic_form_data);
});
})
<table>
<tbody id="dynamic_form_tbody">
<tr id="123">
<td><input type="text"></td>
<td><input type="date"></td>
<td><input type="radio" name="choice123" value="yes" checked> <input type="radio" name="choice123" value="no"></td>
</tr>
<tr id="1256">
<td><input type="text"></td>
<td><input type="date"></td>
<td><input type="radio" name="choice1256" value="yes" checked> <input type="radio" name="choice1256" value="no"></td>
</tr>
<tr id="1212">
<td><input type="text"></td>
<td><input type="date"></td>
<td><input type="radio" name="choice1212" value="yes" checked> <input type="radio" name="choice1212" value="no"></td>
</tr>
</tbody>
</table>
<input type="button" id="log" value="console.log data">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
i'm just learned the javascript. i'm trying to make a simple front-end for practice. so, i've been struggling to select all checkbox inside 'td'.
<table>
<tr class="top1000">
<td><input type="checkbox" onclick="ropangTopping()"><label>milo</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>chocolate</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>chocochip</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>koko krunch</label></td>
</tr>
<tr class="top3000">
<td><input type="checkbox" onclick="ropangTopping()"><label>mozarella</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>cheddar</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>green tea</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>boba</label></td>
</tr>
</table>
when i initialized with this var topping1000 = document.querySelector(".top1000 td input[type=checkbox]");, it just select the first checkbox. but when i use querySelectorAll it didn't select anything. i know this is a silly question. any answer would be appriciated it. thanks in advance.
You're almost there. You do need to use
querySelectorAll()
to grab all the nodes.
But then you need to loop through those nodes and check each one in turn.
One way to do this (there are several) might be to use a forEach loop:
toppings1000.forEach((topping1000) => {topping1000.checked = true;});
N.B. Note the names of the variables I'm using immediately above. I'm distinguishing between the collection of multiple nodes (toppings1000):
toppings1000 // with an 's' to indicate that it's a plural set
and the individual node in each iteration of the forEach loop (topping1000):
topping1000 // no 's' this time - it's just a single node
Working Example:
var toppings1000 = document.querySelectorAll(".top1000 td input[type=checkbox]");
toppings1000.forEach((topping1000) => {
topping1000.checked = true;
});
<table>
<tr class="top1000">
<td><input type="checkbox" onclick="ropangTopping()"><label>milo</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>chocolate</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>chocochip</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>koko krunch</label></td>
</tr>
<tr class="top3000">
<td><input type="checkbox" onclick="ropangTopping()"><label>mozarella</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>cheddar</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>green tea</label></td>
<td><input type="checkbox" onclick="ropangTopping()"><label>boba</label></td>
</tr>
</table>
I'm having issues with some JS code that hides columns based off the state of a checkbox, and I'm hoping to get some help.
The check boxes are in a table. The table has multiple rows. eg:
1, 2
3, 4
Those check boxes correspond to columns in another maintable. That maintable is a single row across. eg: 1, 2, 3, 4
When I uncheck boxes 1 & 2 from the the table, it hides row 1 & 2 from the main table. But if I uncheck boxes 3 & 4, it also hides row 1 & 2.
If the check boxes from the table are on a single line, then they hide all the columns as intended. But because they are broken up via table-row, there is an issue.
$(function() {
$("#checkboxes input[type=checkbox]").on("change", function(e) {
var id = $(this).parent().index()+1,
col = $("#table tr th:nth-child("+id+"), #table tr td:nth-child("+id+")");
$(this).is(":checked") ? col.show() : col.hide();
}).prop("checked", true).change();
});
Here is a fiddle. Any help will be greatly appreciated.
https://jsfiddle.net/o6e3pc3a/7/
Thanks
You have a problem with the table rows when you call to $(this).parent().index()+1 beacause you have the <td> tag in two rows which means that it is going to return the position inside <tr> and in every new <tr> the count start in 1 again.
You have two solutions for that:
1- You can put all the checkboxes inside one row:
<tr>
<td><input type="checkbox" name="option1" value="eventid" />Name</td>
<td><input type="checkbox" name="option2" value="groupid" />ID</td>
<td><input type="checkbox" name="option3" value="pathfile" />Type</td>
<td><input type="checkbox" name="option4" value="filesize" />Number</td>
</tr>
Here's an example JS Fiddle Example 1
2- Or you can just add an attribute data-id with the value of the column's position:
<tr>
<td><input type="checkbox" data-id="1" name="option1" value="eventid" />Name</td>
<td><input type="checkbox" data-id="2" name="option2" value="groupid" />ID</td>
</tr>
<tr>
<td><input type="checkbox" data-id="3" name="option3" value="pathfile" />Type</td>
<td><input type="checkbox" data-id="4" name="option4" value="filesize" />Number</td>
</tr>
And then catch it in js:
$(function() {
$("#checkboxes input[type=checkbox]").on("change", function(e) {
var id = $(this).attr('data-id'),
col = $("#table tr th:nth-child("+id+"), #table tr td:nth-child("+id+")");
$(this).is(":checked") ? col.show() : col.hide();
}).prop("checked", true).change();
});
Here's an example JS Fiddle Example 2
If you don't mind the style of the page I recommend de first one. If not, the second one is more dynamic
Agree with #joac omf .
Because the <chekcbox> are the childen of <td> tags. They are not sibling, so the index is incorrect.
The index is 'incorrect' because you have the checkboxes split into two table rows.
Put the checkboxes in one row <tr> and they work correctly.
<tr>
<td><input type="checkbox" name="option1" value="eventid" />Name</td>
<td><input type="checkbox" name="option2" value="groupid" />ID</td>
<td><input type="checkbox" name="option3" value="pathfile" />Type</td>
<td><input type="checkbox" name="option4" value="filesize" />Number</td>
</tr>
https://jsfiddle.net/o6e3pc3a/8/
Lets say I have table with 10 rows and in each row 10 columns of checkboxes
before the user submits I want to add the following validation:
in each row at least two checkbox are checked!
<form name="myForm">
<div data-ng-controller="myController">
<table border="1">
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
...
</table>
<button data-ng-click="save()" ng-disabled="$myForm.invalid">Save</button>
</form>
$scope.save = function() {
if (myForm.$valid){
alert("can submit the form...")
}
};
How to do this? where to add the validation functionality?
I recently answered a similar question with a custom directive that allows the user to define groups of controls (text-fields, selects, checkboxs, whatever) and require that at least one control in each group not empty.
It should be easy to modify so that at least two controls are not empty.
Then myForm.$valid will always be "up-to-date" (so you can use it to give visual feedback or allow the form to be submitted).
If your checkboxes are static in the HTML, You can bind the checkboxes to boolean models like:
<input type="checkbox" ng-model="checked[1]">
Validate
and then use something like this to validate
$scope.checked = {};
$scope.validate = function() {
var count=0;
angular.forEach($scope.checked, function(k,v){ if (k) count++; });
if (count > 2)
alert("validated");
};
To extend this to multiple rows is trivial.
You can see this working on here: http://plnkr.co/edit/thbJ81KWUDyF6WTcWL9u?p=preview
Of course you can define an array in the controller and use the ng-repeat directive in conjunction with this idea.
The reason not to use radio buttons here is because I want the option to have all checkboxes unchecked, and there are other behaviors linked to checking and unchecking.
When the 1st box is checked, all radio buttons in the row are selected.
(see here How to use javascript to select a row of radio buttons when a checkbox is selected)
When the 1st button is unchecked, all the radios in that row are deselected.
Whenever a checkbox is checked, the other checkbox should automatically be deselected.
I'm thinking maybe I could do this by css class. So, whenever one checkbox in the class is checked, the others are automatically unchecked.
I'm imagining code like this:
function uncheckOther(row_id) {
var row = document.getElementById(row_id)
var theClassName = row.className;
var classGroup = document.getElementsByClassName(theClassname);
for(var i=0; i<classGroup.length; i++) {
if(classGroup[i].id != row_id) {
classGroup[i].radio = unchecked;
}
}
}
How would I do this? Here's the example HTML with id's and classes in the tr elements, and checkboxes in the 1st child td elements:
<form name="form3" action="testfile4.php" method="get">
<table border="1"><thead>
<tr><th>Select entire row</th><th>item_code</th><th>page</th><th>usd_dn</th></tr>
</thead>
<tbody>
<tr id="534" class="15838">
<td ><input type="checkbox" onclick="select_row(534);"></td> <td>15838 <input type="radio" name="15838|item_code" value="534" /></td>
<td>284<input type="radio" name="15838|page" value="534" /></td>
<td>$73.00<input type="radio" name="15838|usd_dn" value="534" /></td>
</tr>
<tr id="535" class="15838">
<td ><input type="checkbox" onclick="select_row(535);"></td> <td>15838 <input type="radio" name="15838|item_code" value="535" /></td>
<td>299
<input type="radio" name="15838|page" value="535" /></td>
<td>$73.00<input type="radio" name="15838|usd_dn" value="535" /></td>
</tr>
<tr id="565">
<td ><input type="checkbox" onclick="select_row(565);"></td> <td>1611 <input type="radio" name="1611|item_code" value="565" /></td>
<td>66<input type="radio" name="1611|page" value="565" /></td>
<td>$3,350.00
<input type="radio" name="1611|usd_dn" value="565" /></td>
</tr>
<tr id="566">
<td ><input type="checkbox" onclick="select_row(566);"></td> <td>1611 <input type="radio" name="1611|item_code" value="566" /></td>
<td>66<input type="radio" name="1611|page" value="566" /></td>
<td>$3,225.00
<input type="radio" name="1611|usd_dn" value="566" /></td>
</tr>
</tbody>
</table>
</form>
I'm ok with jquery answers but prefer pure javascript at the moment.
There are plenty of reasons to use checkboxes instead of radio buttons...
if ($('#myDivID').attr('checked'))
This will tell you if it's checked. To loop through all, and keep only the current checked one checked, you could do something like this in the $(document).ready() function:
$('input[type="checkbox"]').click(function () {
$('input[type="checkbox"]').attr('checked', false);
$(this).attr('checked', true);
});
Any checkbox checked will STAY checked. The rest will be unchecked.
The native way would be to use the checked property that's on the checkbox dom object:
document.getElementById("checkboxId").checked = false;
Or, to toggle:
var cb = document.getElementById("checkboxId");
cb.checked = !cb.checked;
Here's the documentation for the checkbox dom object, if you're trying to not use jQuery.