remove table tr when click btn jquery - javascript

I am creating a add and remove function in jQuery when minus btn [remove_button] will click. but it not working.
I am appending the td when which plus btn [add_button] it works but how I achieve for deletion method.
My code is below, I am fresh in jQuery and hoping if I am wrong you buddy developers will help to fix the issue.
var maxField = 5;
var x = 1;
$('.add_button').click(function() {
if (x < maxField) {
x++;
newrow = '<tr class="ok"><td><select class="form-control" name="product_name[]" id="product_id" required><option value="14563">Product 1</option><option value="96547">Product 2</option><option value="965489">Product 3</option></select></td><td><input type="tel" class="form-control" name="quantity[]" placeholder="Enter Quantity" /></td><td><button type="button" class="btn btn-danger remove_button"><i class="fa fa-minus"></i></button></td></tr>';
var rowspan = parseInt($('.field_data').attr('rowspan')) + 1;
$('.field_data').attr('rowspan', rowspan);
$('.complaint_table tr:eq(3)').after(newrow);
}
});
$(".complaint_table").on("click", ".remove_button", function(e) {
e.preventDefault();
$(this.tr).remove();
x--;
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<table class="table table-striped table-hover table-bordered complaint_table">
<tbody>
<tr>
<td>Company:</td>
<td>
<input class="form-control" type="text" maxlength="50" placeholder="Company" />
</td>
<td>Company RegDate:</td>
<td>
<input class="form-control" type="date" />
</td>
</tr>
<tr class="complaint_table">
<td rowspan="10" class="field_data">Products<span style="color: red; font-size: 14px;"> *</span>:</td>
<td>
<select class="form-control" name="product_name[]">
<option value="14563">Product 1</option>
<option value="96547">Product 2</option>
<option value="965489">Product 3</option>
</select>
</td>
<td><input class="form-control" type="number" maxlength="2" minlength="1" name="quantity[]" /></td>
<td><button type="button" class="btn btn-success add_button"><i class="fa fa-plus"></i></button></td>
</tr>

The issue is because this in the .remove_button click handler refers to the DOM element. They do not have a tr property.
Instead to get a reference to the parent tr element to the clicked button use closest():
$(".complaint_table").on("click", ".remove_button", function(e) {
e.preventDefault();
$(this).closest('tr').remove();
x--;
});

Related

Javascript/Jquery : How can I show value which match with selected value on dynamic table?

I have a dynamic table where button on click add new row. Each row has a select value for product name and a input value for product price. I want to show the product price depends on the selected value. For backed I used Laravel 7. Below I added my code:
Table:
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control" id="product-name">
<option value="" selected disabled>Select Product</option>
#foreach($product as $row)
<option value="{{ $row->id }}">{{ $row->name }}</option>
#endforeach
</select>
</td>
<td>
#foreach($product as $row)
<input id="price_{{ $row->id }}" value="{{ $row->price }}" type="number" class="form-control price" style="display:none;">
#endforeach
</td>
<td><button class="remove">Delete</button></td>
</tr>
</tbody>
</table>
This is the script where button on click add a new row:
$(function() {
const $tb = $('#product-table tbody');
$(".delete").eq(0).hide()
$("#productAdd").on("click",function() {
const $row = $tb.find("tr").eq(0).clone();
$(".delete",$row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
Here I show all the product price and all are hidden. I want to show the price value which match with the selected value. For this I used id = price_{{ $row->id }}
#foreach($product as $row)
<input id="price_{{ $row->id }}" value="{{ $row->price }}" type="number" class="form-control price" style="display:none;">
#endforeach
And this is my script where showed the product price:
$('#product-name').on('change',function(){
$(".price").hide();
var price = $(this).find('option:selected').val();
$("#price_" + price).show();});
But this works for the first row only. How can I merge this script, so that it works for every new row added inside the table?
$(function() {
const $tb = $('#product-table tbody');
$(".remove").eq(0).hide()
$("#productAdd").on("click",function() {
const $row = $tb.find("tr").eq(0).clone();
$(".remove",$row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
$('#product-name').on('change',function(){
$(".price").hide();
var price = $(this).find('option:selected').val();
$("#price_" + price).show();});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control" id="product-name">
<option value="" selected disabled>Select Product</option>
<option value="1">Pant</option>
<option value="2">Shirt</option>
<option value="3">T-shirt</option>
</select>
</td>
<td>
<input id="price_1" value="100" type="number" class="form-control price" style="display:none;">
<input id="price_2" value="200" type="number" class="form-control price" style="display:none;">
<input id="price_3" value="50" type="number" class="form-control price" style="display:none;">
</td>
<td><button class="remove">Delete</button></td>
</tr>
</table>
With proper delegation it will work
As I said in my other answer, do not use ID
Here is a working version. See I changed the ID to class
$(function() {
const $tb = $('#product-table tbody');
$(".remove").eq(0).hide()
$("#productAdd").on("click", function() {
const $row = $tb.find("tr").eq(0).clone();
$(".remove", $row).show(); // show the hidden delete on this row
$row.find("select").val(""); // reset the select
$row.find("[type=number]").val(); // reset the numbers
$tb.append($row);
});
$tb.on('click', '.remove', function() {
$(this).closest('tr').remove();
});
$tb.on('change', '.product-name', function() {
const $row = $(this).closest('tr');
$(".price", $row).hide();
const whichPrice = $(this).val();
if (whichPrice != "") $(".price", $row).eq(whichPrice-1).show()
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="productAdd" type="button"> Add Row</button>
<table id="product-table" class="table table-bordered text-center">
<tr>
<td>
<select name="product_id[]" class="form-control product-name">
<option value="" selected disabled>Select Product</option>
<option value="1">Pant</option>
<option value="2">Shirt</option>
<option value="3">T-shirt</option>
</select>
</td>
<td>
<input value="100" type="number" class="form-control price" style="display:none;">
<input value="200" type="number" class="form-control price" style="display:none;">
<input value="50" type="number" class="form-control price" style="display:none;">
</td>
<td><button class="remove">Delete</button></td>
</tr>
</table>

How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>

How to make a dynamic change and access a parent element on a value using JQuery?

I have a form where it is related to my previous question here. What I want to do is to get the previous value inside my input element labeled "SERIAL END" then automatically appends it's value when adding a row to "SERIAL START", and not only append but will add +1 to it's value (this is solved), but I want to add a function when the value is already added, it will get the value of the edited parent element and can be changeable but still adds the children element's value by +1.
Here is my whole code
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var lasttr = $('#tbl tr:last').attr('id');
var lastinsertedrow = lasttr.replace('tablerow_', '');
var end = $('#serend' + lastinsertedrow).val();
end = (parseInt(end) + parseInt(1));
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" required><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
echo "<option value=$row[id]>".$row['model_name'].
" </option>";
}
} ? > < /select></td > ';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="text" class="form-control" id="serstart' + hidden +
'" name="serstart[]" value="' + end + '" readonly/></td>';
cols +=
'<td><input type="text" class="form-control" id="serend' + hidden +
'" name="serend[]" onchange="myChangeFunction(this)" required /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
$("#serend" + hidden).on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
}
})
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
include ('../include/header_pis.php');
?>
<html>
<title>Lot_Registration</title>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header"> Lot Registration
<a href="rbg_table.php">
<button class="btn btn-success pull-right">
<span class="fa fa-reply"> Back </span>
</button>
</a>
</h1>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Model Form
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form class="className" name="form" id="form" action="lot_registration_model_submit.php" data-toggle="validator" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno" name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof" name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serstart" name="serstart" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serend" name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model
left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
} ?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="text" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="text" name="serend[]" id="serend0" class="form-control" onchange="myChangeFunction(this)" required />
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
As i said in comment you just need to get index of tr where input has changed and then using that access next tr input and add value there.
Demo Code :
$("[id*=serend]").on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
} else {
//get index of tr
var row = $(this).closest('tr').index() + 1;
var end = $(this).val(); //get value of input change
end = (parseInt(end) + parseInt(1));
$("tbody tr:eq(" + row + ") td:eq(2) input").val(end) //add inside next input
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
<tr id="tablerow_1">
<td>
<select name="model[]" id="model1" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code1" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart1" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend1" value="" class="form-control"> </td>
</tr>
<tr id="tablerow_2">
<td>
<select name="model[]" id="model2" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code2" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart2" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend2" value="" class="form-control"> </td>
</tr>
</tbody>
</table>

How to set the selected value of a dynamically created select box

I have a table with multiple cells containing select boxes. The code I have can create/delete rows relative to the entry which you click "+/-" from. I would like it so that if I press "+" then my program will look at the employee chosen in the above entry and have it as the selected value in the current (or new) entry.
I am having a hard time grabbing the value of the field, as well as making it the selected value.
Here is my code:
[JS]
function createRow(id, emp = null) {
var newrow = [
id,
'<select class="browser-default custom-select">' + employee_list + '</select>', // Want to add 'emp' here as selected element
'<select class="browser-default custom-select"></select>',
'<div class="input-group"><input type="number" min="0" step="0.5" class="form-control"><div class="input-group-append"><span class="input-group-text">hours</span></div>',
'<div class="input-group"><div class="input-group-prepend"><span class="input-group-text">$</span></div><input type="number" step="0.01" min="0" class="form-control"></div>',
'<textarea class="form-control" maxlength="200"></textarea>',
'<a class="addButton"><i class="fa fa-plus"></i></a> <a class="deleteButton"> <i class="fa fa-minus"></i></a>'
];
return '<tr><td>' + newrow.join('</td><td>') + '</td></tr>';
}
function renumberRows() {
$('table#budget tbody tr').each(function(index) {
$(this).children('td:first').text(index + 1);
});
}
$('#add').click(function() {
var lastvalue = 1 + parseInt($('table#budget tbody').children('tr:last').children('td:first').text());
$('table#budget tbody').append(createRow(lastvalue));
});
$('table#budget').on('click', '.addButton', function() {
$(this).closest('tr').after(createRow(0));
console.log($(this).closest('tr').children('td:nth-child(2)').val()); // tring to get previous entries selected employee
renumberRows();
}).on('click', '.deleteButton', function() {
$(this).closest('tr').remove();
renumberRows();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="pure-table pure-table-horizontal" id="budget" style="width: 100%" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Row</th>
<th>Employee</th>
<th>Task</th>
<th>Budget</th>
<th>Expense</th>
<th>Comments</th>
<th><a id="add" style="float: right; color: #0000EE">Add Row <i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<select class="browser-default custom-select" id="emp" size="1">
<option disabled selected>Choose Employee</option>
<?php for($i=0;$i<count($options_2);$i++){echo $options_2[$i];} ?>
</select>
</td>
<td>
<select class="browser-default custom-select" id="task" size="1">
<option disabled selected>Pick Employee</option>
</select>
</td>
<td>
<div class="input-group">
<input type="number" min="0" step="0.5" class="form-control">
<div class="input-group-append">
<span class="input-group-text">hours</span>
</div>
</td>
<td>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" step="0.01" min="0" class="form-control">
</div>
</td>
<td><textarea class="form-control" maxlength="200"></textarea></td>
<td><a class="addButton"><i class="fa fa-plus"></i></a>
<a class="deleteButton"> <i class="fa fa-minus"></i></a>
</td>
</tr>
<!-- This is our clonable table line -->
</tbody>
</table><br>
example
The expected result would be to have the employee of the previous (or above) entry as the selected value in the new row upon clicking +. Or in the photo, the blacked out name would be showing where Choose Employee is.
EDIT: the global variable employee_list is an array containing all of the employees in html options format.
It would be easier if createRow() converted the HTML to DOM elements. Then you can use jQuery methods to find the select and set its value.
Use $(this).closest('tr').find('select:first').val() to get the employee from the row where you clicked Add.
It would also be a good idea to add distinct classes to specific inputs and selects, rather than using selectors like select:first to find a particular select in the row.
function createRow(id, emp = null) {
var newrow = [
id,
'<select class="browser-default custom-select">' + employee_list + '</select>', // Want to add 'emp' here as selected element
'<select class="browser-default custom-select"></select>',
'<div class="input-group"><input type="number" min="0" step="0.5" class="form-control"><div class="input-group-append"><span class="input-group-text">hours</span></div>',
'<div class="input-group"><div class="input-group-prepend"><span class="input-group-text">$</span></div><input type="number" step="0.01" min="0" class="form-control"></div>',
'<textarea class="form-control" maxlength="200"></textarea>',
'<a class="addButton"><i class="fa fa-plus"></i></a> <a class="deleteButton"> <i class="fa fa-minus"></i></a>'
];
var elts = $('<tr><td>' + newrow.join('</td><td>') + '</td></tr>');
if (emp !== null) {
elts.find("select:first").val(emp);
}
return elts;
}
function renumberRows() {
$('table#budget tbody tr').each(function(index) {
$(this).children('td:first').text(index + 1);
});
}
$('#add').click(function() {
var lastvalue = 1 + parseInt($('table#budget tbody').children('tr:last').children('td:first').text());
$('table#budget tbody').append(createRow(lastvalue));
});
$('table#budget').on('click', '.addButton', function() {
var prevemp = $(this).closest('tr').find('select:first').val();
$(this).closest('tr').after(createRow(0, prevemp));
console.log($(this).closest('tr').children('td:nth-child(2)').val()); // tring to get previous entries selected employee
renumberRows();
}).on('click', '.deleteButton', function() {
$(this).closest('tr').remove();
renumberRows();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="pure-table pure-table-horizontal" id="budget" style="width: 100%" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Row</th>
<th>Employee</th>
<th>Task</th>
<th>Budget</th>
<th>Expense</th>
<th>Comments</th>
<th><a id="add" style="float: right; color: #0000EE">Add Row <i class="fa fa-plus"></i></a></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<select class="browser-default custom-select" id="emp" size="1">
<option disabled selected>Choose Employee</option>
<?php for($i=0;$i<count($options_2);$i++){echo $options_2[$i];} ?>
</select>
</td>
<td>
<select class="browser-default custom-select" id="task" size="1">
<option disabled selected>Pick Employee</option>
</select>
</td>
<td>
<div class="input-group">
<input type="number" min="0" step="0.5" class="form-control">
<div class="input-group-append">
<span class="input-group-text">hours</span>
</div>
</td>
<td>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" step="0.01" min="0" class="form-control">
</div>
</td>
<td><textarea class="form-control" maxlength="200"></textarea></td>
<td><a class="addButton"><i class="fa fa-plus"></i></a>
<a class="deleteButton"> <i class="fa fa-minus"></i></a>
</td>
</tr>
<!-- This is our clonable table line -->
</tbody>
</table><br>

adding delete button to appended elements

My code is attached below.
$('#aprod').on('click', function() {
$('#ln1').clone().appendTo('#page3_inside');
prodnum = prodnum + 1;
$('#conf_prodnum').val(prodnum);
});
$('body').on('click', '.del', function() {
$(this).closest('tr').remove();
});
<html>
<head>
<meta name="generator"
content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<form>
<input type='button' value='Add Another Product' id='aprod' />
</form>
<table id='page3_inside'>
<tr id='ln1'>
<td>
<label for="product_name">Product Name</label>
<br />
<select class='input name_of_product' style='width:150px; height:34px;' name="name_of_product[]">
<option value="">Select from List</option>
</select>
</td>
<td>
<label for="product_cat">Product Category</label>
<br />
<input type='text' class="input product_category" name="product_category[]"
style="font-family:verdana; width:150px; border: 1px solid #000000;" readonly="readonly" />
</td>
<td>
<label for="qty">Qty</label>
<br />
<input type="text" value="" class="input qty" style="width:100px;" name="qty[]" placeholder="Qty"
onkeypress="return isNumberKey(event)" />
</td>
<td>
<label for="unit">Unit</label>
<br />
<input type='text' class="input unit" style="width:100px;" name="unit[]" readonly="readonly" />
</td>
<td>
<label for="brand">PO Number</label>
<br />
<input type="text" value="" class="input po" name="po[]" placeholder="PO Number"
style='width:150px; height:28px;' />
</td>
<td>
<img src='http://www.oasisservicedoffices.co.uk/wp-content/uploads/2014/08/Delete-button-150x150.jpg'
class='del' width='30px' style='cursor:hand;cursor:pointer;' />
</td>
</tr>
</table>
</body>
</html>
$('body').on('click', '.del', function() {
$(this).closest('tr').remove();
});
I created a delete button for appended elements. but as you can see, there is a delete button on the first row. what i want to do is remove that delete button, and only display it on the next row upon pressing the 'Add Another Product' button.
$('#aprod').on('click', function() {
$('#ln1').clone().appendTo('#page3_inside');
prodnum = prodnum + 1;
$('#conf_prodnum').val(prodnum);
});
You could just hide the first delete button with css
table tr:first-child .del{
display: none;
}
DEMO
If you want delete button to the last element only:
$('#aprod').on('click', function() {
var el = $('#page3_inside tr:last').clone()
$('#page3_inside').find('.del').remove();
el.appendTo('#page3_inside');
prodnum = prodnum + 1;
$('#conf_prodnum').val(prodnum);
});
$('body').on('click', '.del', function() {
$(this).closest('tr').remove();
});
Demo: http://jsfiddle.net/tusharj/f772sovm/8/
You can append the img directly in JS. Remove it from your HTML.
$('#aprod').on('click', function() {
var i=$('#ln1').clone().appendTo('#page3_inside');
i.append('<img src="http://www.oasisservicedoffices.co.uk/wp-content/uploads/2014/08/Delete-button-150x150.jpg" class="del" width="30px" style="cursor:hand;cursor:pointer;">')
prodnum = prodnum + 1;
$('#conf_prodnum').val(prodnum);
});
Fiddle
You can try this
$( "#page3_inside table" ).first().find('img').css("display", "none");

Categories

Resources