Javascript, pass values to new added table row/cell - javascript

basically the objective of this request is to have a modal table that adds new table row/cells and pass the value of "var OBGyneID = $(this).attr("id"); " to first cell and value of "var billing_id = newID;" to second cell whenever new rows/cells is/are added. Seeking your help, thanks!
* MY MODAL*
<div id="myModal" class="modal fade card new-contact myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="card profile">
<div class="profile__img">
<img src="img/profile2.jpg" alt="">
</div>
<div class="profile__info">
<h3 style="text-transform:capitalize;" id="pxname" name="pxname"></h3>
<ul class="icon-list">
<li>LAST <p name="consdates" id="consdates"></p></li>
<li>Last visit: </li>
<li><i class="zmdi zmdi-twitter"></i> #mallinda-hollaway</li>
</ul>
</div>
</div>
<div>
<div class="table-responsive">
<table id="billingTable" class="table table-inverse table-sm table-hover table-condensed" style="font-size:120%">
<thead>
<th>OBDYID</th>
<th>CK</th>
<th>PROCEEDURE</th>
<th>AMOUNT</th>
</thead>
<tbody id="billing_body" style="text-transform:capitalize;">
<form method="get" id="insert_form">
<tr>
<td width="10%"><input type="text" style="width:100%;" id="OBGyneID" name="OBGyneID"></td>
<td width="10%"><input type="text" style="width:100%;" id="AssessMentEntryID" name="AssessMentEntryID"></td>
<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" id="ExamDesc" name="ExamDesc"></td>
<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" id="Price" name="Price"></td>
</tr>
</form>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
<input type="submit" id="addRow" value="add" name="add" class="btn btn-info" />
<button type="button" class="btn btn-link" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
* MY JS to add new rows/cells*
$(document).ready(function () {
$("#addRow").click(function () {
$("#billingTable").append('<tr><td width="10%"><input type="text" style="width:100%;" id="OBGyneID" name="OBGyneID" ></td>'+
'<td width="10%"><input type="text" style="width:100%;" id="AssessMentEntryID" name="AssessMentEntryID"></td>'+
'<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" id="ExamDesc" name="ExamDesc"></td>'+
'<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" id="Price" name="Price"></td></tr>');
jQuery(".ExamDesc").autocomplete({
source: 'php/billingentry.php'
});
});
});
* Pass values to Modal * this will only pass value when modal pops-up but cant pass value whenever new rows/cells are added.
$(document).on('click', '.billing_data', function(){
var OBGyneID = $(this).attr("id");
var newID = new Date().getUTCMilliseconds();
var billing_id = newID;
$.ajax({
url:"php/billing_fetch.php",
method:"GET",
data:{OBGyneID: OBGyneID},
dataType:"json",
success:function(data){
$('#AssessMentEntryID').val(data.AssessMentEntryID);
$('#ExamDesc').val(data.ExamDesc);
$('#Price').val(data.Price);
$('#pxservice').val(data.pxservice);
$('#companyname').val(data.companyname);
$('#chiefcomplain').val(data.chiefcomplain);
document.getElementById("OBGyneID").value = OBGyneID;
document.getElementById("AssessMentEntryID").value = billing_id;
document.getElementById("pxname").innerHTML = (data.fname)+" "+(data.mi)+" "+(data.lname);
document.getElementById("consdates").innerHTML = (data.obgyneDate);
$('#myModal').modal('show');
}
});
});

whenever you are adding a new row HTML in billing table, you are using the same id for OBGyneID, AssessMentEntryID,ExamDesc and Price. And if you added two rows, DOM will not be able to work properly as there are multiple same ids out there. So I will suggest you to replace that with class and use class name to set values. Check below code:
$(document).ready(function () {
$("#addRow").click(function () {
$("#billingTable").append('<tr><td width="10%"><input type="text" style="width:100%;" class="OBGyneID" name="OBGyneID" ></td>'+
'<td width="10%"><input type="text" style="width:100%;" class="AssessMentEntryID" name="AssessMentEntryID"></td>'+
'<td width="60%"><input type="text" style="width:100%;" class="ExamDesc" type="text" name="ExamDesc"></td>'+
'<td width="20%"><input type="text" style="width:100%;" class="Price" type="text" name="Price"></td></tr>');
jQuery(".ExamDesc").autocomplete({
source: 'php/billingentry.php'
});
});
});
One you have added HTML code, then you can find out last row of billingTable and can set vales in that. Check below code:
$(document).on('click', '.billing_data', function(){
var OBGyneID = $(this).attr("id");
var newID = new Date().getUTCMilliseconds();
var billing_id = newID;
$.ajax({
url:"php/billing_fetch.php",
method:"GET",
data:{OBGyneID: OBGyneID},
dataType:"json",
success:function(data){
$("#billingTable").find(".AssessMentEntryID:last").val(data.AssessMentEntryID);
$("#billingTable").find(".ExamDesc:last").val(data.ExamDesc);
$("#Price").find(".Price:last").val(data.Price);
$("#billingTable").find(".consdates:last").html(data.obgyneDate);
//and so on
$('#myModal').modal('show');
}
});
});
Also, I would suggest you to use HTMl template tag for making clone for row. Appending HTML in JS is not a recommended way. Hope it helps you.

Related

jQuery validation on dynamic table form not working on using blur

I am creating form dynamically which has n rows (coming from array having n elements). Form fields have two type of columns (text & number) which I have given different id.
Although JQuery validation is working but "validate parts button" is not responding correctly. From the code condition it should not be enabled in case text is not valid.
Thanks..!
<div class="container-sm">
<div class="col-md-12 text-center">
<input class="btn btn-outline-primary" type="button" onclick = "buildTagPartsTable()" id="partNum" style="height:40px; width:220px" value="Enter Form Details#">
</div>
</div>
<div class="container-sm">
<div class="row">
<form id = "partsQuantForm">
<div class="col-lg-12" style="width:700px;overflow:auto; max-height:400px;">
<div class="partsTagsForm">
<table class="table table-striped" id="validTagsParts" style="width:100%;">
<thead>
<tr>
<th>Valid Row</th>
<th>Part </th>
<th># </th>
<th>Part </th>
<th># </th>
</tr>
</thead>
<tbody id="tagsPartsTable"></tbody>
</table>
</div>
<div class="col-md-12 text-center">
<input class="btn btn-outline-primary" type="button" id="tagsParts" style="height:40px; width:220px" value="Validate Parts ">
</div>
</div>
</form>
</div>
</div>
<script>
function buildTagPartsTable(){
validTagsInfo = ['Row1', 'Row2', 'Row3', 'Row4', 'Row5'];
var table = "<table>";
for (let key in validTagsInfo) {
table += `<tr>
<td>${validTagsInfo[key]}</td>
<td><input type="text" class="form-control" id = "partInfo" name="partInfo[0]" style="width:5em" minlength="5" maxlength="5" ></td>
<td><input type="number" class="form-control" id = "partQuantInfo" name="partQuantInfo[0]" style="width:3em" minlength="1" maxlength="1"></td>
<td><input type="text" class="form-control" id = "partInfo" name="partInfo[1]" style="width:5em" minlength="5" maxlength="5"></td>
<td><input type="number" class="form-control" id = "partQuantInfo" name="partQuantInfo[1]" style="width:3em" minlength="1" maxlength="1"></td>
</tr>`;
}
table += "</table>";
document.getElementById("tagsPartsTable").innerHTML = table;
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('input').on('blur', function() {
if ($("#partsQuantForm").valid()) {
$('#tagsParts').prop('disabled', false);
} else {
$('#tagsParts').prop('disabled', true);
}
});
jQuery("#partsQuantForm").validate({
rules: {
'partInfo[]': {
required: true,minlength: 5,maxlength: 5
},
'partQuantInfo[]': {
required: true,minlength: 2,maxlength: 2
}
}
});
});
</script>

Laravel, javascript add rows table class select not working

I have this code which works fine. my problem is that when i go to add one or more rows in the table with the button
the select:
<select name = "product_id_product []" id = "product_id_product '. $ request-> count_product.'" class = "form-control js-select2" required>
it is as if it does not take the "js-select2" class
if instead I insert it manually in the index bypassing the whole class it works
I just can't figure out how to do it ..
index.blade:
<div class="card-body" style="text-align: center;">
<button type="button" name="aggiungi_prodotto" id="aggiungi_prodotto" class="btn btn-primary aggiungi_prodotto" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Prodotto</button>
<button type="button" name="aggiungi_accessorio" id="aggiungi_accessorio" class="btn btn-success aggiungi_accessorio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Accessorio</button>
<button type="button" name="aggiungi_servizio" id="aggiungi_servizio" class="btn btn-warning aggiungi_servizio" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Servizio</button>
<button type="button" name="aggiungi_riga" id="aggiungi_riga" class="btn btn-danger aggiungi_riga" style="visibility: visible;"><i class="mdi mdi-playlist-plus"></i>Aggiungi Riga</button> <br/><br/><br/>
<div class="form-row">
<div class="table-responsive">
<table class="table table-hover ">
<thead>
<tr>
<th width="50%">Prodotto</th>
<th width="10%">Quantità</th>
<th width="10%">Acconto</th>
<th width="10%">Costo</th>
<th width="10%">Sconto TOT</th>
<th width="10%">Azioni</th>
</tr>
</thead>
<tbody id="prodottiRows">
</tbody>
</table>
</div>
</div>
<hr>
</div>
Javascript:
var count_prodotto = 0;
$(document).on('click', '#aggiungi_prodotto', function(){
count_prodotto = count_prodotto + 1;
var categorieID = document.getElementById('categorie_id').value;
var brandID = document.getElementById('brand_id').value;
var modelloID = document.getElementById('modello_id').value;
$.ajax({
type: 'POST',
url: "{{ route('autocomplete.fetch_prodotti') }}",
data: {
'_token': $('input[name=csrf-token]').val(),
'categorie_id':categorieID,
'brand_id':brandID,
'modello_id':modelloID,
'count_prodotto':count_prodotto
},
success:function(data){
$('#prodottiRows').append(data);
}
});
});
Controller:
public function fetch_prodotti(Request $request)
{
$products = Product::with('Multitenantable')
->where("stato_prodotto",'1')
->where("categorie_id",$request->categorie_id)
->where("brand_id",$request->brand_id)
->where("modello_id",$request->modello_id)
->pluck("nome_prodotto","id");
$prodotti = '
<tr id="row_prodotto'.$request->count_prodotto.'">
<td><select name="product_id_prodotto[]" id="product_id_prodotto'.$request->count_prodotto.'" class="form-control js-select2" required>
<option value="">Seleziona Prodotto</option>';
foreach ($products as $key => $product) {
$prodotti .= '<option value="'.$key.'">'.$product.'</option>';
# code...
}
$prodotti .='</select></td>
<td><input type="text" name="quantita_prodotto[]" id="quantita_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="acconto_prodotto[]" id="acconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="costo_prodotto[]" id="costo_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td><input type="text" name="sconto_prodotto[]" id="sconto_prodotto'.$request->count_prodotto.'" class="form-control" value="0" required /></td>
<td data-column="Rimuovi"><button type="button" name="remove_prodotto" id="'.$request->count_prodotto.'" class="btn btn-danger btn-xs remove_prodotto">Rimuovi</button></td>
</tr>';
return response()->json($prodotti);
}

best approach in adding a comma to a number like 123,456.78 in jquery

found this solution in this solution
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
in this link add commas to a number in jQuery
I am trying to apply it in my project. it works in one column but it doesn't work in price and sub total
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
var rowCount = 1;
$('#add').click(function() {
rowCount++;
$('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]" for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});
// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
getTotalCost($(this).attr("for"));
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr('id');
$('#row'+button_id+'').remove();
});
// Using a new index rather than your global variable i
function getTotalCost(ind) {
var qty = $('#quantity_'+ind).val();
var price = $('#product_price_'+ind).val();
var totNumber = (qty * price);
var tot = totNumber.toFixed(2);
tot = commaSeparateNumber(totNumber);
$('#total_cost_'+ind).val(tot);
calculateSubTotal();
}
function calculateSubTotal() {
var subtotal = 0;
$('.total_cost').each(function() {
subtotal += parseFloat($(this).val());
});
$('#subtotal').val(commaSeparateNumber(subtotal));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-12">
<div class="line line-dashed line-lg pull-in"></div>
<div class="row">
<table class="table table-bordered" id="orders">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Total Cost</th>
<th>
</th>
</tr>
<tr>
<td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
<td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
<td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
<td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
</tr>
</table>
<input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>
</div>
</div>
<div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
<div class="col-md-12 nopadding">
<div class="col-md-4 col-md-offset-4 pull-right nopadding">
<div class="col-md-8 pull-right nopadding">
<div class="form-group">
<td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
</div>
</div>
<div class="col-md-3 pull-right">
<div class="form-group">
<label>Subtotal</label>
</div>
</div>
</div>
</div>
</body>
</html>
Thank you so much in advance!
The problem is that parseFloat fails to correctly parse the value from the total cost textbox because it contains one or more ,. You need to remove the , from the string before parsing to float. You can remove any ,'s by calling .replace(/,/g,'') on the textbox value in the calculateSubTotal function.
It seems that for some values the function commaSeparateNumber doesn't work as expected. I removed it from the snippet below and replaced it with toLocaleString() which takes parameters for locale and minimum/maximum fraction digits .toLocalString("en-US", { maximumFractionDigits: 2}). Set the locale to one you know uses , to separate thousands. If you know that won't be an issue you can pass undefined for the locale.
Your snippet has been updated below:
var rowCount = 1;
$('#add').click(function() {
rowCount++;
$('#orders').append('<tr id="row'+rowCount+'"><td><input class="form-control product_price" type="number" data-type="product_price" id="product_price_'+rowCount+'" name="product_price[]" for="'+rowCount+'"/></td><input class="form-control" type="hidden" data-type="product_id" id="product_id_'+rowCount+'" name="product_id[]" for="'+rowCount+'"/><td><input class="form-control quantity" type="number" class="quantity" id="quantity_'+rowCount+'" name="quantity[]" for="'+rowCount+'"/> </td><td><input class="form-control total_cost" type="text" id="total_cost_'+rowCount+'" name="total_cost[]" for="'+rowCount+'" readonly/> </td><td><button type="button" name="remove" id="'+rowCount+'" class="btn btn-danger btn_remove cicle">-</button></td></tr>');
});
// Add a generic event listener for any change on quantity or price classed inputs
$("#orders").on('input', 'input.quantity,input.product_price', function() {
getTotalCost($(this).attr("for"));
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr('id');
$('#row'+button_id+'').remove();
});
// Using a new index rather than your global variable i
function getTotalCost(ind) {
var qty = $('#quantity_'+ind).val();
var price = $('#product_price_'+ind).val();
var totNumber = (qty * price);
// .toLocaleString
var tot = totNumber.toLocaleString("en-US", { maximumFractionDigits: 2});
$('#total_cost_'+ind).val(tot);
calculateSubTotal();
}
function calculateSubTotal() {
var subtotal = 0;
$('.total_cost').each(function() {
// replace ',' here
subtotal += parseFloat($(this).val().replace(/,/g,''));
});
// toLocaleString
$('#subtotal').val(subtotal.toLocaleString("en-US", { maximumFractionDigits: 2}));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-12">
<div class="line line-dashed line-lg pull-in"></div>
<div class="row">
<table class="table table-bordered" id="orders">
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Total Cost</th>
<th>
</th>
</tr>
<tr>
<td><input class="form-control product_price" type='number' data-type="product_price" id='product_price_1' name='product_price[]' for="1"/></td> <!-- purchase_cost -->
<td><input class="form-control quantity" type='number' id='quantity_1' name='quantity[]' for="1"/></td>
<td><input class="form-control total_cost" type='text' id='total_cost_1' name='total_cost[]' for='1' readonly/></td>
<td><button type="button" name="add" id="add" class="btn btn-success circle">+</button></td>
</tr>
</table>
<input class="form-control" type='hidden' data-type="product_id_1" id='product_id_1' name='product_id[]'/>
</div>
</div>
<div class="line line-dashed line-lg pull-in" style="clear: both;"></div>
<div class="col-md-12 nopadding">
<div class="col-md-4 col-md-offset-4 pull-right nopadding">
<div class="col-md-8 pull-right nopadding">
<div class="form-group">
<td><input class="form-control subtotal" type='text' id='subtotal' name='subtotal' readonly/></td>
</div>
</div>
<div class="col-md-3 pull-right">
<div class="form-group">
<label>Subtotal</label>
</div>
</div>
</div>
</div>
</body>
</html>

Can Javascript be written in .edge file?

I just started learning Adonis.js and I would like to know if it's possible to write Javascript in an .edge file? I've found this tutorial (here) on how to add table row dynamically and I want to implement this in my Adonis.js project. I've add the coding inside a <script> tag, yet there's nothing happen when I clicked the 'Add' button. Does anyone know how to work this out? Or even have another solution on this?
Thank you in advance for the help.
#layout('main')
#section('content')
Go back
<hr>
<h1>Create Club</h1>
<form action="/clubs/create" method="POST">
{{ csrfField() }}
<div class="form-group">
<label>Club Name</label>
<input type="text" name="clubName" class="form-control" value="{{ old('clubName', '') }}">
{{ elIf('<span class="text-danger">$self</span>', getErrorFor('clubName'), hasErrorFor('clubName')) }}
</div>
<div class="form-group">
<label>Club Description</label>
<textarea name="clubDesc" class="form-control">{{ old('clubDesc', '') }}</textarea>
{{ elIf('<span class="text-danger">$self</span>', getErrorFor('clubDesc'), hasErrorFor('clubDesc')) }}
</div>
<br>
<table class="table order-list">
<thead>
<tr>
<td>Name</td>
<td>Position</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="memberName" class="form-control"/>
</td>
<td>
<input type="text" name="position" class="form-control"/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-sm btn-block" id="addrow" value="Add Member"/>
</td>
</tr>
</tfoot>
</table>
<button class="btn btn-primary" type="submit">Create!</button>
</form>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="memberName' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="position' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
</script>
#endsection
From the docs:
in order to write raw HTML, you must wrap it inside {{{ }}}
That suggests that you should be able to do*:
{{{
<script>
// .. JavaScript here
</script>
}}}
*There may be other - potentially better, ways. I've never used the templating engine before, but the above seems to accomplish what you are looking for.

Modal in Asp.NET MVC

I have a Asp.NET MVC application, i trying to use a modal to make the update of the data, i have two modal for Register and Update, the Register is OK, but the Update is not working, when a click on the "Alterar" button, need to open a modal with the data filled, i trying to use JavaScript to do this.
Can someone help me?
My table
My modal that need open filled with data
My Code
Table
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Produto</th>
<th>Custo</th>
<th>Lucro</th>
<th>Opcoes</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach(var sale in Model)
{
<tr>
<td>#Html.DisplayFor(model => sale.idProduct)</td>
<td>#Html.DisplayFor(model => sale.nameProduct)</td>
<td>#Html.DisplayFor(model => sale.costProduct)</td>
<td>#Html.DisplayFor(model => sale.profitProduct)</td>
<!--Get values to put on Modal-->
<td><a class="update" data-toggle="modal" href="#updateModal" data-id="#sale.idProduct" data-name="#sale.nameProduct"
data-cost="#sale.costProduct" data-profit="#sale.profitProduct"><span class="glyphicon glyphicon-edit">Alterar</span></a></td>
</tr>
}
}
</tbody>
</table>
enter code here
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var $this = $(this);
var idProduct = $this.data('id');
var nameProduct = $this.data('name');
var costProduct = $this.data('cost')
var profitProduct = $this.data('profit')
$('#nameProduct').text(nameProduct);
$('#costProduct').text(costProduct);
$('#profitProduct').text(profitProduct);
$("#updateModal #form_update #idProduct").val(idProduct);
$('#updateModal').modal();
});
});
Modal
<div id="updateModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal">×</button>
<h4 class="modal-title">Alterar Produto<span id="name_product"></span></h4>
</div>
<form method="post" id="form_update" action="/Dashboard/Product">
<div class="modal-body">
<div class="form-group">
<input type="hidden" name="idProduct" id="idProduct" class="form-control" placeholder="ID do produto"/>
<input type="text" name="nameProduct" id="nameProduct" class="form-control" placeholder="ID do produto" required />
<input type="text" name="costProduct" id="costProduct" class="form-control" placeholder="Custo do Produto" required />
<input type="text" name="profitProduct" id="profitProduct" class="form-control" placeholder="Lucro do Produto" required />
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" value="Atualizar" />
<button type="button" class="btn btn-warning" data-dissmiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
to change the value of input you need to use val() :
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var $this = $(this);
var idProduct = $this.data('id');
var nameProduct = $this.data('name');
var costProduct = $this.data('cost')
var profitProduct = $this.data('profit')
$('#nameProduct').val(nameProduct);
$('#costProduct').val(costProduct);
$('#profitProduct').val(profitProduct);
$("#updateModal #form_update #idProduct").val(idProduct);
$('#updateModal').modal();
});
});
Your modal contains only inputs.
For setting the value of input you used $('#nameProduct').text(nameProduct) and that's the wrong thing. You need the val() method.
$('#nameProduct').val(nameProduct);
.text() method is used specially for div, span, etc.
UPDATE
<td>#Html.DisplayFor(model => sale.idProduct)</td> generates a span with the follow properties: id and name have value idProduct. The problem is that you have two elements with same id(in table and in modal). id attribute must be unique in DOM.
Modal
<div id="updateModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal">×</button>
<h4 class="modal-title">Alterar Produto<span id="name_product"></span></h4>
</div>
<form method="post" id="form_update" action="/Dashboard/Product">
<div class="modal-body">
<div class="form-group">
<input type="hidden" class="form-control modalInput" placeholder="ID do produto"/>
<input type="text" class="form-control modalInput" placeholder="ID do produto" required />
<input type="text" class="form-control modalInput" placeholder="Custo do Produto" required />
<input type="text" class="form-control modalInput" placeholder="Lucro do Produto" required />
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" value="Atualizar" />
<button type="button" class="btn btn-warning" data-dissmiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var modal=$('#updateModal');
var idInput = modal.find('input.modalInput').eq(0);
var nameInput = modal.find('input.modalInput').eq(1);
var costInput = modal.find('input.modalInput').eq(2);
var profitInput = modal.find('input.modalInput').eq(3);
idInput.val($(this).data('id'));
nameInput .val($(this).data('name'));
costInput.val($(this).data('cost'));
profitInput .val($(this).data('profit'));
modal.modal();
});
});
</script>
HTML
foreach(var sale in Model)
{
<tr>
<td>#Html.DisplayFor(model => sale.idProduct)</td>
<td>#Html.DisplayFor(model => sale.nameProduct)</td>
<td>#Html.DisplayFor(model => sale.costProduct)</td>
<td>#Html.DisplayFor(model => sale.profitProduct)</td>
<!--Get values to put on Modal-->
<td><a class="update" data-id="#sale.idProduct" data-name="#sale.nameProduct" data-cost="#sale.costProduct" data-profit="#sale.profitProduct"><span class="glyphicon glyphicon-edit">Alterar</span></a></td>
</tr>
}
you must use val().You use like a text("asda").you change these problem resolve

Categories

Resources