.onchange or .onclick and checkbox value to JS script - javascript

I have an array of checkboxes group into class='year'. I would like to call a function in JS when a checkbox is checked.
The html is,
<table class="inner" id="searchTable">
<search>Exam Type:<th>
<?php
foreach($exams as $key=>$value):
echo "<tr><td class='left'><input type='checkbox' class='year' id='$key' name='$key' value='$value'
if ($category['selected'])
{
echo ' checked';
}
> $value</td></tr>";
endforeach; ?>
</table>
This table is inside a form. but I am too worried about the form at the moment.
The JS should create a table with a row when any checkbox is checked.
function yearTable(){
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
var empty = document.createTextNode("year.value");
/*var empty = document.createTextNode("");*/
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
document.getElementByClassName('year').onchange = yearTable;
I have tried using .onchange and .clicked but neither do anything when a box is checked.
Also I need the value checked in the JS.
I tried year.value but that doesn't work. Prviously I has a select options menu with id = 'exam' and I was able to get the value using exam.value but I can't figure out how to do soemthing equivalent for these checkboxes.
Any help would be greatly appreciated.
Thanks

While an html document may contain only one element with a specific id, there can be several elements with the same class.
So, there is no such a function as document.getElementByClassName. There is a function document.getElementsByClassName, and it returns an array of elements, so could call that function and then iterate over its return value, setting the needed callbacks.
Also, the code you posted must have thrown an exception at this line:
document.getElementByClassName('year')
So if you looked at developer tools in Chrome or Firebug in Firefox, you would probably see an error.

Got it,
function yearTable(){
var year = this.value;
var table = document.getElementById("searchYear");
var row = document.createElement("tr");
var cell = document.createElement("td");
if (this.checked){
var empty = document.createTextNode(year);
}
cell.appendChild(empty);
row.appendChild(cell);
table.appendChild(row);
}
var checkboxes = document.getElementsByClassName('year');
for(var index in checkboxes){
checkboxes[index].onchange = yearTable;
}
Thanks

Related

How to get a count of checkboxes checked on pagination Jquery dataTables

Below is my code, I want to get the count of checked checkboxes of all pages in my DataTable. Please advice how to proceed
<td align="center"><input type="checkbox" align="center" id="all" class="groupCheckBox" name="emails[]" value=' . $user['id'] . '></td>
Below code I used for get the values of checked boxes in all pages on button click
$('#merge_button').click(function () {
var id = "";
var oTable = $("#userTable").dataTable();
$(".groupCheckBox:checked", oTable.fnGetNodes()).each(function () {
if (id != "") {
id = id + "," + $(this).val();
} else {
id = $(this).val();
}
document.getElementById("email").value = id;
});
});
but now I want to count the checkedboxes without button click function whenever user clicked on checkboxes and deduct count when unchecking boxes . pls advice
var table = $("#userTable").DataTable();
var countchecked = table
.rows()
.nodes()
.to$() // Convert to a jQuery object
.find('input[type="checkbox"].groupCheckBox:checked').length;
Uses the most recent API
"...please be aware that using deferRender will cause some nodes to be created only when they are required for display, so they might not be immediately available when this method is called." from https://datatables.net/reference/api/rows().nodes()
Quite easy.
$("td input[type='checkbox']:checked").length;

How to create an input field and then prepopulate the field with

Please no jquery.
I've seen several examples of this where the input field already exists on the page before you update it, but I'd like to dynamically create the input field and then populate it with information available from the page (hence current_value variable defined above this code snippet):
for (i=0; i<tables.length; i++) {
(function(i) {
var sp = document.createElement('span');
var act_table = document.createElement('table');
act_table.id = 'act-tests-' + i;
act_table.style.display = 'none';
var test_name_input = document.createElement('tr');
test_name_input.innerHTML = '<tr><td width="100px">Name</td><td><input type="text" class="wideValue testName input"></td></tr>';
test_name_input.setAttribute('value', current_rule);
act_table.innerHTML ='<tbody><tr>LOTS OF TABLE ROWS HERE</tr></tbody>';
act_table.insertBefore(test_name_input,act_table.firstChild);
sp.appendChild(act_table);
}
The field is being shown but not populated with my current_value.
Any help greatly appreciated.
In your example you set an attribute to the tr, instead of the created input field.
try to do this:
document.getElementsByClassName("input")[you_index].setAttribute("value", current_value);
Here an example: http://jsfiddle.net/35g0ks0t/

How to delete a selected row of a table created in JavaScript?

Here is my code:
<body>
<div id="metric_results">
<div id="form">
<form name="myForm" >
...//get course IDnumber and course score
</form>
</div>
<div id="table">
<table id="TABLE" border = '1'>
</table>
</div>
<script type="text/javascript">
//when click on "add" button,call "addTable" function.
document.getElementById("add_button").onclick = function() {addTable()};
document.getElementById("delete_button").onclick = function() {DeleteTableRow()};
var stock = new Array();
var i = 0;
function addTable() { //create table with 3 column(idnumber,score,checkbox)
var c = document.createElement("INPUT");
c.setAttribute("type", "checkbox");
stock[i] = new Array(id, score);//id= course ID number,score=course score, get from form
//Create table row and append it to end of table
var tr = document.createElement('TR');
for (j = 0; j < 3; j++) {
var td = document.createElement('TD');
if(j == 2){
td.setAttribute("id","check_box"+(i+1));
td.appendChild(c);}
else{
td.appendChild(document.createTextNode(stock[i][j]));}
tr.appendChild(td);
}
table.appendChild(tr);
i=i+1
}
// Delete courses that their checkbox is on.
function DeleteTableRow(){
var check_boxes=new Array();
for(j=0; j<i ;j++){
check_boxes[j]= document.getElementById("check_box"+(j+1));
if(check_boxes[j].checked==true){document.getElementById("TABLE").deleteRow(j+1);}
}
</script>
</body>
I create a form which get course idnumber and course score.At first, when I fill the form, javascript creates a table so when I click the "add" button, I can add courses. Now, I want to add another function named DeleteTableRow() to delete the selected rows.
When I create the table for each course,I create a checkbox column and set "id" for each rows checkbox(td.setAttribute("id","check_box"+(i+1));) so in the DeleteTableRow() function I use getElementById("check_box"+(j+1)) in the for loop.
Everything is OK but I can't check the value of the check box and I can't delete the selected rows. what should I do and how do I check it?
Your main problem is that in your addTable function you set the id attribute on the table cell, rather than the checkbox. Naturally, cells don't have a checked attribute. You could fix this by doing the setAttribute('id', ...) on c, before the loop.
Note there are a few strange things about your code - for example, you should really use the literal [] when defining a new array, rather than the new Array() call; but having said that there doesn't seem to be any need for the check_boxes array in the first place, since you never use it.
In any case, your code would be a lot simpler if you used something like jQuery, which is pretty much the default for doing DOM manipulation in Javascript these days.

Why is this tiny bit of jQuery messing up the rest of my JavaScript?

I have an area on my page that has tabular data. I am attempting to add in-line editing of the values in each row. I have tried jqGrid, but it will not work for my needs. So, I am attempting a "home brew" version of in-line editing. My table is simple enough:
<table>
<tbody>
<tr id="row0" onClick="changeMe(this);">
<td>
some value
</td>
<td>
some other value
</td>
<td>
...
</td>
</tr>
<tr id="rowN" onClick="changeMe(this);">
<td>
...
</td>
</tr>
</tbody>
</table>
When a user clicks anywhere on the TR, I want my JavaScript to change all static text to the proper form inputs. The first two elements of the form are select boxes. The first box needs to be filled in before the second box's options are available. Here is part of the JavaScript I am using to accomplish this:
function changeMe(row){
var serviceArray = ["option_1-1","option_1-2","option_1-3","option_1-4","option_1-5"]
for(var i=0; i<2; i++){
if(row.children[i].children.length == 0){
var selectBox = document.createElement("select");
var.setAttribute("id",serviceArray[i]);
var.setAttribute("name",serviceArray[i]);
switch(i){
case 0:
$.getJSON("./dataGetter.php?qid=" + Math.random(),function(data){
$.each(data,function(key,value){
var option = document.createElement("option");
var innerValue = document.createTextNode(value);
option.appendChild(innerValue);
option.setAttribute("value",value);
selectBox.appendChild(option);
});
});
selectBox.setAttribute("onChange","someFunction(this.value)");
break;
case 1:
selectBox.setAttribute("onChange","someOtherFunction(this.value)");
var option = document.createElement("option");
option.setAttribute("selected","selected");
option.setAttribute("disabled","disabled");
var textNode = document.createTextNode("\u2190 choose that first");
option.appendChild(textNode);
selectBox.appendChild(option);
break;
}
row.children[i].innerHTML = null;
row.children[i].appendChild(selectBox);
}
}
}
This is where my problem comes in. when a user clicks the TR, child 0 of the TR, which is a TD with text, should be converted into the appropriate select box, filled with the appropriate data from the database. This, however, is not happening. What is happening, is that child 1 of the TR (i.e., the second TD) is the one being converted instead.
Just as a test, I added a new test array to the function:
var testArray = new Array("option_2-1","option_2-2","option_2-3","option_2-4","option_2-5");
and changed my JavaScript to the following:
function changeMe(row){
var serviceArray = ["option_1-1","option_1-2","option_1-3","option_1-4","option_1-5"];
var testArray = new Array("option_2-1","option_2-2","option_2-3","option_2-4","option_2-5");
for(var i=0; i<2; i++){
if(row.children[i].children.length == 0){
var selectBox = document.createElement("select");
var.setAttribute("id",serviceArray[i]);
var.setAttribute("name",serviceArray[i]);
switch(i){
case 0:
$.each(testArray,function(key,value){
var option = document.createElement("option");
var innerValue = document.createTextNode(value);
option.appendChild(innerValue);
option.setAttribute("value",value);
selectBox.appendChild(option);
});
selectBox.setAttribute("onChange","someFunction(this.value)");
break;
case 1:
selectBox.setAttribute("onChange","someOtherFunction(this.value)");
var option = document.createElement("option");
option.setAttribute("selected","selected");
option.setAttribute("disabled","disabled");
var textNode = document.createTextNode("\u2190 choose that first");
option.appendChild(textNode);
selectBox.appendChild(option);
break;
}
row.children[i].innerHTML = null;
row.children[i].appendChild(selectBox);
}
}
}
When I make this change, the first TD (child 0) of the TR is changed as it should be.
When I go directly to my dataGetter.php page in the browser, I get the correct data:
["option_2-1","option_2-2","option_2-3","option_2-4","option_2-5"]
I know this is the correct data, because I put an "alert();" just after the "$.each" line, and the proper data was shown in the alert pop-up.
So, I'm not sure what is happening here. It looks like the one line
$.getJSON("./dataGetter.php?qid=" + Math.random(),function(data){
}
is messing up my switch statement, and populating the second TD (child 1) with child 0 and child 1 data both. It's almost like the "break" in "case 0" is being removed, and all the logic is falling through to the second case.
UPDATE: If I add the line "alert(i);" after my for loop, then everything works as it should ... except for the annoying pop-up.
For all those that are interested, I have figured out the problem. It appears that my switch statement was completing before the AJAX return came back. So, I set "async" to "false" and everything worked perfectly.

Use jQuery insertAfter in existing function that appends table

Here is what I have so far: http://jsfiddle.net/JEAkX/1/
I am trying to get the appended cells to come after the last tr. Furthermore, I am attempting to change the appendTable(id) function so that the output cells have their content inside an <input> field like the original cells.
For the <input> addition I have tried:
Adding the input field code <input type='text' size='1' value='subset[i++]' /> at various point with no luck I also tried it in another location but changed the value to value='c'.
For append after last tr I have tried:
Using jQuery and .insertAfter('#alphabetTable tbody>tr:last') I added it to various parts of the cell.appendChild(document.createTextNode(subset[i++])); line but had no luck..probably the wrong placement?
I feel like I am sort of on the right track but lack the Javascript knowledge to know exactly where to insert the code and if surrounding code needs change.
It'll be easier with JQuery but here's a hint:
function appendTable(id)
{
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var i = 0;
var html = '<tr>';
for(i=0;i<4;i++){
html += '<td><input type="text" size="1"/></td>';
}
html += '</tr>';
tbody.innerHTML += html;
}
Jquery:
var $tbody = $('#mytableid tbody:eq(0)');
var $tdLen = $('#mytableid tbody:eq(0) tr:eq(0) td').length; // cell length in row
$("<tr>").appendTo($tbody);
//append cells to row with input text
for (var i=0;i<$tdLen;i++){
var inp = $("<input>").attr("type","text").attr("name","text"+i).val(i);
var tdTemo = $("<td>");
inp.appendTo(tdTemo);
tdTemo.appendTo("tr:last");
}
this script will append row to table and add 4cells contain input type text :)

Categories