Add and remove row dynamically from jquery from given content - javascript

I tried follows code from refer various site but stuck on add/remove dynamic row.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<form>
Name: <input type="text" id="name" value=""></input></br>
Gender : <input type="radio" name="sex" value="male">M &nbsp
<input type="radio" name="sex" value="female">F</br>
Resident: <input type="checkbox" name="resident" value="Yes">Yes &nbsp
<input type="checkbox" name="resident" value="No">No
</br>
Edu : <select name="selectbox" id="selectbox">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</br>
<input type="submit" id="button" value="Submit">
</form>
<table width="400" border="1" id="empinfo" cellpadding="2" cellspacing="2">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Resident</th>
<th>Edu</th>
<th>Action</th>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#button").click(function(){
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident= $('input:checkbox:checked').val();
});
});
</script>
</html>
I created one html form and posting data, I have to show submitted
information in table on same page and in action column need to show edit and delete button. if I press edit then information need to open on same page and when I submit it will affect on table. If I press delete button then rows need to remove. All this operation only by using Javascript and Jquery.
Please help me to solve this problem.

Here is the modified code:
$(document).ready(function() {
$("#button").click(function(e){
e.preventDefault();
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident= $('input:checkbox:checked').val();
var education = $("#selectbox").val();
var content = '<td>' + name + '</td>' +
'<td>' + gender + '</td>' +
'<td>' + resident + '</td>' +
'<td>' + education + '</td>' +
'<td><button class="edit-row">Edit</button><button class="delete-row">Delete</button></td>';
if ($(this).hasClass('save-edit')) {
$('.editing').html(content);
$("#button").removeClass('save-edit').val('Submit');
} else {
var rowContent = '<tr class="employee-row">' + content + '</tr>';
$('#empinfo').append(rowContent);
}
});
$('body').on('click', '.edit-row', function (e) {
$('.editing').removeClass('editing');
$(this).closest('.employee-row').addClass('editing');
$("#button").addClass('save-edit').val('Save');
});
$('body').on('click', '.delete-row', function (e) {
$(this).closest('.employee-row').remove();
});
});
and jsfiddle:
https://jsfiddle.net/s6wty7vv/2/

This is a working solution:
HTML: Same as what you have updated.
Javascript:
$(document).ready(function() {
$("#button").click(function(e){
e.preventDefault();
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident= $('input:checkbox:checked').val();
var education = $("#selectbox").val();
var rowContent = '<tr>' +
'<td>' + name + '</td>' +
'<td>' + gender + '</td>' +
'<td>' + resident + '</td>' +
'<td>' + education + '</td>' +
'<td></td>' +
'</tr>';
$('#empinfo').append(rowContent);
});
});
See the working code: https://jsfiddle.net/s6wty7vv/1/
This will however not persist unless you remove the prevent default and add a form submit and tie it up to a backend, or retain the prevent default and add an ajax call to persist this data in the backend as required.

I think this is what you're looking for:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<form>
Name:
<input type="text" id="name" value=""></input>
</br>
Gender :
<input type="radio" name="sex" value="male">M &nbsp
<input type="radio" name="sex" value="female">F</br>
Resident:
<input type="checkbox" name="resident" value="Yes">Yes &nbsp
<input type="checkbox" name="resident" value="No">No
</br>
Edu :
<select name="selectbox" id="selectbox">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</br>
<input type="submit" id="button" value="Submit">
</form>
<table width="400" border="1" id="empinfo" cellpadding="2" cellspacing="2">
<tr>
<th>Name</th>
<th>Gender</th>
<th>Resident</th>
<th>Edu</th>
<th>Action</th>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident = $('input:checkbox:checked').val();
var edu = $('#selectbox').val();
var rowToAdd = $('<tr>');
rowToAdd.html('<td></td><td></td><td></td><td></td><td></td>');
rowToAdd.find('td:nth-child(1)').html(name);
rowToAdd.find('td:nth-child(2)').html(gender);
rowToAdd.find('td:nth-child(3)').html(resident);
rowToAdd.find('td:nth-child(4)').html(edu);
$('#empinfo').append(rowToAdd);
});
});
</script>
</html>

Related

User data only appears for a second in the data table when I hit submit button, which is enabled by checking a checkbox

I've recently added the disabling/enabling submit button function. However, I encounter a new problem. the user data disappears super quickly after i hit the submit button. I want it to be stored in the table data. I would really appreciate any guidance on this!
Here's my HTML code for the user data:
<div id="data">
<form id="breakies">
<p> Breakfast Options</p>
<div>
<input type="checkbox" id="protein-oatmeal" name= "breakies" value="Protein Oatmeal">
<label for="protein-oatmeal">Protein Oatmeal</label>
</div>
<div>
<input type="checkbox" id="toast-and-eggs" name= "breakies" value="Toast and Eggs">
<label for="toast-and-eggs">Toast and Eggs</label>
</div>
<div>
<input type="checkbox" id="gyp" name= "breakies" value="Greek Yogurt Parfait">
<label for="gyp">Greek Yogurt Parfait</label>
</div>
<div>
<input type="checkbox" id="pw" name= "breakies" value="Protein Waffles">
<label for="pw">Protein Waffles</label>
</div>
<br><input type="checkbox" name="checkme" id="checkBox">
<label for="checkBox"> I have selected at least 4 options for each meal</label>
<br><input type="submit" id="submitButton" name="submit" onclick= "addData()">
</form>
Here's my HTML code for the table data:
<div id="tab">
<table id="list" cellspacing="0px" cellpadding="20px" text-align="center">
<thead>
<tr>
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
<td>Thursday</td>
<td>Friday</td>
<td>Saturday</td>
<td>Sunday</td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
This is the JavaScript/JQuery part:
<
script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
$('#submitButton').attr('disabled', 'disabled');
$('#checkBox').click(function() {
if ($(this).is(':checked')) {
$('#submitButton').removeAttr('disabled');
} else {
$('#submitButton').attr('disabled', 'disabled');
}
});
});
</script>
<script>
function addData() {
var rows = "";
var a = document.getElementById("protein-oatmeal").value;
var b = document.getElementById("toast-and-eggs").value;
var c = document.getElementById("gyp").value;
var d = document.getElementById("pw").value;
rows += "<td>" + a + "</td><td>" + b + "</td><td>" + c + "</td><td>" + d + "</td><td>"+ b + "</td><td>"+ c +"</td><td>"+ a + "</td>";
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
</script>
You need to get event when form submit and then use preventDefault()
$(function() {
$('#breakies').submit(function(event) {
event.preventDefault();
// do something
});
$('#submitButton').attr('disabled', 'disabled');
$('#checkBox').click(function() {
if ($(this).is(':checked')) {
$('#submitButton').removeAttr('disabled');
} else {
$('#submitButton').attr('disabled', 'disabled');
}
});
});
function addData() {
var rows = "";
var a = document.getElementById("protein-oatmeal").value;
var b = document.getElementById("toast-and-eggs").value;
var c = document.getElementById("gyp").value;
var d = document.getElementById("pw").value;
rows += "<td>" + a + "</td><td>" + b + "</td><td>" + c + "</td><td>" + d + "</td><td>"+ b + "</td><td>"+ c +"</td><td>"+ a + "</td>";
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="data">
<form id="breakies">
<p> Breakfast Options</p>
<div>
<input type="checkbox" id="protein-oatmeal" name= "breakies" value="Protein Oatmeal">
<label for="protein-oatmeal">Protein Oatmeal</label>
</div>
<div>
<input type="checkbox" id="toast-and-eggs" name= "breakies" value="Toast and Eggs">
<label for="toast-and-eggs">Toast and Eggs</label>
</div>
<div>
<input type="checkbox" id="gyp" name= "breakies" value="Greek Yogurt Parfait">
<label for="gyp">Greek Yogurt Parfait</label>
</div>
<div>
<input type="checkbox" id="pw" name= "breakies" value="Protein Waffles">
<label for="pw">Protein Waffles</label>
</div>
<br><input type="checkbox" name="checkme" id="checkBox">
<label for="checkBox"> I have selected at least 4 options for each meal</label>
<br><input type="submit" id="submitButton" name="submit" onclick= "addData()">
</form>
<div id="tab">
<table id="list" cellspacing="0px" cellpadding="20px" text-align="center">
<thead>
<tr>
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
<td>Thursday</td>
<td>Friday</td>
<td>Saturday</td>
<td>Sunday</td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>

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>

Issue in populating dynamic data to dropdown column using ajax

I am trying to populate and append a column For Example:Id with the below column data dynamically using jquery and ajax.
The data will be populated via rest webservice. But the data is not getting populated.
The code snippet is as below.
The code which is pasted may not work properly due to lack of dynamic data from a webservice.
So the issue lies in populating/appending the data into the column in the header.
$(document).ready(function() {
// DO GET
$.ajax({
type: "GET",
url: "api/customer/all",
success: function(result) {
$.each(result, function(i, customer) {
var customerRow = "<tr><td><input type='checkbox' name='record'></td><td>" +
customer.id + "</td><td>" +
customer.name.toUpperCase() + "</td><td>" +
customer.age + "</td><td>" +
customer.address.street + "</td><td>" +
customer.address.postcode + "</td></tr>";
$('#IdProof').append('<option value="' + customer.id + '">' + customer.age + '</option>');
$('#customerTable tbody').append(customerRow);
});
},
error: function(e) {
alert("ERROR: ", e);
console.log("ERROR: ", e);
}
});
$('#select-all').click(function(event) {
if (this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
$('#reboot').click(function() {
$('#customerTable').find('tr').each(function(i) {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var $tds = $(this).find('td'),
Id = $tds.eq(1).text(),
name = $tds.eq(2).text(),
age = $tds.eq(3).text();
// do something with productId, product, Quantity
alert('Row ' + (i + 1) + ':\nId: ' + Id +
'\nname: ' + name +
'\nage: ' + age);
}
});
});
$(function() {
$("#inputFilter").on("keyup", function() {
$("#select-all").hide();
var value = $(this).val().toLowerCase();
$("#customerTable > tbody > tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
})
<!DOCTYPE HTML>
<html>
<head>
<title>Spring Boot - DELETE-UPDATE AJAX Example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/jqueryScript.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="#{/css/main.css}" />
</head>
<body>
<div class="container">
<h2>Filter Table</h2>
<div class="row col-md-7 ">
<div style="margin-bottom: 20px; padding: 10px; background-color: green; color: white;">
<p>
Type some text to search the table for <strong>Id</strong>, <strong>Name</strong>,
<strong>Age</strong>, <strong>Street</strong>, <strong>PostCode</strong>:
</p>
<input class="form-control" id="inputFilter" type="text" placeholder="Search.." />
</div>
<table id="customerTable" class="table table-bordered table-hover table-responsive ">
<thead>
<tr>
<th><input type="checkbox" name="select-all" id="select-all" /></th>
<th>
<select name="IdProof" id="id" class="form-control">
<option value="">Id</option>
</select>
</th>
<th>
<select name="Name" id="name" class="form-control">
<option value="">Name</option>
</select>
</th>
<th>
<select name="Age" id="age" class="form-control">
<option value="">Age</option>
</select>
</th>
<th>
<select name="Street" id="street" class="form-control">
<option value="">Street</option>
</select>
</th>
<th>
<select name="Postcode" id="postcode" class="form-control">
<option value="">Postcode</option>
</select>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button id="reboot">Reboot</button>
<button id="logs">Logs</button>
</div>
</div>
</body>
</html>
Try to fix your code like this. I think problem is in your concatination. Make all the concatenations like these
var customerRow = "<tr><td><input type='checkbox' name='record'></td><td>" +
customer.id + "'</td><td>'" +
customer.name.toUpperCase() + "'</td><td>'" +
customer.age + "'</td><td>'" +
customer.address.street + "'</td><td>'" +
customer.address.postcode + "'</td></tr>'";

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

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.

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