I'm trying to achieve the change of Id But the code what I have is only having the code to change the name of the element can anyone please help to change the id of the element in the below give jquery code
Thanks in Advance.
Html View-source code is as follows
<div style="width:700px; padding:5px; background-color:white;">
<form action="/" method="post">
<a id="addNew" href="#">+</a> <a id="remove" href="#">-</a>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>UserName</th>
<th>Password</th>
<th>Service line</th>
<th>Track</th>
<th>subtrack</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="TemplateRow" style="border:1px solid black">
<td><input data-val="true" data-val-required="The Username field is required." id="z0__UserName" name="[0].UserName" type="text" value="Required" /></td>
<td><input data-val="true" data-val-required="The Password field is required." id="z0__Password" name="[0].Password" type="text" value="Required" /></td>
<td>
<select class="wrapper-dropdown Service_Line" id="z0__Service_Line" name="[0].Service_Line">
<option value="">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</td>
<td>
<select class="wrapper-dropdown Track" id="z0__Track" name="[0].Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td>
<select class="wrapper-dropdown Sub_Track" id="z0__Sub_Track" name="[0].Sub_Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td></td>
</tr>
</tbody>
</table>
<input type="submit" value="Save Bulk Data" />
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Iv10IHEfBVKvKHuuUa1dyFaBzngVKjKG3-va_WAZxz30jKahHLoMeCFM1qbmA9nPf01CYch9VobgyZOOv60VPsPJjlD4yUbH4F7TF0QrcJJTnMpj88n1Et9Ksa2i2y23CBEPqICCPoC18cdrY1Ral0" />
</form>
</div>
Jquery is as follows
$(document).ready(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone(true);
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
// If you have another Type then replace with default value
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
});
});
I have tried by changing the attr(name) to attr(id) after changing like that its not changing the name but even not changing the ids too...
For more reference the Html code is as follows::
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>UserName</th>
<th>Password</th>
<th>Service line</th>
<th>Track</th>
<th>subtrack</th>
<th></th>
</tr>
</thead>
<tbody>
#if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr id="TemplateRow" style="border:1px solid black">
<td>#Html.TextBoxFor(a => a[j].UserName)</td>
<td>#Html.TextBoxFor(a => a[j].Password)</td>
<td>
#if (ViewBag.ServiceLineList != null)
{
#Html.DropDownListFor(a => a[j].Service_Line, ViewBag.ServiceLineList as SelectList, "--Select--", new { #class = "wrapper-dropdown Service_Line" })
}
</td>
<td>
#Html.DropDownListFor(a => a[j].Track, new SelectList(" "), "--Select--", new { #class = "wrapper-dropdown Track" })
</td>
<td>
#Html.DropDownListFor(a => a[j].Sub_Track, new SelectList(" "), "--Select--", new { #class = "wrapper-dropdown Sub_Track" })
</td>
<td>
#if (j > 0)
{
Remove
}
</td>
</tr>
j++;
}
}
</tbody>
</table>
To create a unique id, we can keep a count of the rows added in the jQuery, and append this to the base name (e.g. UserName) to create a unique name and id. You say there will only be one row in the HTML, so we can start the count for our new rows at 1.
Every time the "Add New" button is clicked, the steps are (numbers match the comment numbers):
Initialise our variable to start the count
generate a unique id for the row, e.g. TemplateRow-1: var newId = "TemplateRow-" + rowcount;
Clone the row and pass in the id: $trLast.clone(true).prop({ id: newId});
generate the name and id for each input: get the input name, remove the [n] to get the base name (e.g. UserName), and use this to create the new name (e.g. [1].UserName) and id (e.g. z1__UserName).
Working snippet: I show the new id using console.log so you can see what is being added:
$(document).ready(function() {
/* 1. Initialise our variable to keep count of the rows added */
var rowcount = 1;
//Add new row
$("#addNew").click(function(e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
// 2. Create the new id with the row count
var newId = "TemplateRow-" + rowcount;
// 3. clone the row with our new id
var $trNew = $trLast.clone(true).prop({ id: newId });
// 4. rename each input and give an id
$.each($trNew.find(':input'), function(i, val) {
oldName = $(this).attr('name');
inputParts = oldName.split(".");
// set the name and id with the base name and rowcount
$(this).attr('name', '[' + rowcount + '].'+inputParts[1]);
$(this).attr('id', 'z'+rowcount+'__'+inputParts[1]);
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
rowcount++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>UserName</th>
<th>Password</th>
<th>Service line</th>
<th>Track</th>
<th>subtrack</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="TemplateRow" style="border:1px solid black">
<!-- <td><input type="text" name="username"></td>
<td><select name="serviceline"><option>1</option></select></td>
<td><input type="text" name="track"></td>
<td><input type="text" name="subtrack"></td> -->
<td><input data-val="true" data-val-required="The Username field is required." id="z0__UserName" name="[0].UserName" type="text" value="Required" /></td>
<td><input data-val="true" data-val-required="The Password field is required." id="z0__Password" name="[0].Password" type="text" value="Required" /></td>
<td>
<select class="wrapper-dropdown Service_Line" id="z0__Service_Line" name="[0].Service_Line">
<option value="">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</td>
<td>
<select class="wrapper-dropdown Track" id="z0__Track" name="[0].Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td>
<select class="wrapper-dropdown Sub_Track" id="z0__Sub_Track" name="[0].Sub_Track">
<option value="">--Select--</option>
<option> </option>
</select>
</td>
<td></td>
</tr>
</tbody>
</table>
<button id="addNew">Add New</button>
Related
I have table with default amount and pre-number select option on top. When select a new price will change in each row's input. Here I want the new number from select calculate the total price into the next row automatically.
$('select.set_price').change(function() {
var pset = $(this).data('pset');
$('td.' + pset).find('input.price').val($(this).val());
});
//calc
$('.price').keyup(function() {
var i_pay = $(this).closest('tr').find('#pay').text();
var i_bet = $(this).val();
var total = (i_pay * i_bet);
$(this).closest('tr').find('#pay').html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tr>
<th class="align-middle text-center">#</th>
<th>
<select class="form-select set_price" data-pset="p_3hi">
<option value="" disabled selected>Order</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</th>
<th>total</th>
</tr>
<tr>
<td class="align-middle text-center">1</td>
<td class="w-10 p_3hi"><input type="number" class="form-control price" name="price1" value="1" /></td>
<td class="align-middle text-center">
<p id="pay">900</p>
</td>
</tr>
<tr>
<td class="align-middle text-center">2</td>
<td class="w-10 p_3hi"><input type="number" class="form-control price" name="price2" value="1" /></td>
<td class="align-middle text-center">
<p id="pay">800</p>
</td>
</tr>
</table>
What I expect is when I select 5. The #1 row's total would be 5*900=4500 and the #2 would be 5*800=4000. Please find the fiddle here : https://jsfiddle.net/w56940ez/
First change $('.price').keyup(function(){}); to $('.price').change(function(){}); or you won't be able to change total value using arrows. If you don't want to use arrows you can keep keyup event.
To automatically change the value of the total column you just need to use trigger("change") on your ìnput elements.
If you want the base values to always be 800 and 900, you should use a data-attributes (data-first-value) which will keep this value and which will be used during the calculation.
Identifiers must be unique like #j08691 said. So you have basically two solutions:
use a pay class instead of a pay id. You juste need to replace id="pay" with class="pay" and #pay with .pay
use two identifiers. You need to add another data-attributes (data-id) and use it to get the input you want.
$('select.set_price').change(function() {
var pset = $(this).data('pset');
input_elements = $('td.' + pset).find('input.price');
input_elements.val($(this).val());
input_elements.trigger("change");
});
//calc
$('.price').change(function() {
/*
USING A CLASS FOR BOTH
var i_pay = $(this).closest('tr').find('.pay').attr("data-first-val");
var i_bet = $(this).val();
var total = (i_pay * i_bet);
$(this).closest('tr').find('.pay').html(total);
*/
var i_pay = $("#"+$(this).attr("data-id")).attr("data-first-val");
var i_bet = $(this).val();
var total = (i_pay * i_bet);
$("#"+$(this).attr("data-id")).html(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tr>
<th class="align-middle text-center">#</th>
<th>
<select class="form-select set_price" data-pset="p_3hi">
<option value="" disabled selected>Order</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</th>
<th>total</th>
</tr>
<tr>
<td class="align-middle text-center">1</td>
<td class="w-10 p_3hi">
<input type="number" class="form-control price" name="price1" value="1" data-id="pay_1" />
</td>
<td class="align-middle text-center">
<p id="pay_1" data-first-val="900">900</p>
<!--<p class="pay" data-first-val="900">900</p>-->
</td>
</tr>
<tr>
<td class="align-middle text-center">2</td>
<td class="w-10 p_3hi"><input type="number" class="form-control price" name="price2" value="1" data-id="pay_2"/></td>
<td class="align-middle text-center">
<p id="pay_2" data-first-val="800">800</p>
<!--<p class="pay" data-first-val="800">800</p>-->
</td>
</tr>
</table>
User can enter values in some or all the rows present in the html table and click on the submit button. If a value is present in the row (if at least one column field value is entered) and the submit button is clicked, I want to get all the details as a json array.
Working sample demo : http://jsfiddle.net/Crw2C/173/
In the working demo above, when the user clicks on the convert button, the data from the html table is shown as a json array. I tried a similar implementation in my demo as shown in the code below but it is not working as expected.
My sample demo code which is not working as expected: http://plnkr.co/edit/FODEJ1BnhPLGHoH9kjO5?p=preview
Sample html code:
<table id="productTable" border="1">
<tr>
<th>Order ID</th>
<th>Product1</th>
<th>Description</th>
<th>Product2</th>
<th>Comments</th>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
.......
Sample js code:
$('#productTable th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).html();
});
array.push(arrayItem);
});
Note: With my code above, the entire html element is retrieved and stored as json array but I only want the value. Any sample code would be appreciated as I tried to search and tried in different ways but was unable to succeed. The sample code I tried I also shared in the demo link above, which is not working. Thanks.
You are selecting the whole <td>...</td> instead of this select html input or select elements.
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index) {
arrayItem[headers[index]] = $(this).val();
});
array.push(arrayItem);
});
Check below snippet.
function populateSelect() {
var ids = [{"pid":"laptop","des":"laptop"},{"pid":"Mobile","des":"Mobile"},{"pid":"IPAD mini.","des":"IPAD mini."}]
var productDropdown1 = $(".product1");
var productDropdown2 = $(".product2");
$.each(ids, function(index,value) {
$("<option />").text(value.des).val(value.pid).appendTo(productDropdown1);
$("<option />").text(value.des).val(value.pid).appendTo(productDropdown2);
});
$("select").change(function() {
var row = $(this).closest("tr");
var product1_drop = $('.product1',row).val();
var product2_drop = $('.product2',row).val();
var descValue = $('input[name="description"]',row).val();
if( product1_drop && product2_drop)
validate(product1_drop,product2_drop, descValue);
});
$('input[name="description"]').on('input', function(e){
var row = $(this).closest("tr");
var product1_drop = $('.product1',row).val();
var product2_drop = $('.product2',row).val();
console.log("-inut -product1_drop----- " + product1_drop);
if( product1_drop && product2_drop)
validate(product1_drop,product2_drop, $(this).val());
});
}
function validate(prod1, prod2, desc){
if(desc && prod1 === prod2 ){
alert('Product1 and Product2 cannot have same value');
}
}
function submitData(){
alert("submit");
var array = [];
var headers = [];
$('#productTable th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index) {
arrayItem[headers[index]] = $(this).val();
});
array.push(arrayItem);
});
alert(JSON.stringify(array));
}
$(document).ready(function(){
populateSelect();
// $('#productTable tbody tr:gt(0) :input').prop('disabled',true)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="productTable" border="1">
<tr>
<th>Order ID</th>
<th>Product1</th>
<th>Description</th>
<th>Product2</th>
<th>Comments</th>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
</table> <br>
<input type="submit" value="submit" onclick="submitData()">
In your column loop, you don't want to assign the entire html of the cell. Rather, you need just the value of the select box that is contained in the cell.
In other words: change $(item).html() in your loop on the 'td's to $(item).find('select').val().
You should change this part of code
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).val();
});
array.push(arrayItem);
});
You are selecting the <td> html, but what you really want is the input and select values.
<script type="text/javascript" src = "diabetestool.js"> </script>
<meta charset="utf-8"/>
</head>
<body>
<form id = "test2" name = "test2">
<table cellpadding="2" width="20%" bgcolor="red"
align="center"
cellspacing="2"
<tr>
<td colspan =2>
<center> <font size = 4>FORM TO FILL IN </font></center>
</td>
</tr>
<td> Title </td>
<td> <select Name="Title">
<option value= "-1 selected"> select...</option>
<option value= "Mr"> Mr </option>
<option value= "Mrs"> Mrs </option>
<option value= "Miss"> Miss </option>
<option value= "Ms"> Ms </option>
<option value= "Master"> Master</option>
</select></td>
</tr>
<tr>
<td>First Name</td>
<td><input type ="text" name= "firstName" id ="firstName" size ="30"> </td>
</tr>
<tr>
<td> Last Name</td>
<td> <input type ="text" name ="lastName" id = "lastName" size ="30"> </td>
</tr>
<tr>
<td> Health Authority Number</td>
<td> <input type ="text" name ="healthNumber" id = "healthNumber" size ="30"> </td>
</tr>
<tr>
<td> Email</td>
<td> <input type ="text" name ="email" id = "email" size ="30"> </td>
</tr>
<tr>
<td> Telephone Number</td>
<td> <input type ="text" name ="telephoneNumber" id = "telephoneNumber" size ="30"> </td>
</tr>
<tr>
<td colspan ="2"> <input type="submit" value="submit form" onsubmit="return validate()"; </td>
</tr>
</table>
</form>
</body>
</html>
this is my code to create the code for my contact form to be filled
there are a selection of options
function validate ()
{
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var Title = document.getElementById("Title").value;
var healthNumber = parseInt(document,getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
if(firstName!="" && lastName!= "" && Title!="" && email !="")
{
if(email.match(validEmail))
{
alert("All Values Validated");
return true;
}
else
{
alert("Enter a valid Email");
return false;
}
}
else
{
alert("All Fields are required");
return false;
}
}
this is just a randomly created js validation code just to test to see if the validating process works with my code and then i will change it to actually do the proper validation i want
the issue is that with my html page for my contact form after submitting, it just refreshes that page i have tried different things but not able to find a solution
You code has lot of syntax error. I fix syntax error. Here is the js fiddle: https://jsfiddle.net/0ngs96n0/13/
Use onsubmit in form tag something like that :
<form id = "test2" name = "test2" onsubmit="return validate(event);">
and In JS:
function validate (e){
e.preventDefault();
.................
.................
.................
.................
.................
}
it will stop the form from refreshing.
parseInt(document,getElementById("healthNumber").value);
Check the above line there is a , comma instead of. Dot . In document.getElementById("healthNumber").value;
Another one is close table element in html part, it will be solved
Thanks
You have some mistakes in your code
such as calling the function in HTML
And "parseInt "function in JS
HTML :
<html>
<head>
<script type="text/javascript" src = "diabetestool.js"> </script>
<meta charset="utf-8"/>
</head>
<body>
<form id = "test2" name = "test2" onsubmit="validate()">
<table cellpadding="2" width="20%" bgcolor="red"
align="center"
cellspacing="2"
<tr>
<td colspan =2>
<center> <font size = 4>FORM TO FILL IN </font></center>
</td>
</tr>
<td> Title </td>
<td> <select Name="Title" id="Title">
<option value= "-1 selected"> select...</option>
<option value= "Mr"> Mr </option>
<option value= "Mrs"> Mrs </option>
<option value= "Miss"> Miss </option>
<option value= "Ms"> Ms </option>
<option value= "Master"> Master</option>
</select></td>
</tr>
<tr>
<td>First Name</td>
<td><input type ="text" name= "firstName" id ="firstName" size ="30"> </td>
</tr>
<tr>
<td> Last Name</td>
<td> <input type ="text" name ="lastName" id = "lastName" size ="30"> </td>
</tr>
<tr>
<td> Health Authority Number</td>
<td> <input type ="text" name ="healthNumber" id = "healthNumber" size ="30"> </td>
</tr>
<tr>
<td> Email</td>
<td> <input type ="text" name ="email" id = "email" size ="30"> </td>
</tr>
<tr>
<td> Telephone Number</td>
<td> <input type ="text" name ="telephoneNumber" id = "telephoneNumber" size ="30"> </td>
</tr>
<tr>
<td colspan ="2"> <input type="submit" value="submit form" >
</td>
</tr>
</table>
</form>
</body>
</html>
javascript:
// Declare all the iables here
var firstName;
var lastName;
var Title ;
var healthNumber;
var email ;
validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
function validate ()
{
firstName = document.getElementById("firstName").value;
lastName = document.getElementById("lastName").value;
Title = document.getElementById("Title").value;
// healthNumber = parseInt(document,getElementById("healthNumber").value);
email = document.getElementById("email").value;
validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
if(firstName!="" && lastName!= "" && Title!="" && email !="")
{
if(email.match(validEmail))
{
alert("All Values Validated");
}
else
{
alert("Enter a valid Email");
}
}
else
{
alert("All Fields are required");
}
}
I have created a table with multiple columns and written a jquery javascript that duplicates or clones the the last row of the table. However when it clones the last row it also gives each column the same name and id as the previous row.
jsp code:
<div id="invTruck" class="invTruck">
<table id="tbl_invTruck" width="100%" border="0">
<tbody>
<tr>
<td width="15%" style="display:none;"><center>Work Order Id</center></td>
<td width="17%"><center>Truck Type</center></td>
<td width="17%"><center>Licences Plate #</center></td>
<td width="17%"><center>Driver ID</center></td>
<td width="17%"><center>Max Haulage Weight</center></td>
<td width="17%"><center>Job Number</center></td>
</tr>
<tr>
<td style="display:none;"><input name="wInv_work_Id" type="text"></td>
<td><select id="invTru_Type" name="invTru_Type" onchange="getTruckPlates(this.value)">
<option disabled selected hidden value="">Select A Truck Type</option>
<%while(rsinvTru1.next()){%>
<option><%=rsinvTru1.getString(1)%></option>
<%}%>
</select>
</td>
<td><select id="invTru_LicensePlateNo" name="invTru_LicensePlateNo" required>
<option disabled selected hidden value="">Select A Truck</option>
</select></td>
<td><input name="driver_emp_Id" type="text"></td>
<td><input name="invTru_MaxHw" type="text"></td>
<td><input name="" type="text"></td>
</tr>
</tbody>
</table>
<table width="100%" height="50%" border="0">
<tr>
<td width="50%"><input class="buttonCreateInv" id="btn_AddTruck" type="button" value="Add A Truck"></td>
<td width="50%"><input class="buttonCreateInv" name="btn_RemoveTruck" type="button" value="Remove A Truck"></td>
</tr>
</table>
</div>
JQuery Javascript:
$(document).ready(function(){
$("#btn_AddTruck").click(function(){
var $tableBody = $('#tbl_invTruck').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
$trLast.after($trNew);
});
});
The expected output i would like is for the duplicated table row
where id in id1 is the orignal tables td id and 1 is appended to it.
and that if i was to add another row to the table
where id in id2 is the orignal tables td id and 2 is appended to it.
Try next one:
$(document).ready(function () {
$("#btn_AddTruck").click(function () {
var $tableBody = $('#tbl_invTruck').find("tbody"),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
// Find by attribute 'id'
$trNew.find('[id]').each(function () {
var num = this.id.replace(/\D/g, '');
if (!num) {
num = 0;
}
// Remove numbers by first regexp
this.id = this.id.replace(/\d/g, '')
// increment number
+ (1 + parseInt(num, 10));
});
$trLast.after($trNew);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="invTruck" class="invTruck">
<table id="tbl_invTruck" width="100%" border="0">
<tbody>
<tr>
<td width="15%" style="display:none;"><center>Work Order Id</center></td>
<td width="17%"><center>Truck Type</center></td>
<td width="17%"><center>Licences Plate #</center></td>
<td width="17%"><center>Driver ID</center></td>
<td width="17%"><center>Max Haulage Weight</center></td>
<td width="17%"><center>Job Number</center></td>
</tr>
<tr>
<td style="display:none;"><input name="wInv_work_Id" type="text"></td>
<td><select id="invTru_Type" name="invTru_Type" onchange="getTruckPlates(this.value)">
<option disabled selected hidden value="">Select A Truck Type</option>
<!-- %while(rsinvTru1.next()){%>
<option><%=rsinvTru1.getString(1)%></option>
<%}% -->
</select>
</td>
<td><select id="invTru_LicensePlateNo" name="invTru_LicensePlateNo" required>
<option disabled selected hidden value="">Select A Truck</option>
</select></td>
<td><input name="driver_emp_Id" type="text"></td>
<td><input name="invTru_MaxHw" type="text"></td>
<td><input name="" type="text"></td>
</tr>
</tbody>
</table>
<table width="100%" height="50%" border="0">
<tr>
<td width="50%"><input class="buttonCreateInv" id="btn_AddTruck" type="button" value="Add A Truck"></td>
<td width="50%"><input class="buttonCreateInv" name="btn_RemoveTruck" type="button" value="Remove A Truck"></td>
</tr>
</table>
</div>
I have 3 problems with this javascript.
User cant add more item if already limit.
Example max item 3, and value item is ab,bc,cd, how I can take value if using javascript (after all done user will be press submit then all data from table will be post (i cant take data from javascript))?
what I want build is like this : Example 2 item
|Total Item | Name Item | Delete |
| 1 | ABC | DELETE(BUTTON) |
| 2 | CDE | DELETE(BUTTON) |
This is html code, example max item is 6
<table border="0">
<tr>
<td>
Title
</td>
<td>
:
</td>
<td>
<input type="text" name="title" value="" placeholder="Input Title">
</td>
</tr>
<tr>
<td>
Show Item
</td>
<td>
:
</td>
<td>
<select name="max" id="maxitem">
<?php
for($i=1; $i<=6; $i++)
{
echo "<option value=".$i.">".$i." Item</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>
Product
</td>
<td>
:
</td>
<td>
<input type="text" name="product" id="product" value="" placeholder="Add Product">
</td>
<td>
<input type="button" id="ADD" value="Add Item">
</td>
</tr>
</table>
<table border="1" id="tblname">
<thead>
<tr>
<td>
Total Item
</td>
<td>
Name Item
</td>
<td>
DELETE
</td>
<tr>
</thead>
<tbody>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="SUBMIT">
and this is javascript code :
$(document).ready(function(){
var item = 1;
$('#ADD').click(function(){
var maxitem = parseInt($("#maxitem").val()); //from max item in html
if($('#product').val()){ // check input product
if( item <= maxitem )
{
$('#tblname tbody').append($("#tblname tbody tr:last").clone());
$('#tblname tbody tr:last td:first').val(item);
$('#tblname tbody tr:last td:first').html($('#product').val());
$('#tblname tbody tr:last td:first').append("<input type='button' class='DEL' value='DELETE'>");
var item +=1;
}
else
{
alert ("Max Limit !!!");
}
}else{alert('Enter Text');}
});
// for delete row
$('body').on('click', 'input.DEL', function() {
$(this).parents('tr').remove();
});
});
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
var item = 1;
$('#ADD').click(function(){
var maxitem = parseInt($("#maxitem").val(), 10); //from max item in html
var iCount = 0;
if($('#product').val()){ // check input product
if( item <= maxitem )
{
iCount = $('#tblname tbody tr').length + 1;
szTr = "<tr><td>";
szTr = szTr + iCount + "</td>";
szTr = szTr + "<td>" +$('#product').val() +"</td>";
szTr = szTr + "<td><input type='button' class='DEL' value='DELETE'></td>";
szTr = szTr + "</tr>";
$('#tblname tbody').append(szTr);
item = item+1;
}
else
{
alert ("Max Limit !!!");
}
}else{alert('Enter Text');}
});
// for delete row
$('body').on('click', 'input.DEL', function() {
$(this).parents('tr').remove();
});
$('#get_data').click(function () {
$('#tblname tbody tr').each(function () {
alert($(this).find('td:eq(1)').text());
});
});
});
</script>
</head>
<body>
<table border="0">
<tr>
<td>
Title
</td>
<td>
:
</td>
<td>
<input type="text" name="title" value="" placeholder="Input Title">
</td>
</tr>
<tr>
<td>
Show Item
</td>
<td>
:
</td>
<td>
<select name="max" id="maxitem">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4">Item4</option>
<option value="5">Item5</option>
<option value="6">Item6</option>
</select>
</td>
</tr>
<tr>
<td>
Product
</td>
<td>
:
</td>
<td>
<input type="text" name="product" id="product" value="" placeholder="Add Product">
</td>
<td>
<input type="button" id="ADD" value="Add Item">
</td>
</tr>
</table>
<table border="1" id="tblname">
<thead>
<tr>
<td>
Total Item
</td>
<td>
Name Item
</td>
<td>
DELETE
</td>
<tr>
</thead>
<tbody>
</tbody>
</table>
<input type="button" value="Get Data" id="get_data">
<input type="submit" value="SUBMIT">
</body>
</html>
See if this is what you are trying to do, your description is hard to decipher:
DEMO: https://jsfiddle.net/d8kpsnxx/
<table border="0">
<tr>
<td>Title</td>
<td>:</td>
<td><input type="text" name="title" value="" placeholder="Input Title"></td>
</tr>
<tr>
<td>Show Item</td>
<td>:</td>
<td>
<select name="max" id="maxitem">
<option value=1>1 Item</option>
<option value=2>2 Item</option>
<option value=3>3 Item</option>
<option value=4>4 Item</option>
<option value=5>5 Item</option>
<option value=6>6 Item</option>
</select>
</td>
</tr>
<tr>
<td>Product</td>
<td>:</td>
<td><input type="text" name="product" id="product" value="" placeholder="Add Product"></td>
<td><input type="button" id="ADD" value="Add Item"></td>
</tr>
</table>
<table border="1" id="tblname">
<thead>
<tr>
<td>
Total Item
</td>
<td>
Name Item
</td>
<td>
DELETE
</td>
<tr>
</thead>
<tbody id="cracker">
</tbody>
</table>
<input id="submitall" type="submit" value="SUBMIT">
<script>
$(document).ready(function() {
var isAllowed = 3;
var isSet = 0;
$(this).on('click',"#ADD",function(e) {
// Prevent submission
e.preventDefault();
// Set all the value object
var drop = $("select[name=max]");
var title = $("input[name=title]");
var prod = $("input[name=product]");
// Append the table
$("#cracker").append('<tr><td>'+title.val()+': '+prod.val()+'</td><td>'+drop.val()+'</td><td><input type="submit" class="dMade" name="'+drop.val()+'" value="DELETE" /></td></tr>');
// Clear all the values to start over
drop.val("");
title.val("");
prod.val("");
// Auto increment
isSet++;
// Turn off/on submit buttons
restFormOpts();
});
$(this).on('click',".dMade",function(e) {
var traversed = $(this).parents("tr");
traversed.remove();
isSet--;
restFormOpts();
});
function restFormOpts()
{
if(isSet === isAllowed) {
$("#ADD").attr("disabled",true);
$("#submitall").attr("disabled",false);
}
else {
$("#ADD").attr("disabled",false);
$("#submitall").attr("disabled",true);
}
}
});
</script>