jQuery how to use event driven variable in multiple functions - javascript

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');
});
});

Related

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

The old value always retain in the textbox modal popup and Can't get the fresh value

I know that there is a lot solution on my problem and I tried some of them,
I also tried this one
$('#myModal').on('hidden.bs.modal', function () {
$('.modal-body').find('textarea,input').val('');
});
but not working
and I even tried this code $('.modalclass').remove();
and also this one $("#myModal")[0].reset();
<div class="container">
<h2>Employees Record</h2>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">Add New Employee</button><br /><br />
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Age
</th>
<th>
State
</th>
<th>
Country
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody class="tbody">
</tbody>
</table>
</div>
<div class="modal fade" id="myModal" 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">×</button>
<h4 class="modal-title" id="myModalLabel">Add Employee</h4>
</div>
<div class="modal-body" id="hello">
<form>
<div class="form-group">
<label for="EmployeeId">ID</label>
<input type="text" class="form-control" id="EmployeeID" placeholder="Id" disabled="disabled"/>
</div>
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" placeholder="Name"/>
</div>
<div class="form-group">
<label for="Age">Age</label>
<input type="text" class="form-control" id="Age" placeholder="Age" />
</div>
<div class="form-group">
<label for="State">State</label>
<input type="text" class="form-control" id="State" placeholder="State"/>
</div>
<div class="form-group">
<label for="Country">Country</label>
<input type="text" class="form-control" id="Country" placeholder="Country"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button>
<button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
here's my Script code
//function for updating employee's record
function Update() {
var res = validate();
if (res == false) {
return false;
}
var empObj = {
EmployeeID: $('#EmployeeID').val(),
Name: $('#Name').val(),
Age: $('#Age').val(),
State: $('#State').val(),
Country: $('#Country').val(),
};
$.ajax({
url: "/Home/Update",
data: JSON.stringify(empObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
loadData();
$('#myModal').modal('hide');
window.location.reload();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
this is my fuction for clearing the textbox box but it miraculously not working on the edit/updated button.
//Function for clearing the textboxes
function clearTextBox() {
$('#EmployeeID').val("");
$('#Name').val("");
$('#Age').val("");
$('#State').val("");
$('#Country').val("");
$('#btnUpdate').hide();
$('#btnAdd').show();
}
And this is for my edit and delete
//Load Data function
function loadData() {
$.ajax({
url: "/Home/List",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.EmployeeID + '</td>';
html += '<td>' + item.Name + '</td>';
html += '<td>' + item.Age + '</td>';
html += '<td>' + item.State + '</td>';
html += '<td>' + item.Country + '</td>';
html += '<td>Edit | Delete</td>';
html += '</tr>';
});
$('.tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}

pop up form data not insert in database

I'm trying to insert data to my PHP using ajax post method.I have passed the first form data to hidden value in first script , but data is not inserted in database.Now I want to pass those variables (response.lastname, response.firstname ) into my database.Please help me to solve this issue. Any example will be very useful.. thank u in advance.
php ajax
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div> <form role="form" id="add_name" method="post" enctype="multipart/form-data" action="">
<div class="modal-body">
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname" name="lname" ></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname" name="fname"></td>
</tr>
<tr><td>name</td>
<td><input type="text" name="nam"></td>
</tr> </table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" >Cancel</button>
<button type="submit" class="btn btn-success" id="submit" name="submit"><i class="glyphicon glyphicon-inbox"></i> Submit</button>
</div>
</div>
</form><div id="response"></div>
<script>
$(document).ready(function(){
$('#submitBtn').click(function() {
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
var fname = $('#firstname').val();
$('#fname').val(fname);
alert(fname);
var laname = $('#lastname').val();
$('#lname').val(laname);
alert(laname);
});
});
</script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var lname = $('#lname').val();
var fname = $('#fname').val();
alert(lname);
$.ajax({
url:"insert.php",
method:"POST",
data:$('#add_name').serialize(),
beforeSend:function(){
$('#response').html('<span class="text-info">Loading response...</span>');
},
success:function(data){
$('form').trigger("reset");
$('#response').fadeIn().html(data);
setTimeout(function(){
$('#response').fadeOut("slow");
}, 5000);
}
});
});
});
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "demoss");
$name = mysqli_real_escape_string($connect, $_POST["lname"]);
$message = mysqli_real_escape_string($connect, $_POST["fname"]);
$query = "INSERT INTO tbl_form(name, message) VALUES ('".$name."', '".$message."')";
if(mysqli_query($connect, $query))
{
echo '<p>You have entered</p>';
echo '<p>Name:'.$name.'</p>';
echo '<p>Message : '.$message.'</p>';
}
?>
Try This:
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<form role="form" id="add_name" method="post">
<div class="modal-body">
<table class="table">
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" id="lname"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" id="fname"></td>
</tr>
<tr>
<td>name</td>
<td>
<input type="text" name="name" id="name">
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" id="submit">
<i class="glyphicon glyphicon-inbox"></i> Submit</button>
</div>
</div>
</form>
<div id="response"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#submit').click(function () {
var lname = $('#lname').val();
var fname = $('#fname').val();
alert(lname);
$.ajax({
method: "POST",
url: "insert.php",
data: $('#add_name').serialize(),
beforeSend: function () {
$('#response').html('<span class="text-info">Loading response...</span>');
},
success: function (data) {
$('form').trigger("reset");
$('#response').fadeIn().html(data);
setTimeout(function () {
$('#response').fadeOut("slow");
}, 5000);
}
});
});
});
</script>
data:$('#add_name').serialize(), - this convert inputs / textareas in form to one string for url. Your form not have inputs. Try
alert($('#add_name').serialize()) or<br>
alert($('#add_name').serialize().toSource()) // firefox <br>
And, may be second problem, if you call two times $(document).ready, may be rewrite first code with second. Combine to one $(document).ready.<br>
$(document).ready(function(){ callfunction1(); callfunction2(); }

Fill form with table row data using 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;
}
});
}

Categories