Fill form with table row data using javascript - javascript

I am having trouble filling a form with table data.The form is in a modal dialogue and I want the dialogue to popup with inputs filled when the user clicks on the glyphicon, glyphicon-pencil.
I have looked at Fill form using table data, How to fill input fields in form with data from row in html table I want to edit, jQuery dynamic fill in form fields with table data, and Automatic fill a table with data using JavaScript and JSON, and none of their solutions worked for me, so please help.
here is the modal and form code:
<div class="modal fade" id="New-Employee-Modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Employee</h4>
</div>
<div class="modal-body">
<div id="data">
<form id="person">
<div class="form-group">
<label class="control-label">First Name:</label>
<input class="form-control" id="FirstName" name="FirstName" type="text">
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<input class="form-control" id="LastName" name="LastName" type="text">
</div>
<div class="form-group">
<label class="control-label">Net Id:</label>
<input class="form-control" id="NetId" name="Netid" type="text">
</div>
<div class="form-group">
<label class="control-label">Phone #:</label>
<input class="form-control" id="PhoneNumber" name="PhoneNumber" type="tel" required />
</div>
<div class="form-group">
<label class="control-label">Email:</label>
<input class="form-control" id="Email" name="Email" type="text">
</div>
<div class="form-group">
<label class="control-label">Role</label>
<input class="form-control" id="Role" name="Role" type="text">
</div>
<div class="form-group">
<label class="control-label">Active:</label>
<br />
<input name="Active" type="radio" value='<span class="glyphicon glyphicon-ok-circle">' /> Active
<br />
<input name="Active" type="radio" value='<span class="glyphicon glyphicon-ban-circle">' /> Not Active
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="ResetForm()">Reset</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="AddData()">Save</button>
</div>
</div>
</div>
</div>
Here is the part of the table:
<div id="tab">
<table class="table table-striped" id="list">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Net ID</th>
<th>Phone #</th>
<th>Email</th>
<th>Active</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joel</td>
<td>lewis</td>
<td>lewisj</td>
<td>333-555-3667</td>
<td>lewisj#gmail.com</td>
<td>
<a id="icon-toggle" class="btn-default">
<span class="glyphicon glyphicon-ok-circle" aria-hidden="true"></span>
</a>
</td>
<td>Developer</td>
<td>
<span class="glyphicon glyphicon-pencil" data-target="#New-Employee-Modal" onclick="UpdateForm()" aria-hidden="true"></span>
<a id="icon-toggle-delete" class="removebutton">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
</td>
</tr>
and here is the javascript:
function AddData() {
var rows = "";
var FirstName = document.getElementById("FirstName").value;
var LastName = document.getElementById("LastName").value;
var NetId = document.getElementById("NetId").value;
var PhoneNumber = document.getElementById("PhoneNumber").value.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
var Email = document.getElementById("Email").value;
var Active = document.querySelector('input[name="Active"]:checked');
Active = Active ? Active.value : '';
var Role = document.getElementById("Role").value;
rows += "<td>" + FirstName + "</td><td>" + LastName + "</td><td>" + NetId + "</td><td>" + PhoneNumber + "</td><td>" + Email + "</td><td>" + Active + "</td><td>" + Role + '</td><td> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> <a id="icon-toggle-delete2" class="removebutton"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </a></td>';
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
function UpdateForm() {
$('span.glyphicon glyphicon-pencil').click(function() {
//! Don't know what do here
});
}
function ResetForm() {
document.getElementById("person").reset();
}
here is the jsfiddle http://jsfiddle.net/neu4gh37/2/

You can use such an example of code. Note, you don't need call UpdateForm() with onclick event, you added this event by jQuery for the selector 'span.glyphicon-pencil' (I fixed it a little)
$('span.glyphicon-pencil').click(function () {
var formFields = [];
var $target = $(event.target);
var $row = $target.closest('tr');
$row.find('td').each(function (index, el) {
var fieldValue = $(el).html();
switch (index) {
case 0:
formFields['FirstName'] = fieldValue;
break;
case 1:
formFields['LastName'] = fieldValue;
break;
default:
break;
}
});
fillForm(formFields);
});
function fillForm(data) {
var $form = $('#person');
$form.find('input').each(function () {
var $input = $(this);
switch ($input.attr("name")) {
case 'FirstName':
$input.val(data['FirstName']);
break;
case 'LastName':
$input.val(data['LastName']);
break;
default:
break;
}
});
}

Related

How to create a unique ID on each function call to a drop down list Asp.net

I am trying to dynamically add a new product each time an option from a drop down menu is chosen. However I believe my id field is preventing me from creating new data on my added rows. I can only change the first row. How to adjust my script to create ne id values on each function call. I tried using the Date.Now field.....but no luck.
This is how the form looks
Drop down menu
Added two more products but cant get the values of the Description, Price, etc
#page
#using Newtonsoft.Json
#model DotComFinal.Pages.Quotations.CreateModel
#{
ViewData["Title"] = "Create";
}
<h1>Create Quotation</h1>
<hr />
<div>
Customer Info
<form method="post d-flex">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Quotation.Customer.FirstName" class="control-label"></label>
<input asp-for="Quotation.Customer.FirstName" class="form-control w-50" asp-items="ViewBag.CustomerID"></input>
</div>
<div class="form-group">
<label asp-for="Quotation.Customer.LastName" class="control-label"></label>
<input asp-for="Quotation.Customer.LastName" class="form-control w-50" asp-items="ViewBag.CustomerID"></input>
</div>
<div class="form-group ">
<label asp-for="Quotation.Customer.Email" class="control-label"></label>
<input asp-for="Quotation.Customer.Email" class="form-control w-50" asp-items="ViewBag.CustomerID"></input>
</div>
<div class="form-group w-100">
<label asp-for="Quotation.QuotDate" class="control-label"></label>
<input asp-for="Quotation.QuotDate" class="form-control w-50" />
<span asp-validation-for="Quotation.QuotDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Quotation.ValidUntil" class="control-label"></label>
<input asp-for="Quotation.ValidUntil" class="form-control w-50" />
<span asp-validation-for="Quotation.ValidUntil" class="text-danger"></span>
</div>
<div class=" w-50">
<label class="control-label">Select a Product</label>
<table id="product-select" class=" table table-striped table-sm w-100">
<thead>
<tr>
<th>
<label asp-for="Product[0].Name"></label>
</th>
<th>
<label asp-for="Product[0].Description"></label>
</th>
<th>
<label asp-for="Product[0].Quantity"></label>
</th>
<th>
<label asp-for="Product[0].UnitPrice"></label>
</th>
<th>
<label asp-for="Product[0].Discount"></label>
</th>
<th>
<label asp-for="Product[0].Vat"> </label>
</th>
<th>
<label asp-for="Product[0].NetTotal"></label>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="btn btn-success " id="productOptions" onchange="changeDropDownValue()">
#* <option value="">Product</option>*#
#foreach (var product in Model.Product)
{
<option value="#product.ID">#product.Name</option>
}
</select>
</td>
<td>
<input asp-for="Product[0].Description" id="test" disabled />
<span asp-validation-for="Product[0].Description" class="text-danger"></span>
</td>
<td>
<input asp-for="Product[0].Quantity" />
<span asp-validation-for="Product[0].Quantity" class="text-danger"></span>
</td>
<td>
<input asp-for="Product[0].UnitPrice" disabled />
<span asp-validation-for="Product[0].UnitPrice" class="text-danger"></span>
</td>
<td>
<input asp-for="Product[0].Discount" />
<span asp-validation-for="Product[0].Discount" class="text-danger"></span>
</td>
<td>
<input asp-for="Product[0].Vat" disabled />
<span asp-validation-for="Product[0].Vat" class="text-danger"></span>
</td>
<td>
<input asp-for="Product[0].NetTotal" disabled />
<span asp-validation-for="Product[0].NetTotal" class="text-danger"></span>
</td>
<ttd>
</ttd>
</tr>
</tbody>
</table>
#* <button onclick="AddItem(this)" id="btnadd" type="button" class=" btn btn-sm btn-outline-success m-auto visible">Add Product</button>
<button id="btnremove" type="button" class="m-2 btn btn-sm btn-danger invisible">Delete</button>*#
</div>
<button onclick="AddItem(this)" id="btnadd" type="button" class=" btn btn-sm btn-outline-success w-100 visible">Add Product</button>
<button onclick="DeleteItem(this)" id="btnremove" type="button" class="m-2 btn btn-sm btn-danger visible">Delete</button>
<div>
<input type="submit" value="Create Quotation" class="btn btn-primary mt-3" />
<a asp-page="Index">Back to List</a>
</div>
<div>
</div>
<div class="d-flex gap-lg-5 ">
<div class="form-group">
<label asp-for="Quotation.StaffID" class="control-label"></label>
#* <select asp-for="Quotation.StaffID" class="form-control" asp-items="#Model.CompanyStaffNameSL"><option value="">-- Select Major --</option></select>
*# </div>
<div class="form-group">
<label asp-for="Quotation.FinalTotal" class="control-label"></label>
<input asp-for="Quotation.FinalTotal" class="form-control" />
<span asp-validation-for="Quotation.FinalTotal" class="text-danger"></span>
</div>
</div>
</form>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");};
}
<script type="text/javascript">
function AddItem(btn){
var product = document.getElementById("product-select");
var rows = product.getElementsByTagName("tr");
var rowOuterHtml = rows[rows.length-1].outerHTML;
var newRow = product.insertRow();
newRow.innerHTML=rowOuterHtml;
function DeleteItem(btn){
var product = document.getElementById("product-select");
var rows = product.getElementsByTagName("tr");
$(btn).closet("tr").remove;
}
}
</script>
<script>
alert("test")
function changeDropDownValue() {
var selectedProductId = document.getElementById("productOptions").value;
var Products = #Html.Raw(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(#Model.Product)));
// Find the product with the matching ID in the Model.Product array
var selectedProduct = Products.find(product => product.ID == selectedProductId);
var newId = "product-" + Date.now();
// Update the input fields with the values of the selected product
document.getElementById("test").value = selectedProduct.Description;
document.getElementsByName("Product[0].Quantity")[0].value = selectedProduct.Quantity;
document.getElementsByName("Product[0].UnitPrice")[0].value = selectedProduct.UnitPrice;
document.getElementsByName("Product[0].Discount")[0].value = selectedProduct.Discount;
document.getElementsByName("Product[0].Vat")[0].value = selectedProduct.Vat;
document.getElementsByName("Product[0].NetTotal")[0].value = selectedProduct.NetTotal;
}
</script>
Firstly,id should be unique,so you need to change the ids when inserting a new row.Then when selcted option is changed,you need to tell the js which row you are changing,so you need to tell the index,here is a demo:
html of select(pass the select element to js,and add the current index into id):
<select class="btn btn-success " id="productOptions_0" onchange="changeDropDownValue(this)">
#* <option value="">Product</option>*#
#foreach (var product in Model.Product)
{
<option value="#product.ID">#product.Name</option>
}
</select>
description input(remove the id so that it will be unique when adding new rows):
js:
function AddItem(btn){
var product = document.getElementById("product-select");
var rows = product.getElementsByTagName("tr");
var rowOuterHtml = rows[1].outerHTML;
var index=rows.length-1;//index of the new row
var newRow = product.insertRow();
newRow.innerHTML=rowOuterHtml.replaceAll("[0","["+index).replaceAll("_0","_"+index);//set ids and names of the new row with index
}
function DeleteItem(btn){
var product = document.getElementById("product-select");
var rows = product.getElementsByTagName("tr");
$(btn).closet("tr").remove;
}
function changeDropDownValue() {
var selectedProductId = document.getElementById("productOptions").value;
var Products = #Html.Raw(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(#Model.Product)));
// Find the product with the matching ID in the Model.Product array
var selectedProduct = Products.find(product => product.ID == selectedProductId);
var index=$(test).attr("id").split("_")[1];//find the index with id
// Update the input fields with the values of the selected product
document.getElementsByName("Product[" + index + "].Description")[0].value = selectedProduct.Description;
document.getElementsByName("Product[" + index + "].Quantity")[0].value = selectedProduct.Quantity;
document.getElementsByName("Product[" + index + "].UnitPrice")[0].value = selectedProduct.UnitPrice;
document.getElementsByName("Product[" + index + "].Discount")[0].value = selectedProduct.Discount;
document.getElementsByName("Product[" + index + "].Vat")[0].value = selectedProduct.Vat;
document.getElementsByName("Product[" + index + "].NetTotal")[0].value = selectedProduct.NetTotal;
}

how can i write a program for checkbox clicked automatically with the help of database and displayed in bootstrap modal page

hai iam trying to write a program for checkbox clicked automatically with the help of database....i am writing the code like this i.e., i am writing jsp project when i am clicked the user page it display the users details in the table format. in that it has two icons one is update and another one is delete...
when i am clicked on update its open a bootstrap modal page and display the user details in that i am using a checkbox tag..when the user is active its checkbox clicked automatically...but iam getting unclicked how can in resolve this...
<div class="table-responsive">
<table class="table table-hover table-centered m-0">
<thead>
<tr>
<th>Rolename</th>
<th>Status</th>
<th>Created On</th>
<th>Modified On</th>
<th>Status1</th>
<th colspan="2">Options</th>
</tr>
</thead>
<%
int status=0;
Connection con=DriverManager.getConnection(connectionUrl);
//Statement st = con.createStatement();
PreparedStatement pstmt=null;
pstmt=con.prepareStatement("select * from m_Roles "); //sql select query
ResultSet rs1=pstmt.executeQuery(); //execute query and set in ResultSet object "rs"
%>
<tbody>
<%
while(rs1.next())
{
status=rs1.getInt("IsActive");
%>
<tr id="<%=rs1.getString("RoleID")%>">
<th><%=rs1.getString("RoleName")%></th>
<th><%=status%></th>
<td><%=rs1.getString("CreatedOn")%></td>
<td><%=rs1.getString("ModifiedOn")%></td>
<!-- <td><input type="checkbox" id="" disabled="" name="active" parsley-trigger="change" <% if(status==1) { %> checked="checked" <% } %> ></td>-->
<td><input type="text" id="" disabled="" name="active"<% if(status==1) { %> value="Active" <% }else{%>value="Inactive"<%} %> > </td>
<td align="">
<!-- Update Icon -->
<a href="#editEmployeeModal" class="edit" data-toggle="modal">
<i class="mdi mdi-account-edit update" data-toggle="tooltip"
data-rid="<%=rs1.getString("RoleID")%>"
data-rname="<%=rs1.getString("RoleName")%>"
data-check="<%=status%>"
title="Edit"></i>
</a>
</td>
<!-- Delete Icon Table -->
<td>
<a href="#deleteEmployeeModal" class="delete" data-rid="<%=rs1.getString("RoleID")%>" data-toggle="modal">
<i class="mdi mdi-delete delete" data-toggle="tooltip"
title="Delete"></i></a>
</div>
</a>
</td>
<div id="editEmployeeModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title mt-0">Edit Roles</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="update_form">
<div class="row">
<input type="hidden" id="rid_u" name="id" parsley-trigger="change" autocomplete="off" required placeholder="Enter First Name" class="form-control" id="firstName">
<div class="col-md-9">
<div class="form-group row">
<label class="col-md-4 control-label">Role Name<span class="text-danger">*</span></label>
<div class="col-md-7">
<input type="text" id="rname_u" name="rname" parsley-trigger="change" autocomplete="off" required placeholder="Enter First Name" class="form-control" id="firstName">
</div>
</div>
<div class="form-group row">
<label class="col-md-5 control-label">Active<span class="text-danger">*</span></label>
<div class="col-md-7">
<input type="text" name="check_box" id="check_u"/>
#if(check_u==1)
{
<input type="checkbox" id="act_u" checked="checked" name="active" parsley-trigger="change" >
}
else
{
<input type="checkbox" id="act_u" name="active" parsley-trigger="change" >
}
</div>
</div>
<div class="form-group text-right mb-0">
<input type="hidden" value="2" name="type">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
<button type="button" class="btn btn-info" id="update">Update</button>
</div>
</div>
</div>
</form>
````
this is ajax code
<script>
$(document).on("click", ".delete", function()
{
var uid=$(this).attr("data-id");
$('#id_d').val(uid);
});
$(document).on('click','#delete',function(e) {
var data = $("#delete_form").serialize();
$.ajax({
data:data,
url: "deleterole.jsp",
//data:"uid="+id,
method: "POST",//HTTP method.
success: function()
{
//alert('Data deleted successfully !');
location.reload();
//setInterval('location.reload()',2000);
}
});
});
$(document).on('click','.update',function(e) {
var id=$(this).attr("data-rid");
var rname=$(this).attr("data-rname");
var check_box=$(this).attr("data-check");
$('#rid_u').val(id);
$('#rname_u').val(rname);
$('#check_u').val(check_box);
});
$(document).on('click','#update',function(e) {
var data = $("#update_form").serialize();
$.ajax({
data: data,
type: "post",
url: "updaterole.jsp",
success: function()
{
alert('Data updated successfully !');
location.reload();
}
});
});
</script>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#act_u").change(function()
{
// var t=document.getElementById('check_u').value;
//if("#check_u").
if($(this).prop("checked") == true)
{
$("#check_u").val("1");
}
else if($(this).prop("checked") == false)
{
$("#check_u").val("0");
}
});
});
</script>
You can directly put your #if(check_u==1) {.. inside your jquery code and only leave <input type="checkbox" id="act_u" name="active" parsley-trigger="change"> in modal. Also ,your jquery code will look like below :
$(document).on('click', '.update', function(e) {
var id = $(this).attr("data-rid");
var rname = $(this).attr("data-rname");
var check_box = $(this).attr("data-check");
$('#rid_u').val(id);
$('#rname_u').val(rname);
$('#check_u').val(check_box);
//checking value of checkbox
if (check_box == 1) {
//checked
$('#act_u').prop('checked', true);
} else {
//unchecked
$('#act_u').prop('checked', false);
}
});

jQuery how to use event driven variable in multiple functions

I have a function that assigns values to multiple dynamically rendered input boxes based on their events. One of these values originate from a Modal, I would like to assign the value from the Modal to a textbox but am having trouble getting the value inside the Modal saving function as the value is generated in an external function. i have tried nesting or separating the two functions but I can't get it right. I would really appreciate any help.
Here is the code for the dynamic inputs in a table
<table id="requested-wh-stock-table" class="table table-bordered table-hover dataTable" width="100%">
<thead>
<tr>
<th width="50%">Luminaire</th>
<th>Shelve Number</th>
<th>Order Quantity</th>
<th>Delivered Qty</th>
<th>Back Order Qty</th>
</tr>
</thead>
<tbody>
#foreach ($salesorder as $request)
<tr>
<td>
<input type="hidden" class="wh_id" name="wh_id" value="{{$request->wh_id}}">
<input type="hidden" class="wh_id" name="light_id" value="{{$request->light_id}}">
<input type="text" class="form-control" name="luminaire" value="{{$request->luminaire}}" readonly></td>
<td><input type="text" class="form-control shelve_number" name="shelve_number" id="shelve_number" value="" onfocus="popModal(this)"></td>
<td><input type="number" class="form-control order_quantity" name="order_quantity" id="order_quantity" value="{{$request->quantity}}" readonly/></td>
<td><input type="number" class="form-control delivered_quantity" name="delivered_quantity" id="delivered_quantity" value=""/></td>
<td><input type="number" class="form-control backorder_quantity" name="backorder_quantity" id="backorder_quantity" value="" readonly/></td>
</tr>
#endforeach
</tbody>
</table>
Here is the Modal Code
<!--Shelve Modal-->
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Select Shelve Number</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-12" style="text-align:center;margin-bottom:5%;margin-right:10%">
<div class="row">
<div class="col-sm-6">
<label>Shelve Number</label>
</div>
<div class="col-sm-6">
<select id="shelve_no" class="form-control select2" style="width: 100%;" name="shelve_no">
</select>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_modal" class="btn btn-primary">Save changes</button>
</div>
</div>
/div>
</div>
<!--End of Model-->
Here are my 2 functions
function popModal(x){
$('#myModal').modal('show');
}
//Return list of Shelves based on ordered luminaire
$('.shelve_number').on('focus',function(){
var wh_id = 1;
var light_id = 9963;
var elementChanges = "<option value='0' disabled selected>Select Shelve Number</option>";
document.getElementById('shelve_no').innerHTML = elementChanges;
$.ajax({
type:"GET",
url: '{!! url('warehouse/getshelveByluminaire') !!}/'+wh_id+"/"+light_id,
}).done(function(res) {
console.log(res);
var elems ="<option value='0' disabled selected='selected'>Choose Shelve</option>";
for(var x=0;x<res.length;x++){
elems =elems + "<option value='"+JSON.stringify(res[x])+"'>"+res[x].shelve_no+"</option>";
}
document.getElementById('shelve_no').innerHTML = elems;
});
});
//Assign Shelve number
$(document).ready(function() {
$('.shelve_number').on('change',function() {
let parent = $(this).parents('tr');
let shelve = parent.find('.shelve_number');
var selected_shelve = jQuery("#shelve_no option:selected").val();
var shelve_selected =JSON.parse(selected_shelve).shelve_no;
//Save Modal function
$('#save_modal').on('click',function(x){
shelve.val(shelve_selected);
$('#myModal').modal('hide');
});
});
});
The shelve listing function is working fine, as the shelves get listed in a drop down and I can select a shelve, but the moment I click on "Save Changes" nothing happens, and there is nothing in the Console. Please assist, I am having trouble with the last 2 functions enter image description here
You can make the variables global using window.
function popModal(x){
$('#myModal').modal('show');
}
$('.shelve_number').on('focus', function() {
let parent = $(this).parents('tr');
window.shelve = parent.find('.shelve_number');
var wh_id = 1;
var light_id = 9963;
var elementChanges = "<option value='0' disabled selected>Select Shelve Number</option>";
$('#shelve_no').html(elementChanges);
$.ajax({
type: 'GET',
url: "{!! url('warehouse/getshelveByluminaire') !!}/" + wh_id + "/" + light_id
}).done(function(res) {
console.log(res);
var elems = "<option value='0' disabled selected='selected'>Choose Shelve</option>";
for (var x = 0; x < res.length; x++) {
elems = elems + "<option value='" + JSON.stringify(res[x]) + "'>" + res[x].shelve_no + "</option>";
}
$('#shelve_no').html(elems);
});
});
//Assign Shelve number
$(document).ready(function() {
//Save Modal function
$('#save_modal').on('click',function(x) {
var selected_shelve = jQuery("#shelve_no option:selected").val();
var shelve_selected = JSON.parse(selected_shelve).shelve_no;
shelve.val(shelve_selected);
$('#myModal').modal('hide');
});
});

How to set modal popup text editor to normal input box when dynamically add rows using jQuery

I have the dynamic data table, its all working perfectly but im facing small problem that is, First row is working properly and it is stable, the Second row "NARRATION" column, is only the problem.
That means Second row narration column having input popup text editor, thats fine its working, now i click ADD NEW button another row will come and click narrate column its again show the popup text editor.. i dont want like that..
I want change the input modal text editor to normal input box. thats appear on dynamically added rows when i click add new button.
Want 1st two rows is should want popup text editor, and dynamic added rows only wants to be input boxes..
Full Code FIDDLE
/* TABLE JS */
$(document).ready(function() {
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
var tr = $("<tr></tr>", {
id: "addr" + newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(1) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
});
// Sortable Code
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$(".table-sortable tbody").sortable({
helper: fixHelperModified
}).disableSelection();
$(".table-sortable thead").disableSelection();
$("#add_row").trigger("click");
});
/* POPUP JS */
$('.cashmodal_btn').on('click', function() {
let val = $('.myInput').val();
$('#pay_narrat').val(val);
});
$('.cashmodal_btn').on('click', function() {
let val = $('.acnarrate').val();
$('#acc_narrat').val(val);
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<!-- table -->
<a id="add_row" class="btn btn-primary float-right adRow">Add New</a>
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-hover table-sortable" id="tab_logic">
<thead style="background-color: #680779;
color: #fff;">
<tr>
<th class="text-center">
Account Code
</th>
<th class="text-center">
A/c Name*
</th>
<th class="text-center">
Narration*
</th>
<th class="text-center">
Debit*
</th>
<th class="text-center">
Credit
</th>
<th class="text-center" style="border-top: 1px solid #ffffff; border-right: 1px solid #ffffff;">
Action
</th>
</tr>
</thead>
<tbody>
<tr id="fst_row">
<td>
<input type="number" id="payacc_code" placeholder='Enter A/c code' class="form-control" />
</td>
<td>
<select class="form-control" id="payacc">
<option value="">Select TDS A/c name</option>
<option value="1">JOE</option>
<option value="2">JOE 2</option>
<option value="3">JOE 3</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="pay_narrat" placeholder="Enter your here" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="paydeb" value="100" placeholder='Debit Amount' data-action="sumDebit" class="form-control" readonly />
</td>
<td>
<input type="number" id="paycredit" placeholder='Credit Amount' class="form-control" readonly />
</td>
<td>
<button class='btn btn-danger glyphicon glyphicon-remove row-remove removeBtn' style="cursor: not-allowed" disabled><span aria-hidden="true">×</span></button>
</td>
</tr>
<tr id='addr0' class="hidden">
<td data-name="cashCode">
<input type="text" id="cashacc_code" name='cashacc_code' placeholder='Enter A/c Code' class="form-control" />
</td>
<td data-name="sel">
<select class="form-control" name="cashacc_sel" id="cashacc_sel">
<option value="">Select A/c name</option>
<option value="1">Plumz</option>
<option value="2">Plumz 2</option>
<option value="3">Plumz 3</option>
</select>
</td>
<td data-name="narrate">
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter your here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td data-name="dbt">
<input type="number" id="cashdeb" name='cashdeb' placeholder='Debit Amount' data-action="sumDebit" class="form-control" />
</td>
<td data-name="crdit">
<input type="number" id="cashcredit" name='cashcredit' placeholder='Credit Amount' class="form-control" readonly />
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove removeBtn'><span aria-hidden="true">×</span></button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- narration text popup modal -->
<div class="modal fade" id="narratModal" tabindex="-1" role="dialog" aria-labelledby="narratModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close cash-dismiss" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title modal_head" id="narratModalLabel">Narration</h4>
</div>
<div class="modal-body">
<label class="modal_note">Note: Only alphabets A-Z a-z number 0-9 and characters % & [] () - _ . , are allowed in text</label>
<input class="myInput form-control form-control-sm" style="height: 7em;" placeholder="Enter Here" />
<span class="modal_valid">0/200 Characterts entered</span>
</div>
<div class="modal-footer narr_footer">
<button type="button" class="btn btn-primary cashmodal_btn" id="narrat_ok" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="accnarratModal" tabindex="-1" role="dialog" aria-labelledby="accnarratModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close cash-dismiss" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title modal_head" id="accnarratModalLabel">Narration</h4>
</div>
<div class="modal-body">
<label class="modal_note">Note: Only alphabets A-Z a-z number 0-9 and characters % & [] () - _ . , are allowed in text</label>
<textarea class="acnarrate form-control form-control-sm" style="height: 7em;" placeholder="Enter Here"></textarea>
<span class="modal_valid">0/200 Characterts entered</span>
</div>
<div class="modal-footer narr_footer">
<button type="button" class="btn btn-primary cashmodal_btn" id="accnarrat_ok" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
Full code FIDDLE
I dont know my question is understandable or not..
I got your problem. Check this code:
Update JS:
/* TABLE JS */
$(document).ready(function() {
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
var tr = $("<tr></tr>", {
id: "addr" + newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(1) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
});
// Sortable Code
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$(".table-sortable tbody").sortable({
helper: fixHelperModified
}).disableSelection();
$(".table-sortable thead").disableSelection();
$("#add_row").trigger("click");
});
/* POPUP JS */
$('.cashmodal_btn').on('click', function() {
let val = $('.myInput').val();
$('#pay_narrat').val(val);
});
$('.cashmodal_btn').on('click', function() {
let val = $('.acnarrate').val();
$(".acnarrate").val("");
$('.active').val(val);
$(".active").removeClass("active");
})
$(document).on('click',"input#acc_narrat", function() {
$(".active").removeClass("active");
$(".acnarrate").val( $(this).val() );
$(this).addClass("active");
})
Hi I understand your problem I updated your fiddle .
you just need to remove data-toggle & data-target property from newly created row. because you are cloning so each function with elements are cloning.
$("#"+trId +" #acc_narrat").removeAttr("data-target")
$("#"+trId +" #acc_narrat").removeAttr("data-toggle")
Here is working example
You are cloning row and changing ids but you need to remove data-target="#narratModal" from the input box so that modal will not be shown.
Just find the input box and remove data-target="#narratModal" attribute, see below code
/* TABLE JS */
$(document).ready(function() {
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
var tr = $("<tr></tr>", {
id: "addr" + newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(1) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
// remove data-target so that popup will not be shown
$(tr).find('input[name^=narrat]').removeAttr('data-target');
});
// Sortable Code
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$(".table-sortable tbody").sortable({
helper: fixHelperModified
}).disableSelection();
$(".table-sortable thead").disableSelection();
$("#add_row").trigger("click");
});
/* POPUP JS */
$('.cashmodal_btn').on('click', function() {
let val = $('.myInput').val();
$('#pay_narrat').val(val);
});
$('.cashmodal_btn').on('click', function() {
let val = $('.acnarrate').val();
$('#acc_narrat').val(val);
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<!-- table -->
<a id="add_row" class="btn btn-primary float-right adRow">Add New</a>
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-hover table-sortable" id="tab_logic">
<thead style="background-color: #680779;
color: #fff;">
<tr>
<th class="text-center">
Account Code
</th>
<th class="text-center">
A/c Name*
</th>
<th class="text-center">
Narration*
</th>
<th class="text-center">
Debit*
</th>
<th class="text-center">
Credit
</th>
<th class="text-center" style="border-top: 1px solid #ffffff; border-right: 1px solid #ffffff;">
Action
</th>
</tr>
</thead>
<tbody>
<tr id="fst_row">
<td>
<input type="number" id="payacc_code" placeholder='Enter A/c code' class="form-control" />
</td>
<td>
<select class="form-control" id="payacc">
<option value="">Select TDS A/c name</option>
<option value="1">JOE</option>
<option value="2">JOE 2</option>
<option value="3">JOE 3</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="pay_narrat" placeholder="Enter your here" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="paydeb" value="100" placeholder='Debit Amount' data-action="sumDebit" class="form-control" readonly />
</td>
<td>
<input type="number" id="paycredit" placeholder='Credit Amount' class="form-control" readonly />
</td>
<td>
<button class='btn btn-danger glyphicon glyphicon-remove row-remove removeBtn' style="cursor: not-allowed" disabled><span aria-hidden="true">×</span></button>
</td>
</tr>
<tr id='addr0' class="hidden">
<td data-name="cashCode">
<input type="text" id="cashacc_code" name='cashacc_code' placeholder='Enter A/c Code' class="form-control" />
</td>
<td data-name="sel">
<select class="form-control" name="cashacc_sel" id="cashacc_sel">
<option value="">Select A/c name</option>
<option value="1">Plumz</option>
<option value="2">Plumz 2</option>
<option value="3">Plumz 3</option>
</select>
</td>
<td data-name="narrate">
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter your here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td data-name="dbt">
<input type="number" id="cashdeb" name='cashdeb' placeholder='Debit Amount' data-action="sumDebit" class="form-control" />
</td>
<td data-name="crdit">
<input type="number" id="cashcredit" name='cashcredit' placeholder='Credit Amount' class="form-control" readonly />
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove removeBtn'><span aria-hidden="true">×</span></button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- narration text popup modal -->
<div class="modal fade" id="narratModal" tabindex="-1" role="dialog" aria-labelledby="narratModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close cash-dismiss" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title modal_head" id="narratModalLabel">Narration</h4>
</div>
<div class="modal-body">
<label class="modal_note">Note: Only alphabets A-Z a-z number 0-9 and characters % & [] () - _ . , are allowed in text</label>
<input class="myInput form-control form-control-sm" style="height: 7em;" placeholder="Enter Here" />
<span class="modal_valid">0/200 Characterts entered</span>
</div>
<div class="modal-footer narr_footer">
<button type="button" class="btn btn-primary cashmodal_btn" id="narrat_ok" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="accnarratModal" tabindex="-1" role="dialog" aria-labelledby="accnarratModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close cash-dismiss" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title modal_head" id="accnarratModalLabel">Narration</h4>
</div>
<div class="modal-body">
<label class="modal_note">Note: Only alphabets A-Z a-z number 0-9 and characters % & [] () - _ . , are allowed in text</label>
<textarea class="acnarrate form-control form-control-sm" style="height: 7em;" placeholder="Enter Here"></textarea>
<span class="modal_valid">0/200 Characterts entered</span>
</div>
<div class="modal-footer narr_footer">
<button type="button" class="btn btn-primary cashmodal_btn" id="accnarrat_ok" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
You just have to properly clone your tds and remove the data-target property from the input field.
Here is the update I made to your element loop.
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(1) td"), function() {
var td;
var cur_td = $(this).clone(); // <-- clone the td
var children = cur_td.children();
$(cur_td).find('#acc_narrat').removeAttr('data-toggle'); // <--- remove the attribute
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
In short, You have to clone var cur_td = $(this).clone(); the columns in order to loose the reference to your existing element.
And remove the relation to the modal from the element. $(cur_td).find('#acc_narrat').removeAttr('data-toggle');
I've updated your fiddle here.
Remove attribute data-toggle from TD before appending to $('#tab_logic')
/* TABLE JS */
$(document).ready(function() {
$("#add_row").on("click", function() {
// Dynamic Rows Code
// Get max row id and set new id
var newid = 0;
$.each($("#tab_logic tr"), function() {
if (parseInt($(this).data("id")) > newid) {
newid = parseInt($(this).data("id"));
}
});
newid++;
var tr = $("<tr></tr>", {
id: "addr" + newid,
"data-id": newid
});
// loop through each td and create new elements with name of newid
$.each($("#tab_logic tbody tr:nth(1) td"), function() {
var td;
var cur_td = $(this);
var children = cur_td.children();
// add new td and element if it has a nane
if ($(this).data("name") !== undefined) {
td = $("<td></td>", {
"data-name": $(cur_td).data("name")
});
var c = $(cur_td).find($(children[0]).prop('tagName')).clone().val("");
c.attr("name", $(cur_td).data("name") + newid);
c.appendTo($(td));
td.appendTo($(tr));
} else {
td = $("<td></td>", {
'text': $('#tab_logic tr').length
}).appendTo($(tr));
}
});
$(tr).find('#acc_narrat').removeAttr('data-toggle');
// add the new row
$(tr).appendTo($('#tab_logic'));
$(tr).find("td button.row-remove").on("click", function() {
$(this).closest("tr").remove();
});
});
// Sortable Code
var fixHelperModified = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width())
});
return $helper;
};
$(".table-sortable tbody").sortable({
helper: fixHelperModified
}).disableSelection();
$(".table-sortable thead").disableSelection();
$("#add_row").trigger("click");
});
/* POPUP JS */
$('.cashmodal_btn').on('click', function() {
let val = $('.myInput').val();
$('#pay_narrat').val(val);
});
$('.cashmodal_btn').on('click', function() {
let val = $('.acnarrate').val();
$('#acc_narrat').val(val);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<!-- table -->
<a id="add_row" class="btn btn-primary float-right adRow">Add New</a>
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-hover table-sortable" id="tab_logic">
<thead style="background-color: #680779;
color: #fff;">
<tr>
<th class="text-center">
Account Code
</th>
<th class="text-center">
A/c Name*
</th>
<th class="text-center">
Narration*
</th>
<th class="text-center">
Debit*
</th>
<th class="text-center">
Credit
</th>
<th class="text-center" style="border-top: 1px solid #ffffff; border-right: 1px solid #ffffff;">
Action
</th>
</tr>
</thead>
<tbody>
<tr id="fst_row">
<td>
<input type="number" id="payacc_code" placeholder='Enter A/c code' class="form-control" />
</td>
<td>
<select class="form-control" id="payacc">
<option value="">Select TDS A/c name</option>
<option value="1">JOE</option>
<option value="2">JOE 2</option>
<option value="3">JOE 3</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="pay_narrat" placeholder="Enter your here" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="paydeb" value="100" placeholder='Debit Amount' data-action="sumDebit" class="form-control" readonly />
</td>
<td>
<input type="number" id="paycredit" placeholder='Credit Amount' class="form-control" readonly />
</td>
<td>
<button class='btn btn-danger glyphicon glyphicon-remove row-remove removeBtn' style="cursor: not-allowed" disabled><span aria-hidden="true">×</span></button>
</td>
</tr>
<tr id='addr0' class="hidden">
<td data-name="cashCode">
<input type="text" id="cashacc_code" name='cashacc_code' placeholder='Enter A/c Code' class="form-control" />
</td>
<td data-name="sel">
<select class="form-control" name="cashacc_sel" id="cashacc_sel">
<option value="">Select A/c name</option>
<option value="1">Plumz</option>
<option value="2">Plumz 2</option>
<option value="3">Plumz 3</option>
</select>
</td>
<td data-name="narrate">
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter your here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td data-name="dbt">
<input type="number" id="cashdeb" name='cashdeb' placeholder='Debit Amount' data-action="sumDebit" class="form-control" />
</td>
<td data-name="crdit">
<input type="number" id="cashcredit" name='cashcredit' placeholder='Credit Amount' class="form-control" readonly />
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove removeBtn'><span aria-hidden="true">×</span></button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- narration text popup modal -->
<div class="modal fade" id="narratModal" tabindex="-1" role="dialog" aria-labelledby="narratModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close cash-dismiss" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title modal_head" id="narratModalLabel">Narration</h4>
</div>
<div class="modal-body">
<label class="modal_note">Note: Only alphabets A-Z a-z number 0-9 and characters % & [] () - _ . , are allowed in text</label>
<input class="myInput form-control form-control-sm" style="height: 7em;" placeholder="Enter Here" />
<span class="modal_valid">0/200 Characterts entered</span>
</div>
<div class="modal-footer narr_footer">
<button type="button" class="btn btn-primary cashmodal_btn" id="narrat_ok" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="accnarratModal" tabindex="-1" role="dialog" aria-labelledby="accnarratModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close cash-dismiss" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title modal_head" id="accnarratModalLabel">Narration</h4>
</div>
<div class="modal-body">
<label class="modal_note">Note: Only alphabets A-Z a-z number 0-9 and characters % & [] () - _ . , are allowed in text</label>
<textarea class="acnarrate form-control form-control-sm" style="height: 7em;" placeholder="Enter Here"></textarea>
<span class="modal_valid">0/200 Characterts entered</span>
</div>
<div class="modal-footer narr_footer">
<button type="button" class="btn btn-primary cashmodal_btn" id="accnarrat_ok" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>

asp.net mvc pop-up modal read from table row

I can successfully read my selected table row to my pop-up modal but if I am going to move my button to dynamic reading of table row from javascript all of my fields will become empty or did not read the selected table.
Here my Javascript that build my table row together with my button update to call pop-up modal:
$.get("/Home/GetItem", function (data) {
tempDIM = JSON.parse(data);
if (tempDIM[0]["status"] == "SUCCESS") {
for (var i = 1; i < tempDIM.length - 1; i++) {
$("#TableBody").append("<tr>" +
"<th scope='row'>" + (i + 1) + "</th>" +
"<td id='" + tempDIM[i]["id"] + "'>" + tempDIM[i]["id"] + "</td>" +
"<td>" + tempDIM[i]["name"] + "</td>" +
"<td>" + tempDIM[i]["address"] + "</td>" +
"<td>" + tempDIM[i]["age"] + "</td>" +
"<td>" + tempDIM[i]["status"] + "</td>" +
'<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Update</button></td>' +
"</tr > ");
}
}
});
Modal:
<table class="table" style="margin-top:10px">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>age</th>
<th>status</th>
</tr>
</thead>
</table>
<table class="table table-striped" id="tBody">
<tbody id="TableBody"></tbody>
</table>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-target="#exampleModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"><b>Update Selected Details</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>id:</label>
<input type="text" id="id" disabled />
</div>
<div class="form-group">
<label>name :</label>
<input type="text" id="name" disabled />
</div>
<div class="form-group">
<label>address :</label>
<input type="text" id="address" disabled />
</div>
<div class="form-group">
<label>age:</label>
<input type="text" id="age" disabled />
</div>
<div class="form-group">
<label>status:</label>
<input type="text" id="status" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" onclick="SaveChanges()" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
And my script for reading the table:
$(function () {
$(".btn").click(function () {
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$("#id").val($row.find('td:eq(0)').text())
$("#name").val($row.find('td:eq(1)').text())
$("#address").val($row.find('td:eq(2)').text())
$("#age").val($row.find('td:eq(3)').text())
$("#status").val($row.find('td:eq(4)').text())
});
});
Any suggestion or comments why I am getting null value from my pop-up modal. TIA
Assumed that your table contains proper data, $(".btn").click() event handler seems to be wrong because you may call other button with class="btn" outside the table row (i.e. <button type="button" id="btnSave" ...>). You should handle show.bs.modal event from exampleModal instead, then iterate row elements and put all values into corresponding <input> elements ordered by column index like example below:
$("#exampleModal").on('show.bs.modal', function (e) {
var $button = $(e.relatedTarget);
var $row = $button.closest("tr");
var $tds = $row.find("td");
$.each($tds, function(i, value) {
$("input:eq(" + i + ")").val($(this).text());
});
});
Note: If you want to submit textbox values inside the modal, avoid using disabled attribute which prevents the value from being posted, use readonly instead e.g. <input type="text" id="id" readonly="readonly" />.
Working example (simplified): .NET Fiddle
Related issue:
Click button on row of the table and show values in modal-window

Categories