Jquery .on(change) event on <select> input only changes first row. - javascript

I have a table whereby people can add rows.
There is a select input in the table that when changed, changes the values in a second select field via ajax.
The problem I have is that if a person adds an additional row to the table, the .on(change) event alters the second field in the first row, not the subsequent row.
I've been racking my brain, trying to figure out if I need to (and if so how to) dynamically change the div id that the event binds to and the div that it affects. Is this the solution? If so, could someone please demonstrate how I'd achieve this?
The HTML form is
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<!--<td><input type="text" placeholder="First Name" name="contact[0][contact_first]"></td>
<td><input type="text" placeholder="Surname" name="contact[0][contact_surname]"></td>-->
<td><select name="asset[0][type]">
<option><?php echo $typeoption ?></option>
</select></td>
<td><select class="manuf_name" name="asset[0][manuf]">
<option><?php echo $manufoption ?></option>
</select></td>
<td><input type="text" placeholder="Serial #" name="asset[0][serial_num]"></td>
<td><input type="text" placeholder="Mac Address" name="asset[0][mac_address]"></td>
<td><input type="text" placeholder="Name or Description" name="asset[0][description]"></td>
<td><select id="site" name="asset[0][site]">
<option><?php echo $siteoption ?></option>
</select></td>
<td><input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]"></td>
<td><select id="new_select" name="asset[0][contact]"></select></td>
<!--<td><input type="email" placeholder="Email" name="contact[0][email]"></td>
<td><input type="phone" placeholder="Phone No." name="contact[0][phone]"></td>
<td><input type="text" placeholder="Extension" name="contact[0][extension]"></td>
<td><input type="phone" placeholder="Mobile" name="contact[0][mobile]"></td>-->
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
The script I have is
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function(){
this.name = this.name.replace(/\[(\d+)\]/,
function(str,p1) {
return '[' + (parseInt(p1,10)+1)+ ']'
})
})
return false;
});
});
$(document).ready(function() {
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last')
if ($last.is(':nth-child(2)')) {
alert('This is the only one')
} else {
$last.remove()
}
});
});
$(document).ready(function() {
$("#myassettable").on("change","#site",function(event) {
$.ajax ({
type : 'post',
url : 'assetprocess.php',
data: {
get_option : $(this).val()
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
})
});
});
</script>
and the assetprocess.php page is
<?php
if(isset($_POST['get_option'])) {
//Get the Site Contacts
$site = $_POST['get_option'];
$contact = "SELECT site_id, contact_id, AES_DECRYPT(contact_first,'" .$kresult."'),AES_DECRYPT(contact_surname,'" .$kresult."') FROM contact WHERE site_id = '$site' ORDER BY contact_surname ASC";
$contactq = mysqli_query($dbc,$contact) or trigger_error("Query: $contact\n<br />MySQL Error: " .mysqli_errno($dbc));
if ($contactq){
//$contactoption = '';
echo '<option>Select a Contact (Optional)</option>';
while ($contactrow = mysqli_fetch_assoc($contactq)) {
$contactid = $contactrow['contact_id'];
$contactfirst = $contactrow["AES_DECRYPT(contact_first,'" .$kresult."')"];
$contactsurname = $contactrow["AES_DECRYPT(contact_surname,'" .$kresult."')"];
$contactoption .= '<option value="'.$contactid.'">'.$contactsurname.', '.$contactfirst.'</option>';
echo $contactoption;
}
}
exit;
}
?>
The code is ugly as sin, but this is only a self-interest project at this stage.
Any assistance would be greatly appreciated.
Cheers,
J.

Working Example: https://jsfiddle.net/Twisty/1c98Ladh/3/
A few minor HTML changes:
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<td>
<select name="asset[0][type]">
<option>---</option>
<option>Type Option</option>
</select>
</td>
<td>
<select class="manuf_name" name="asset[0][manuf]">
<option>---</option>
<option>
Manuf Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="Serial #" name="asset[0][serial_num]">
</td>
<td>
<input type="text" placeholder="Mac Address" name="asset[0][mac_address]">
</td>
<td>
<input type="text" placeholder="Name or Description" name="asset[0][description]">
</td>
<td>
<select id="site-0" class="chooseSite" name="asset[0][site]">
<option>---</option>
<option>
Site Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]">
</td>
<td>
<select id="new-site-0" name="asset[0][contact]">
</select>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
This prepares the id to be incrementd as we add on new elements. Making use of the class, we can bind a .change() to each of them.
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function() {
this.name = this.name.replace(/\[(\d+)\]/,
function(str, p1) {
return '[' + (parseInt(p1, 10) + 1) + ']';
});
});
var lastId = parseInt(newgroup.find(".chooseSite").attr("id").substring(5), 10);
newId = lastId + 1;
$("#myassettable tbody>tr:last .chooseSite").attr("id", "site-" + newId);
$("#myassettable tbody>tr:last select[id='new-site-" + lastId + "']").attr("id", "new-site-" + newId);
return false;
});
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last');
if ($last.is(':nth-child(2)')) {
alert('This is the only one');
} else {
$last.remove();
}
});
$(".chooseSite").change(function(event) {
console.log($(this).attr("id") + " changed to " + $(this).val());
var target = "new-" + $(this).attr('id');
/*$.ajax({
type: 'post',
url: 'assetprocess.php',
data: {
get_option: $(this).val()
},
success: function(response) {
$("#" + target).html(response);
}
});*/
var response = "<option>New</option>";
$("#" + target).html(response);
});
});
Can save some time by setting a counter in global space for the number of Rows, something like var trCount = 1; and use that to set array indexes and IDs. Cloning is fast and easy, but it also means we have to go back and append various attributes. Could also make a function to draw up the HTML for you. Like: https://jsfiddle.net/Twisty/1c98Ladh/10/
function cloneRow(n) {
if (n - 1 < 0) return false;
var html = "";
html += "<tr class='removable' data-row=" + n + ">";
html += "<td><select name='asset[" + n + "][type]' id='type-" + n + "'>";
html += $("#type-" + (n - 1)).html();
html += "<select></td>";
html += "<td><select name='asset[" + n + "][manuf]' id='manuf-" + n + "'>";
html += $("#manuf-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='Serial #' name='asset[" + n + "][serial_num]' id='serial-" + n + "' /></td>";
html += "<td><input type='text' placeholder='MAC Address' name='asset[" + n + "][mac_address]' id='mac-" + n + "' /></td>";
html += "<td><input type='text' placeholder='Name or Desc.' name='asset[" + n + "][description]' id='desc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][site]' class='chooseSite' id='site-" + n + "'>";
html += $("#site-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='E.G. Level 3 Utility Room' name='asset[" + n + "][location]' id='loc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][contact]' id='contact-" + n + "'><select></td>";
html += "</tr>";
return html;
}
It's more work up front, yet offers a lot more control of each part. And much easier to use later.

Related

My validation does not work on added rows and autonumbering

I have a function where i can add rows and autonumbering. The add rows works when you click the "add row" button, and auto numbering works when you press Ctrl+Enter key when there's 2 or more rows. My problem is, my validation does not work on my autonumbering.
For example: when I type manually the "1" on the textbox, it works.
But when I do my auto numbering, "Not good" does not appear on my 2nd
textbox.
Is there anything I missed? Any help will be appreciated.
//this is for adding rows
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
const inputs = document.querySelectorAll(".form");
document.querySelectorAll(".form")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You can call your event handler i.e : change whenever you change your input values by auto numbering . So , use $(this).trigger("change") where this refer to input where value is changed .
Demo Code :
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" name="entryCount" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form" type="number" /> <span class="email_result"></span></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
//this is for my validation
$(document).on('change', 'input[name*=lightBand]', function() {
var lightBand1 = $(this).val(); //get value
var selector = $(this) //save slector
selector.next('.email_result').html("") //empty previous error
if (lightBand1 != '') {
/*$.ajax({
url: "<?php echo base_url(); ?>participant/check_number_avalibility",
method: "POST",
data: {
lightBand1: lightBand1
},
success: function(data) {*/
selector.next('.email_result').html("NOT GOOD"); //use next here ..
/* }
});*/
}
});
// this is for autonumbering when ctrl+enter is pressed.
$(document).on('keyup', '.form', function(e) {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
//loop through all values...
$(".form").each(function(i) {
if (i !== 0) {
$(this).val(++value); //assign new value..
$(this).trigger("change") //call your change event to handle further...
}
})
}
})
Add a row and type any number at number textbox column and press ctrl+enter. You'll see the "Not good" is not working on added rows. It'll only work if you enter the number manually per row.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>Number</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="form" name="lightBand1" placeholder="" id="lightBand1" />
<span class="email_result"></span>
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>

I want to add new data from second table to main table

I want to add new data to the main table using the checkbox option, but the data added is not the same as the selected data. this is my code ...
<table border="1" id="table2">
<tr>
<td>Raka</td>
<input type="hidden" id="fname" value="Raka">
<td>Gilbert</td>
<input type="hidden" id="lname" value="Gilbert">
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<input type="hidden" id="fname" value="Achyar">
<td>Lucas</td>
<input type="hidden" id="lname" value="Lucas">
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<script>
$(document).on('click', '#Add', function() {
$("table").find('input[name="chk"]').each(function(){
if($(this).is(":checked")){
var fname = $('#fname').val();
var lname = $('#lname').val();
var newData = '<tr>'+
'<td>'+fname+'</td>'+
'<td>'+lname+'</td>'+
'<tr>';
$('table').append(newData);
}
});
})
</script>
You need to change your id="fname" to class="fname" and get the input value closest to checkbox. Currently you are getting data from the first inputs as they have the same id's.
function valueExists(value) {
if (!value) {
return true;
}
let exists = false;
$("#main-table").find('tr').each(function() {
let fname = $(this).find("td:nth-child(1)").text(),
lname = $(this).find("td:nth-child(2)").text();
const fullName = `${fname}${lname}`;
if (value.toLowerCase() === fullName.toLowerCase()) {
exists = true;
}
});
return exists;
}
$(document).on('click', '#add', function() {
$("table").find('input[name="chk"]').each(function(e) {
if ($(this).is(":checked")) {
var fname = $(this).parents('tr').find('.fname').val();
var lname = $(this).parents('tr').find('.lname').val();
if (valueExists(`${fname}${lname}`)) return;
var newData = '<tr>' +
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<tr>';
$('#main-table').append(newData);
}
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Main Table</h1>
<table class="table table-dark" border="1" id="main-table">
</table>
<hr>
<h1>Second table</h1>
<table border="1" id="table2">
<tr>
<td class="name">Raka</td>
<input type="hidden" class="fname" value="Raka">
<td class="last">Gilbert</td>
<input type="hidden" class="lname" value="Gilbert">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
<tr>
<td class="name">Achyar</td>
<input type="hidden" class="fname" value="Achyar">
<td class="last">Lucas</td>
<input type="hidden" class="lname" value="Lucas">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="add" name="button">Add</button>
Try this. I have used plain javascript
document.addEventListener("click", function() {
[...document.querySelectorAll("input[name='chk']")].forEach(data => {
console.log(data);
if (data.checked) {
const fname = document.getElementById("fname").value;
const lname = document.getElementById("lname").value;
const newData = `<tr><td>${ fname }</td><td>${ lname }</td</tr>`;
// "<tr>" + "<td>" + fname + "</td>" + "<td>" + lname + "</td>" + "<tr>";
document.getElementById("table2").innerHTML += newData;
}
});
});
Hope was useful. If any flaws please update
Here is a neater solution, using 2 tables as requested, without hidden inputs and a better use of 'tables' and 'trs' in jquery
$(function(){
$("#btnAdd").click(function(){
let table1 = $("#table1");
table2 = $("#table2");
$.each(table2.find('tr'), function(i, tr){
tr = $(tr);
let new_tr = $('<tr>');
if (tr.find("td input").is(":checked")) {
let fname = tr.find("td:nth-child(1)").html(),
lname = tr.find("td:nth-child(2)").html();
new_tr.append(
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<td><input type="checkbox" name="chk"></td>'
);
table1.append(new_tr)
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TABLE 1
<table border="1" id="table1">
</table>
<hr/>
TABLE 2
<table border="1" id="table2">
<tr>
<td>Raka</td>
<td>Gilbert</td>
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<td>Lucas</td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="btnAdd">Add</button>

Problems with HTML and Javascript dynamic table

I am facing problems in:
the function saveRow does not save the row. I get this error:
Uncaught TypeError: Cannot set property name of undefined at at saveRow at HTMLInputElement.onclick.
2) the deleteRow does not work. I get a similar error:
Uncaught TypeError: Cannot set property 'innerHTML' of null.
3) in the editRow, I fields to become editable, but with the default values as what was saved before. For example, the list is always A, B, C which is not what I want. I want the initial value of the list to be what was selected previously.
There should be something wrong I am doing. Here is the code:
HTML:
<html>
<head>
</head>
<body>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table-rows">
<tr>
<td><input type="text" id="name-text"></td>
<td>
<select name="levels-list" id="levels-list">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" value="Add Row" id="add-button"></td>
</tr>
</tbody>
</table>
</div>
<script src="get-text.js"></script>
</body>
</html>
The script:
var myArray = [{
"name": "aaa",
"level": "A"
}, {
"name": "bbb",
"level": "B"
}, {
"name": "ccc",
"level": "C"
}];
display();
function display() {
var length = myArray.length;
var htmlText = "";
for (var i = 0; i < length; i++) {
htmlText +=
"<tr id='row" + i + "'>\
<td>" + myArray[i].name + "</td>\
<td>" + myArray[i].level + "</td>\
<td>\
<input type='button' id='edit_button" + i + "' value='Edit' class='edit' onclick='editRow("+i+")'> \
<input type='button' id='save_button" + i + "' value='Save' class='save' onclick='save_row(" + i + ")'> \
<input type='button' value='Delete' class='delete' onclick='delete_row(" + i + ")'>\
</td>\
</tr>";
}//end loop
htmlText+=
"<tr>\
<td><input type='text' id='name-text'></td>\
<td>\
<select name='levels-list' id='levels-list'>\
<option value='A' id='option-1'>A</option>\
<option value='B' id='option-2'>B</option>\
<option value='C' id='option-3'>C</option>\
</select>\
</td>\
<td><input type='button' class='add' value='Add Row' id='add-button' ></td>\
</tr>";
document.getElementById("table-rows").innerHTML = htmlText;
}//end display
var addButton=document.getElementById("add-button");
addButton.addEventListener('click', addRow, false);
function addRow(){
event.preventDefault();
var newData= document.getElementById("name-text").value;
var newLevel = document.getElementById("levels-list").value;
var table = document.getElementById("data_table");
var tableLength = (table.rows.length)-1;
// console.log(tableLength);
var row = table.insertRow(tableLength).innerHTML=
"<tr id= 'row"+tableLength+"'>\
<td id='name-text"+tableLength+"'>"+newData+"</td>\
<td id='levels-list"+tableLength+"'>"+newLevel+"</td>\
<td><input type='button' id='edit-button"+tableLength+"' value='Edit' class='edit' onclick='editRow("+tableLength+")'> \
<input type='button' id='save-button"+tableLength+"' value='Save' class='save' onclick='saveRow("+tableLength+")'> \
<input type='button' id= 'delete-button"+tableLength+"' value='Delete' class='delete' onclick='deleteRow("+tableLength+")'>\
</td>\
</tr>";
document.getElementById("name-text").value="";
}//end addRow
function editRow(no)
{
document.getElementById("edit-button"+no).disabled=true;
//document.getElementById("save-button"+no).style.display="block";
var name=document.getElementById("name-text"+no);
var level=document.getElementById("levels-list"+no);
var nameData=name.innerHTML;
var levelData=level.innerHTML;
name.innerHTML="<input type='text' id='name_text"+no+"' value='"+nameData+"'>";
level.innerHTML='<select id="levels-list'+no+'">\
<option value="A" id="option-1">A</option>\
<option value="B" id="option-2">B</option>\
<option value="C" id="option-3">C</option>\
</select>' ;
document.getElementById("levels-list"+no).value = levelData;
}
function deleteRow(no) {
myArray.splice(no, 1);
document.getElementById("row"+no).innerHTML="";
//display();
} //end deleteRow
function saveRow(no)
{
myArray[no].name = document.getElementById("name-text"+no).value;
myArray[no].level = document.getElementById("levels-list"+no).value;
document.getElementById("row"+no).innerHTML =
"<tr id= 'row"+no+"'>\
<td id='name-text"+no+"'>"+myArray[no].name+"</td>\
<td id='levels-list"+no+"'>"+myArray[no].level+"</td>\
<td><input type='button' id='edit-button"+no+"' value='Edit' class='edit' onclick='editRow("+no+")'> \
<input type='button' value='Delete' class='delete' onclick='deleteRow("+no+")'>\
</td>\
</tr>";
}//end saveRow
I refactored a bit your code and created a new jsfiddle. You can refactor it more and more, and if possible to insert jQuery in your project, you will simply it a lot more.
So few notes:
1) Keep you model up to date with your UI changes. In the before sample you were manipulating HTML but you were not updating the array model
2) Try to keep your common code in functions, in order to avoid repetitions.
For example I moved the logic for creating row inside a function, and just calling that function every time that you need to create a new row (for displaying at the beginning and when clicking add row)
3) When you call your functions in the row, pass also the current HTML element. You can pass it in order to know which current HTML element has been clicked, so that you can easily manipulate that row.
4) Use two tbodies. One for the data and another one for the actions. It makes easier to distinct data from actions, avoiding to repeat every time also that row for actions
And few other things that you can check alone with the code.
You have to manage just the logic of disabling the buttons in the right operations, in order to avoid for example to click edit again when editing, but it would be a good exercise to do it yourself :)
Here the sample:
var myArray = [{
"name": "aaa",
"level": "A"
}, {
"name": "bbb",
"level": "B"
}, {
"name": "ccc",
"level": "C"
}];
function createDataRow(el, ind) {
var row = document.createElement('tr');
row.id = 'row-' + ind;
var cell1Content = `
<div class="name-content">${el.name}</div>
<input class="name-edit" type="text" id="name-text-${ind}" value="${el.name}" style="display:none;">
`;
var cell2Content = `
<div class="level-content">${el.level}</div>
<select class="level-edit" id="levels-list-${ind}" style="display:none;">
<option value="A">A</option>\
<option value="B">B</option>\
<option value="C">C</option>\
</select>
`;
var cell3Content = `
<input type="button" id='edit_button" + i + "' value="Edit" class="edit" onclick="editRow(this, ${ind})">
<input type="button" id='save_button" + i + "' value="Save" class="save" onclick="saveRow(this, ${ind})">
<input type="button" value="Delete" class="delete" onclick="deleteRow(this, ${ind})">
`;
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = cell1Content;
cell2.innerHTML = cell2Content;
cell3.innerHTML = cell3Content;
document.getElementById('table-data').appendChild(row);
}
function displayData() {
myArray.forEach(function(el, ind) {
createDataRow(el,ind);
});
}
function deleteRow(el, ind) {
el.parentElement.parentElement.parentElement.removeChild(el.parentElement.parentElement);
myArray.splice(ind, 1);
}
function addRow(){
event.preventDefault();
var newEl = {
"name": document.getElementById("name-text").value,
"level": document.getElementById("levels-list").value
};
myArray.push(newEl);
createDataRow(newEl, myArray.length - 1);
document.getElementById("name-text").value = '';
document.getElementById("levels-list").value = 'A';
}//end addRow
function editRow(el, ind)
{
var currentRow = el.parentElement.parentElement;
currentRow.cells[0].getElementsByClassName("name-content")[0].style.display = 'none';
currentRow.cells[0].getElementsByClassName("name-edit")[0].style.display = 'block';
currentRow.cells[1].getElementsByClassName("level-content")[0].style.display = 'none';
currentRow.cells[1].getElementsByClassName("level-edit")[0].value = myArray[ind].level;
currentRow.cells[1].getElementsByClassName("level-edit")[0].style.display = 'block';
}
//end deleteRow
function saveRow(el, ind)
{
var currentRow = el.parentElement.parentElement;
var nameContent = currentRow.cells[0].getElementsByClassName("name-content")[0];
var nameEdit = currentRow.cells[0].getElementsByClassName("name-edit")[0];
nameContent.innerHTML = nameEdit.value;
nameContent.style.display = 'block';
nameEdit.style.display = 'none';
var levelContent = currentRow.cells[1].getElementsByClassName("level-content")[0];
var levelEdit = currentRow.cells[1].getElementsByClassName("level-edit")[0];
levelContent.innerHTML = levelEdit.value;
levelContent.style.display = 'block';
levelEdit.style.display = 'none';
myArray[ind].name = nameEdit.value;
myArray[ind].level = levelEdit.value;
}//end saveRow
var addButton=document.getElementById("add-button");
addButton.addEventListener('click', addRow, false);
displayData();
<body>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table-data">
</tbody>
<tbody id="table-rows">
<tr>
<td><input type="text" id="name-text"></td>
<td>
<select name="levels-list" id="levels-list">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" value="Add Row" id="add-button"></td>
</tr>
</tbody>
</table>
</div>
</body>
And here the jsfiddle (this time saved :D ):
https://jsfiddle.net/u0865zaa/8/
I hope it helps. For any queries let me know.

Retrieving HTML Table Values

I created a table and borrowed a javascript function from http://www.fourfront.us/blog/store-html-table-data-to-javascript-array to retrieve the contents of the table the way I wanted to. It almost works, but for some reason I cannot access the value that the user inputs.
I have made a JS fiddle at http://jsfiddle.net/danielmdavies/4mu80x2L/1/
The code is also posted below. If I use "time_cutoff": $(tr).find('td:eq(2)').html() instead of "time_cutoff": $(tr).find('td:eq(2)').val(), I get the html code that is correct I believe.
This is the relevant html code:
<table id="cycler_table">
<tr>
<th>Cycle Step</th>
<th>Mode</th>
<th>Time Cutoff</th>
<th>Voltage Cutoff</th>
<th>Current Cuttoff</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='cyc_mode1'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff1' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff1' value='0'>
</td>
<td>
<input type='text' name='current_cutoff1' value='0'>
</td>
</tr>
<tr>
<td>2</td>
<td>
<select name='cyc_mode2'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff2' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff2' value='0'>
</td>
<td>
<input type='text' name='current_cutoff2' value='0'>
</td>
</tr>
<tr>
<td>3</td>
<td>
<select name='cyc_mode3'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff3' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff3' value='0'>
</td>
<td>
<input type='text' name='current_cutoff3' value='0'>
</td>
</tr>
<tr>
<td>4</td>
<td>
<select name='cyc_mode4'>
<option value='galvanostatic'>Galvanostatic</option>
<option value='Potentiostatic'>Potentiostatic</option>
<option name='rest'>Rest</option>
</td>
<td>
<input type='text' name='time_cutoff4' value='10'>
</td>
<td>
<input type='text' name='voltage_cutoff4' value='0'>
</td>
<td>
<input type='text' name='current_cutoff4' value='0'>
</td>
</tr>
</table>
<textarea id="tbTableValuesArray" name="tblValuesArray" rows="10"></textarea>
</div>
<p id="cyc_confirm">Waiting for Properties to be Confirmed
<button onclick="storeAndShowTableValues()">Send the Setup</button>
And the Javascript
$(document).ready(function () {
console.log("ready!");
storeAndShowTableValues();
});
function storeAndShowTableValues() {
var TableData;
TableData = storeTblValues();
$('#tbTableValuesArray').val('TableData = \n' + print_r(TableData));
}
function storeTblValues() {
var TableData = new Array();
$('#cycler_table tr').each(function (row, tr) {
TableData[row] = {
"cyc_mode": $(tr).find('td').eq(1).val(),
"time_cutoff": $(tr).find('td:eq(2)').val(),
"voltage_cutoff": $(tr).find('td:eq(3)').val(),
"current_cutoff": $(tr).find('td:eq(4)').val()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function convertArrayToJSON() {
var TableData;
TableData = $.toJSON(storeTblValues());
$('#tbConvertToJSON').val('JSON array: \n\n' + TableData.replace(/},/g, "},\n"));
}
function print_r(arr, level) {
var dumped_text = "";
if (!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for (var j = 0; j < level + 1; j++) level_padding += " ";
if (typeof (arr) == 'object') { //Array/Hashes/Objects
for (var item in arr) {
var value = arr[item];
if (typeof (value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' \n";
dumped_text += print_r(value, level + 1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
}
return dumped_text;
}
This is probably super easy but for whatever reason I can't work out how to make it give me the values.
Any help would be awesome.
Try something like this to get the values:
TableData[row] = {
"cyc_mode": $(tr).find('select').val(),
"time_cutoff": $(tr).find('input:eq(0)').val(),
"voltage_cutoff": $(tr).find('input:eq(1)').val(),
"current_cutoff": $(tr).find('input:eq(2)').val()
};
You need to find the actual input and select elements to get their values.
Or better:
var elem = $(tr);
TableData[row] = {
"cyc_mode": elem.find('select').val(),
"time_cutoff": elem.find('input:eq(0)').val(),
"voltage_cutoff": elem.find('input:eq(1)').val(),
"current_cutoff": elem.find('input:eq(2)').val()
};
Which avoids recreating the jquery object four times.

Remove/delete part of hidden field value on button click

I am trying to build a form where users can add a course using select boxes.
When a course is added, it creates a new table row displaying the course to the user and also adds the course prefix and number (e.g. MATH120) to a hidden form field value. Finally, it adds a delete button.
The delete button should remove the table row AND the hidden input value that corresponds to the course being deleted.
Here's my jsfiddle: http://jsfiddle.net/MtJF2/10/
My script is deleting the row just fine, but its not removing the input value correctly. It's not throwing any errors. Sometimes I've noticed that it will delete the zero in the correct value (e.g. MATH120, becomes MATH12,). Any ideas what might be causing this?
HTML:
<script type="text/javascript">
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function($course, value) {
return value.replace($course, '');
});
}
</script>
<table width="80%" align="center">
<tr id="add-required-course">
<td><input type="button" value="+ Add a Required Course" class="MC-big-button" onclick="$('#course-menu').slideToggle()" /></td>
</tr>
</table>
<input type="hidden" id="required-courses" name="required-courses" value="null" />
<table id="course-menu" width="80%" align="center">
<tr>
<td>Select the course prefix:</td>
<td><select id="1" name="course-prefix">
<option value="MATH">MATH</option>
<option value="BIOL">BIOL</option>
</select>
</td>
</tr>
<tr>
<td>Select the course number:</td>
<td><select id="2" name="course-num">
<option value="101">101</option>
<option value="120">120</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add this course" class="MC-big-button" id="save-course" />
</td>
</tr>
</table>
Javascript:
document.getElementById("save-course").onclick = buildCourse;
function buildCourse() {
var $coursePrefix = ($('#1').val());
var $courseNum = ($('#2').val());
var $course = $coursePrefix + $courseNum;
var $HTMLoutput = '<tr id="' + $course + '"><td>' + $course + '<input type="button" value="Delete" onclick="deleteCourse(\'' + $course + '\')" /></td></tr>';
var $VALUEoutput = ($('#required-courses').val());
if ($VALUEoutput == 'null') {
$VALUEoutput = $course + ',';
}
else {
$VALUEoutput = $VALUEoutput + $course + ',';
}
$('#course-menu').slideToggle();
$('#add-required-course').before($HTMLoutput);
$('#required-courses').val($VALUEoutput);
}
I found this question to be helpful, but I think my implementation is off.
You are replacing $course with a new value in the delete function at
$('#required-courses').val(function($course, value) {
// here it gets a new value which is wrong
Use it like this
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function(_, value) {
return value.replace($course, '');
});
}

Categories

Resources