Why is the first table column skipped? - javascript

As this screenshot shows, the Title header is misaligned with the table data.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Writer's Tryst - Manage Uploads</title>
<style>
table {
border-spacing:0;
border-collapse:collapse;
}
td, th {
padding: 5px;
}
.nbr-pages {
width: 48px;
text-align: right;
padding-right: 2px;
}
.delete {
cursor: pointer;
}
</style>
</head>
<body>
<h1>Manage Uploads</h1>
<form id="form-manage-uploads">
<table id="table-writer-uploads">
<tbody>
<tr>
<th>Delete</th><th>TItle</th><th>Type</th><th>Genre</th><th>Length</th><th>PDF</th><th>Save</th>
</tr>
<tr class="tr-clone" >
<td><img class="delete" src="img/icons/delete.png" alt="delete" /> </td>
<td><input class="id" name="id" type="hidden" /></td>
<td><input class="title" name="title" placeholder="Title" autofocus="true" /></td>
<td>
<select class="form-type" name="form-type">
</select>
</td>
<td>
<select class="genre" name="genre">
</select>
</td>
<td><input class="nbr-pages" name="nbr-pages" required placeholder="Pages" /></td>
<td>Synopsis</td>
<td><input type="button" class="save btn btn-custom-primary" value="Save" /></td>
<td><input type="hidden" class="id" name="id" /></td>
</tr>
</tbody>
</table>
<input class="current-id" type="hidden" />
</form>
<script src="js/common.js"></script>
<script src="js/manage-uploads.js"></script>
</body>
</html>
The table is built using JavaScript:
function getWritersData() {
var data = {};
data.action = 'get-writer-data';
data["account-id"] = localStorage.getItem("account-id");
ajax('post', 'php/manage-uploads.php', data, getSuccess, "Error retrieving writer's data: ");
function getSuccess(data) {
var trClone = $(".tr-clone");
var jsonData = $.parseJSON(data);
var count = 0;
for (var key in jsonData) count++;
if (key != undefined) {
count--;
$.each(jsonData, function (index, value) {
trClone = trClone.clone().insertAfter($(".tr-clone:last"));
trClone.find(".id").val(value.ID);
trClone.find(".title").val(value.Title);
trClone.find(".form-type").val(value.FormType);
trClone.find(".genre").val(value.Genre);
trClone.find(".nbr-pages").val(value.NumberOfPages);
var filepath = "uploads/" + value.Filename;
var synopsis = trClone.find(".synopsis");
var sv = synopsis.val(filepath);
synopsis.attr("href", filepath);
});
} else {
$("h1").append("<br/><br/><div class='but-custom-warning'>No records were found.</div>"); //.css("disp
$("table").css("display", "none");
}
$(".tr-clone:first").css("display", "none");
}
}

You have an extra table column for the hidden input:
There's no need for this to be in its own table cell, so combine it with one of the other cells.
<td><input class="id" name="id" type="hidden" /><input class="title" name="title" placeholder="Title" autofocus="true" /></td>

You got an extra column with nothing visible in it:
<td><input class="id" name="id" type="hidden" /></td>
I'd recommend you put the hidden field in another column or use this:
<th colspan="2">Delete</th>

Related

Swap table cells between rows based on clicking position

I am creating a table of two rows which each consist of 0s and 1s. I have created a function which allows the user to click onto two table cells and a button which swaps the two selected table cells.
I want to be able to swap the td elements from position 0 of a row to the table cell that is selected, and the same for the second row so that multiple table cells are swapped between two rows.
for example, if I select the sixth table cell in both rows, it should swap all the table cells from the beginning of the row to the sixth table cell
I have featured below the code which uses jQuery. Any help will be greatly appreciated:
<html>
<style>
body{
font-size: 30px;
text-align: center;
background-color: ivory;
}
table{
width:100px;
}
h1{
font-family: Helvetica;
font-size: 30px;
}
th{
border: 10px solid black;
padding: 5px;
font-size: 70px;
}
td{
border: 10px solid black;
padding: 5px;
font-size: 130px;
}
tr.center, td.center{
text-align: center;
}
td:not(.notSelectable) {
cursor: pointer
}
td.selected,
td.lastSelected {
background-color: yellow;
color: white;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("table td:not(.notSelectable)").click(function() {
$(".lastSelected").removeClass("lastSelected");
$(".selected").toggleClass("selected lastSelected");
$(this).addClass("selected");
});
});
function swap() {
if ($(".selected, .lastSelected").length != 2) { return; }
$("#lblSelectedDate").text($(".selected").siblings(".date").text());
$("#lblLastSelectedDate").text($(".lastSelected").siblings(".date").text());
// Set label with value data
$("#lblSelectedValue").text($(".selected").children("input[type=hidden]").val());
$("#lblLastSelectedValue").text($(".lastSelected").children("input[type=hidden]").val());
// Swap cell data
var temp = $(".lastSelected").html();
$(".lastSelected").html($(".selected").html());
$(".selected").html(temp);
$(".selected, .lastSelected").removeClass();
}
</script>
<body>
<button onclick="swap();">Crossover</button>
<br /><br />
<table border="1" align = "center">
<tbody>
<tr>
<td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor = "#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor = "#4caf50">1<input type="hidden" value="1" /></td>
<th>P1</th>
</tr>
<tr>
<td bgcolor ="#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor= "#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor ="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor ="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor ="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor= "#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor= "#ff0000">0<input type="hidden" value="0" /></td>
<th>P2</th>
</tr>
</tbody>
</table>
</body>
</html>
I tried to figure out what you need, If I am correct you want to swap td with content between 2 rows with same index, but it should swap all the tds starting from zero index till the selected td index among 2 rows.
If my above statement is correct, you must have requirement to select same td index in both rows, other wise uneven index selection will generate abnormality.
Check my complete working code here:
https://github.com/helloritesh000/swap-table-cells-between-rows-based-on-clicking-position
Comment if required.
<pre>
<script>
$(function() {
$("table td:not(.notSelectable)").click(function() {
var otherTrIndex = ($(this).closest('tr').index() == 1) ? 0 : 1;
if($(this).closest('tr').find('td.selected').length >= 1
|| $(this).closest('tr').find('td.lastSelected').length >= 1
|| ($('td.selected').length > 0
&& $($('table').find('tr')[otherTrIndex]).find('td.selected').length != ($(this).index() + 1)
)
)
{
return false;
}
$(".lastSelected").removeClass("lastSelected");
$(".selected").toggleClass("selected lastSelected");
for(i = 0; i <= $(this).index(); i++)
{
$($(this).closest('tr').find('td')[i]).addClass("selected");
}
});
});
function swap() {
var selectedTd = $('td.selected');
var lastSelectedTd = $('td.lastSelected');
for(i = 0; i < selectedTd.length; i++)
{
var selectedTdHtml = selectedTd[i].outerHTML;
selectedTd[i].outerHTML = lastSelectedTd[i].outerHTML;
lastSelectedTd[i].outerHTML = selectedTdHtml;
}
$(".selected, .lastSelected").removeClass();
}
</script>
</pre>
The following demo will swap with the counterpart of the .selected cell (from either row -- bidirectionally). Details are commented in demo.
// Counter
let id = 0;
// Click on any cell...
$('table td').on('click', function() {
// Increment counter
let idx = id++;
// Get index of clicked cell
let i = $(this).index();
/*
Add/remove .selected to/from clicked cell and...
...add data-id attribute to it with the value of counter
*/
$(this).toggleClass('selected').data('id', idx);
// Find the clicked cell's counterpart
let otherCell = $(this).closest('tr').siblings('tr').find('td').eq(i);
// Give it the class .marked+counter
otherCell.addClass(`marked${idx}`);
});
// When button is clicked...
$('button').on('click', function() {
// On each .selected cell...
$('.selected').each(function() {
// Get .selected data-id
let idx = $(this).data('id');
// Find its counterpart
let otherCell = $(`.marked${idx}`);
// Get the value of .selected's hidden input
let zer00ne = $(this).find(':hidden').val();
// Get the value of counterpart's hidden value
let other01 = otherCell.find(':hidden').val();
// Replace the contents with one another
$(this).html(`${other01}<input type="hidden" value="${other01}">`);
otherCell.html(`${zer00ne}<input type="hidden" value="${zer00ne}">`);
});
// Cleanup all of the cells
$('td').each(function() {
this.className = '';
$('.selected').removeData();
});
});
body {
font-size: 30px;
text-align: center;
background-color: ivory;
}
table {
width: 100px;
}
h1 {
font-family: Helvetica;
font-size: 30px;
}
th {
border: 10px solid black;
padding: 5px;
font-size: 70px;
}
td {
border: 10px solid black;
padding: 5px;
font-size: 130px;
}
tr.center,
td.center {
text-align: center;
}
td:not(.notSelectable) {
cursor: pointer
}
td.selected,
td.lastSelected {
background-color: gold;
color: black;
}
td[class^=marked] {
background-color: black;
color: gold;
}
<button>Crossover</button>
<br /><br />
<table border="1" align="center">
<tbody>
<tr>
<td bgcolor="#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor="#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor="#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor="#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor="#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor="#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor="#4caf50">0<input type="hidden" value="0" /></td>
<td bgcolor="#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor="#4caf50">1<input type="hidden" value="1" /></td>
<td bgcolor="#4caf50">1<input type="hidden" value="1" /></td>
<th>P1</th>
</tr>
<tr>
<td bgcolor="#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor="#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor="#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor="#ff0000">0<input type="hidden" value="0" /></td>
<td bgcolor="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor="#ff0000">1<input type="hidden" value="1" /></td>
<td bgcolor="#ff0000">0<input type="hidden" value="0" /></td>
<th>P2</th>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Looks like you're assigning the value of one element to the other without first saving the original value. So both of them end up with the value of the second.

Dynamically add/remove rows from html table

I am working on a table that can be modified by pressing "Delete" buttons in each row and "Insert row" to add a new one at the end:
So far by now my code is:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow(id,row) {
document.getElementById(id).deleteRow(row);
}
function insRow(id) {
var filas = document.getElementById("myTable").rows.length;
var x = document.getElementById(id).insertRow(filas);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = '<input type="text" id="fname">';
z.innerHTML ='<button id="btn" name="btn" > Delete</button>';
}
</script>
</head>
<body>
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',0)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',1)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',2)"></td>
</tr>
</table>
<p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>
</body>
</html>
But i cannot attach the function onclick="deleteRow('myTable',0)" on
z.innerHTML ='<button id="btn" name="btn"> Delete</button>'
¿Is there something else i need to declare in order to make that button work when clicked?
Thanks for your answers
First off, IDs must be unique, so why not use classes here instead?
Second, if you're using jQuery, then use jQuery.
Third, you need to use event delegation when dynamically adding elements, so try the following:
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#myTable').append('<tr><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
<p>
<input type="button" value="Insert row">
</p>
On each DeleteRow(tableId,Index) function you are passing table id and static index that's why document.getElementById("mytable").deleteRow(Index) first find table node then find no of tr element as children and assigns the index to tr element start from 0 and delete the matching index tr element.
Whenever you delete first row then it will matches the 0 index from 3 elements and deletes the first row. Now there are 2 tr left with index 0 and 1 dynamically assign by table but you trying to match with 1 and 2.
for deleting second row it will delete tr with index 1 (third tr) not the second tr.
for deleting third row actual index is 0 (after deleting 2 rows) and you are passing 1 because of this reason it wont find the matching index.
Here is Simple javascript soltution.
<script>
function delRow(currElement) {
var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(parentRowIndex);
}
</script>
and html,
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
</table>
here is jsfiddle exmple
Click Here
Say you have the following table:
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="firstName" /></td>
<td><input type="text" name="lastName" /></td>
<td> <input type="text" name="email" /></td>
</tr>
</tbody>
<p>
<label>Insert</label>
<input type="number" value="1" id="numberOfRowsToInsert">
<input type="button" value="Insert row" id="insert-line-button">
</p>
</table>
The following jquery code will generate x number of rows entered by the user and append them to the bottom of the table with the ability to delete them if needed:
$('#insert-line-button').on("click", function(){
var noOfRows = $('#numberOfRowsToInsert').val();
for(var i = 0; i < noOfRows; i++){
$('#myTable').append("<tr>" +
"<td><input type='text' name='firstName' /></td>" +
"<td><input type='text' name='lastName' /></td>" +
"<td> <input type='text' name='email' /></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
}
});
And the following jquery code will remove the rows when clicked on the 'Delete' button:
$("#myTable").on('click', 'input[id="deleteRowButton"]', function(event) {
$(this).parent().parent().remove();
});
Go through below code:
You can see that this is the most basic way to create dynamic table. You can use this approach and can try yourself to remove rows from the existing table. I have not used any pluggin/ jquery. You can just copy this code and save as an html file to see how this code is working. Go head! Good luck.
<html>
<script>
function CreateTableAndRows(){
var mybody = document.getElementsByTagName("body")[0];
var newTable = document.createElement("table");
var newTableHead = document.createElement("thead");
var headRow = document.createElement("tr");
var headHead1 = document.createElement("th");
var headRowCellValue = document.createTextNode("Device Name");
headHead1.appendChild(headRowCellValue);
var headHead2 = document.createElement("th");
headRowCellValue = document.createTextNode("Start Timing");
headHead2.appendChild(headRowCellValue);
var headHead3 = document.createElement("th");
headRowCellValue = document.createTextNode("End Timing");
headHead3.appendChild(headRowCellValue);
var headHead4 = document.createElement("th");
headRowCellValue = document.createTextNode("Duration");
headHead4.appendChild(headRowCellValue);
headRow.appendChild(headHead1);
headRow.appendChild(headHead2);
headRow.appendChild(headHead3);
headRow.appendChild(headHead4);
newTableHead.appendChild(headRow);
newTable.appendChild(newTableHead);
var newTableBody = document.createElement("tbody");
for(var rowCount=0;rowCount<5;rowCount++)
{
var newTableRow = document.createElement("tr");
for(var cellCount=0; cellCount<4; cellCount++)
{
var newTableRowCell = document.createElement("td");
var cellValue = document.createTextNode("cell is row"+rowCount+", coumn "+cellCount);
newTableRowCell.appendChild(cellValue);
newTableRow.appendChild(newTableRowCell);
}
newTableBody.appendChild(newTableRow);
}
newTable.appendChild(newTableBody);
newTable.setAttribute("border","2");
mybody.appendChild(newTable);
}
</script>
</head>
<body>
<input type="submit" onclick="CreateTableAndRows();">
</body>
</html>

show/hide div based on radio button checked

I am trying to show/hide text fields based on checked radio buttons checked. Here is my code; it works fine if I don't use table tags, when using table tags, Javascript doesn't work
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked) {
document.getElementById(id + '_form_fields').style.display = 'block';
document.getElementById(other_id + '_form_fields').style.display = 'none';
} else {
document.getElementById(id + '_form_fields').style.display = 'none';
document.getElementById(other_id + '_form_fields').style.display = 'block';
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onchange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');">
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td><tr>
<!-- If Individual Form is checked -->
<div id="personal_form_fields">
<tr><td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr><td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
</div>
<!-- If Corporation Form is checked -->
<div id="corporate_form_fields" style="display: none;">
<tr><td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</div>
</table>
What putvande might mean by "strange markup" is that your <div id="personal_form_fields"> is in the table, with its parent being a table tag. That's not right. The tr should contain the td, which contains the div, not the other way around.
If you're trying to change visibility, this syntax error could be the problem.
Simply add a class to the TR of each group and show / hide the class...
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked)
{
class_display(id + '_form_fields','block');
class_display(other_id + '_form_fields','none');
} else {
class_display(id + '_form_fields','none');
class_display(other_id + '_form_fields','block');
}
}
function class_display(tr_class,display)
{
var tr_ele = document.getElementsByClassName(tr_class);
for (var i = 0; i < tr_ele.length; ++i) {
var item = tr_ele[i];
item.style.display = display;
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onChange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');" checked>
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td>
<tr>
<!-- If Individual Form is checked -->
<tr class="personal_form_fields">
<td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr class="personal_form_fields">
<td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
<!-- If Corporation Form is checked -->
<tr class="corporate_form_fields" style="display: none;">
<td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</table>

Javascript jQuery textbox creation and output

Currently, I have a two table rows with two textboxes. I want to buid a button which allows the user to add and subtract an author row depending on how many they want. Once they increase the amount of authors they need for input, the user clicks on the generate button, the input from the textboxes will be outputed at the bottom of the page. I was trying to pull this off with javascript and jQuery. I am a ten day old student with javascript and jQuery and feel as if I have bit off more than I can chew.
An example of what I want can be found at this lnk: http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/. However, I need the input from the textboxes outputed on the same page.
<!DOCTYPE html>
<head>
</head>
<body>
<table>
<tbody>
<tr>
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
<tr>
<td>Second Author (If Any)</td>
<td><input type="text" id="3" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="4" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<br>
<br>
<output id="20"></output>
<br>
<br>
</body>
</html>
<script type=text/javascript>
function myFunction()
{
var firstlast=document.getElementById("1").value;
if (firstlast==null || firstlast=="")
{
firstlast;
}
else if(firstlast!=null || firstlast!="")
{
firstlast=document.getElementById("1").value + ", ";
}
var firstfirst=document.getElementById("2").value;
if (firstfirst==null || firstfirst=="")
{
firstfirst;
}
else if(firstfirst!=null || firstfirst!="")
{
firstfirst=document.getElementById("2").value + ". ";
}
var secondlast=document.getElementById("3").value;
if (secondlast==null || secondlast=="")
{
secondlast;
}
else if(secondlast!=null || secondlast!="")
{
secondlast=document.getElementById("3").value + ", ";
}
document.getElementById("20").innerHTML = firstlast + firstfirst + secondlast;
}
</script>
The jQuery
//wait for the document to be ready
$(document).ready(function()
{
// when generate authors is clicked
$("#generate-authors").click(function()
{
// get the first author row in your table
var author = $(".author-row:first");
// for the amount of authors put into the text box
// insert a copy of the row after the last row
for(i = 0; i < parseInt($("#author-amount").val()); i++)
$(".author-row:last").after(author.clone());
});
// when output data is clicked
$("#output-data").click(function()
{
// go through all the author rows
$(".author-row").filter(function()
{
// add them to the output element
$("#output").append("<p>" + $(this).find("[placeholder=\"Last\"]").val() + ", " + $(this).find("[placeholder=\"First\"]").val() + ".</p>");
});
});
});
The html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
// put the script here
</script>
</head>
<body>
<input id="author-amount" type="text" />
<input id="generate-authors" type="button" value="Generate" />
<br />
<input id="output-data" type="button" value="Output Data" />
<table>
<tbody>
<tr class="author-row">
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<br />
<output id="output"></output>
</body>
</html>
See this Example might be this is that what you want
HTML
<table id="table">
<tbody>
<tr>
<td>Author</td>
<td><input type="text" id="1" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="2" class="normalinput" placeholder="First"></td>
</tr>
<tr>
<td>Second Author (If Any)</td>
<td><input type="text" id="3" class="normalinput" placeholder="Last"></td>
<td><input type="text" id="4" class="normalinput" placeholder="First"></td>
</tr>
</tbody>
</table>
<input type="button" id="generat" value="add">
<input type="button" id="remove" value="remove">
<input type="button" id="display" value="display">
<output id="20"></output>
JS
$(document).ready(function(){
$("#generat").click(function(){
var clone = $("#table tr:first").clone();
$("#table tbody:last").append(clone);
});
$("#remove").click(function(){
$("#table tbody tr:last").remove();
});
$("#display").click(function(){
$("#20").html("");
$("table tr").each(function(){
$(this).find("input").each(function(){
$("#20").append(($(this).val()));
});
});
})
});
LINK

Need to count checkboxes on a button click on it does not work

The following form has 11 checkboxes.. I set up the script to execute a function on the click of a button that would show a popup telling how many of the checkboxes were checked.. However, when I click the button, nothing happens. I think my mistake may be in the function code and discerning the use of name vs. id etc... But I am not sure about what the mistake was.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<style type="text/css">
body {background-color:Gray;}
body {text-align:left;}
p {text-align:center}
</style>
<title>My First Project</title>
</head>
<body>
<form id="form1" >
<table align=center>
<tr>
<td><input type="checkbox" name="ingredients" value="sausage" /> Italian Sausage<br /></td>
<td><input type="checkbox" name="ingredients" value="mushrooms" /> Fresh Mushrooms<br /></td>
<td><input type="checkbox" name="ingredients" value="pepperoni" /> Pepperoni<br /></td>
</tr>
<tr>
<td><input type="checkbox" name="ingredients" value="onions" /> Fresh Onions<br /></td>
<td><input type="checkbox" name="ingredients" value="ham" /> Diced Ham<br /></td>
<td><input type="checkbox" name="ingredients" value="peppers" /> Fresh Green Peppers<br /></td>
</tr>
<tr>
<td><input type="checkbox" name="ingredients" value="beef" /> Beef<br /></td>
<td><input type="checkbox" name="ingredients" value="tomatoes" /> Diced Tomatoes<br /></td>
<td><input type="checkbox" name="ingredients" value="bacon" /> Bacon Bits<br /></td>
</tr>
<tr>
<td><input type="checkbox" name="ingredients" value="green" /> Green Olives<br /></td>
<td><input type="checkbox" name="ingredients" value="olives" /> Ripe Olives<br /></td>
</tr>
</table>
<br />
<script type="text/javascript">
function anyCheck(form) {
var total = 0;
var max = form.ckbox.length;
for (var idx = 0; idx < max; idx++) {
if (eval("document.form.ckbox[" + idx + "].checked") == true) {
total++;
}
}
alert("You selected " + total + " boxes.");
}
}
</script>
<input type="button" name="submit" value="Submit" onclick="anyCheck(form1);" />
</form>
</body>
</html>
UPDATED CODE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<style type="text/css">
body {background-color:Gray;}
body {text-align:left;}
p {text-align:center}
</style>
<title>My First Project</title>
</head>
<body>
<form id="form1" >
<table align="center">
<tr>
<td><input type="checkbox" name="ingredients" value="sausage" /> Italian Sausage<br /></td>
<td><input type="checkbox" name="ingredients" value="mushrooms" /> Fresh Mushrooms<br /></td>
<td><input type="checkbox" name="ingredients" value="pepperoni" /> Pepperoni<br /></td>
</tr>
<tr>
<td><input type="checkbox" name="ingredients" value="onions" /> Fresh Onions<br /></td>
<td><input type="checkbox" name="ingredients" value="ham" /> Diced Ham<br /></td>
<td><input type="checkbox" name="ingredients" value="peppers" /> Fresh Green Peppers<br /></td>
</tr>
<tr>
<td><input type="checkbox" name="ingredients" value="beef" /> Beef<br /></td>
<td><input type="checkbox" name="ingredients" value="tomatoes" /> Diced Tomatoes<br /></td>
<td><input type="checkbox" name="ingredients" value="bacon" /> Bacon Bits<br /></td>
</tr>
<tr>
<td><input type="checkbox" name="ingredients" value="green" /> Green Olives<br /></td>
<td><input type="checkbox" name="ingredients" value="olives" /> Ripe Olives<br /></td>
</tr>
</table>
<br />
<script type="text/javascript">
function anyCheck() {
var form = document.getElementById("form1"),
inputs = form.getElementsByTagName("input"),
i,
total = 0;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type.toLowerCase() === "checkbox" && inputs[i].checked)
total++;
}
alert("You selected " + total + " boxes.");
}
}
</script>
<input type="button" name="submit" value="Submit" onclick="anyCheck();" />
</form>
</body>
</html>
There are a couple problems:
You need to pass in either a string or an element into anyCheck. I would do a string.
onclick="anyCheck('form1')"
Inside of anyCheck, you should first get the actual instance of the form into a variable, like this:
form = document.getElementById(form);
You can then loop through each of the items in the form using getElementsByTagName()
var inputs = form.getElementsByTagName("input");
for(var x = 0; x < inputs.length; x++) {
var input = inputs[x];
if(input.type != "checkbox") continue;
if(input.checked) {
total += 1;
}
}
There's a problem in your function call. form1 is undefined.
Use document.getElementById("form1"); instead, like this:
onclick="anyCheck(document.getElementById('form1'));"
Edit:
There's some more problems as well:
There's no ckbox array. Either create an array for that, or use the form.elements array (which will give you all form elements, then you can check to see if it's a checkbox or not).
And you don't need to call eval.
for (var idx = 0; idx < max; idx++) {
if (form.ckbox[idx].checked == true) {
total++;
}
}
This works in newer browsers (IE8+,FF 3.5+,Chrome):
function anyCheck() {
var total = 0;
var max = document.querySelectorAll('[type=checkbox]');
for (var idx = 0; idx < max.length; idx++) {
if (max[idx].checked) {
total++;
}
}
alert("You selected " + total + " boxes.");
}
DEMO: http://jsfiddle.net/6pNjf/1/
As the other answers said, the parameter in anyCheck() needs to be a reference to the form. I'd pass in the id as a string and use document.getElementById() inside the function. Or, if there is only one form, don't even have it as a parameter, something like this:
function anyCheck() {
var form = document.getElementById("form1"),
inputs = form.getElementsByTagName("input"),
i,
total = 0;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type.toLowerCase() === "checkbox" && inputs[i].checked)
total++;
}
alert("You selected " + total + " boxes.");
}
http://jsfiddle.net/ZxyPW/
Your code was trying to use a ckbox array that doesn't exist. What I've shown is how to select all input elements, then test if each one is a checkbox that is checked.
You don't need to use eval at all, certainly not to use an index variable in an array (or array-like object).
Try this code instead.
You got a few problems with you were passing in the form and how you were accessing the elements within the form. I also highly suggest you get IDE with javascript debugger built in. VS 2010 is a free one that you can use to develop html or asp.net code. You can stick with straight html code if you like. I.E. has a built in one if you turn on the correct options.
To use the debugger you can uncomment the //debugger line
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
body
{
background-color: Gray;
}
body
{
text-align: left;
}
p
{
text-align: center;
}
</style>
<title>My First Project</title>
</head>
<body>
<form id="form1">
<table align="center">
<tr>
<td>
<input type="checkbox" name="ingredients" value="sausage" />
Italian Sausage<br />
</td>
<td>
<input type="checkbox" name="ingredients" value="mushrooms" />
Fresh Mushrooms<br />
</td>
<td>
<input type="checkbox" name="ingredients" value="pepperoni" />
Pepperoni<br />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ingredients" value="onions" />
Fresh Onions<br />
</td>
<td>
<input type="checkbox" name="ingredients" value="ham" />
Diced Ham<br />
</td>
<td>
<input type="checkbox" name="ingredients" value="peppers" />
Fresh Green Peppers<br />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ingredients" value="beef" />
Beef<br />
</td>
<td>
<input type="checkbox" name="ingredients" value="tomatoes" />
Diced Tomatoes<br />
</td>
<td>
<input type="checkbox" name="ingredients" value="bacon" />
Bacon Bits<br />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ingredients" value="green" />
Green Olives<br />
</td>
<td>
<input type="checkbox" name="ingredients" value="olives" />
Ripe Olives<br />
</td>
</tr>
</table>
<br />
<script type="text/javascript">
function anyCheck(form)
{
//debugger;
var total = 0;
var max = form.length;
for (var idx = 0; idx < max; idx++)
{
var element = form[idx];
if(element.type == "checkbox" && element.checked)
{
total++;
}
}
alert("You selected " + total + " boxes.");
}
</script>
<input type="button" name="submit" value="Submit" onclick="anyCheck(document.getElementById('form1'));" />
</form>
</body>
</html>

Categories

Resources