How to create a simple edit button on crud? - javascript

i'm trying to make a simple Crud for my homework . most of my code works properly for the most part, except the edit button. it only edits the first row. below, i provide my TS code along with my HTML. for the HTML i'm using Modal windows. so everytime i click on the edit buttons. a modal will appears
function create() {
let user: string = String($("#username").val());
let data: JQuery = $("<tr id='crudData'><td>" + user + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crud").append(data);
}
function edit() {
let user2: string = String($("#username2").val());
let data2: JQuery = $("<tr id='crudData'><td>" + user2 + "</td><td><button class='btn btn-info' data-toggle='modal' data-target='#crudModal'>Bearbeiten</button></td></tr>");
$("#crudData").replaceWith(data2);
}
$("#userbstg").on("click", create);
$("#saveEdit").on("click", edit);
<section>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3 class="section-heading">Aufgabe - Usermanager</h3>
<label for="username">Username:</label>
<input id="username" class="form-control col-md-3" type="text">
<button id="userbstg" class="btn btn-info">Add</button>
<table id="crud" class="col-md-4 table">
<tr>
<th class="col-2" id="user">User</th>
<th class="col-2" id="edit"></th>
</tr>
</table>
</div>
</div>
</div>
<div class="modal fade" id="crudModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<label for="username2">Username:</label>
<input id="username2" class="form-control col-md-12" type="text">
<button type="button" id="saveEdit" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
</section>

Related

Javascript function works only on the first table row inside my foreach laravel loop

I am using a javascript functions to input a number and automatically display the result after calculation inside a boostrap modal.
If click the request button at the first row, javascript functions work well. But when I click on the request button on the second row and succeeding rows, it doesn't function.
I am not really sure if the problem is the data inside the modal or the data outside the modal
I tried to getElementsByClassName instead of ID but it still not working.
<script>
function mult(value) { // === calculate the profit and the total amount due === //
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit").value = x;
document.getElementById("total").value = y;
}
</script>
<table id="table1">
<thead>
<tr>
<th>#</th>
<th>Full Name</th>
<th>Requests</th>
</tr>
</thead>
<tbody>
#foreach($Clients as $Client)
<tr id="foreach-row">
<td>{{ $Client->full_name }}</td>
<td>
<div class="buttons">
<a class="btn icon btn-secondary" data-toggle="modal"
data-target="#LoanRequestModel-{{ $Client->id }}">
Request
</a>
</div>
</td>
</tr>
{{-- =========== MODEL - NEW REQUEST ===============--}}
<div class="modal" id="LoanRequestModel-{{ $Client->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><b>REQUEST</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('finance.storeRequest', $Client->id) }}" method="post"
class="loanrequest_form" enctype="multipart/form-data">
{{ csrf_field() }}
<label>Full name</label>
<div class="form-group">
<input type="text" name="creditor_full_name"
class="form-control" value="{{ $Client->full_name }}" >
</div>
<div>
<label>Amount</label>
<div class="form-group">
<input type="number" name="loan_amount"
class="form-control" onkeyup="mult(this.value);" >
</div>
</div>
<div class="row">
<div class="col-md-5">
<label>Interest Rate</label>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Choose</label>
<select class="form-select rate"name="interest_rate" >
<option value="15" selected>15%</option>
<option value="20">20%</option>
</select>
</div>
</div>
<div class="col-md-7">
<label>Profit</label>
<div class="input-group mb-3">
<input type="text" id="profit" class="form-control" name="profit"
aria-label="Amount">
</div>
</div>
</div>
<div class="row">
<label>Total Amount due</label>
<div class="input-group mb-3">
<input type="text" id="total" class="form-control" name="amount_due"
aria-label="Amount">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-outline-secondary ml-1" >
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endforeach
</tbody>
</table>
The problem - as others have said above - is that whilst you are making the ID of each modal unique using :
id="LoanRequestModel-{{ $Client->id }}"
within your loop, when generating each modal, you are using fields which have non-unique IDs :
type="text" id="profit"
type="text" id="total"
What you would be better off is making those IDs non-unique, in the same way that you did with the modal ID :
type="text" id="profit-{{ $Client->id }}"
type="text" id="total-{{ $Client->id }}"
and add IDs to the fields which you will need to use in your script that does not presently have one :
type="number" id="loan_amount-{{ $Client->id}}" name="loan_amount"
Then, when you trigger the javascript on keyup here :
onkeyup="mult(this.value);"
rather than pass the value of the field, pass the client ID :
onkeyup="mult({{ $Client->id);"
Then you just need to adjust your javascript (because it's no longer being passed the loan_amount) so that it first gets the loan_amount, then the other bits and pieces it needs, and finally returns them to the right place :
<script>
function mult(id) { // === this is now receiving the ID, not a value so first we need to get the value for the relevant field *emphasized text*== //
var value = document.getElementById("loan_amount-" + id).value
var x = value * 15 / 100;
var y = parseFloat(x)+parseInt(value);
document.getElementById("profit" + id).value = x;
document.getElementById("total" + id).value = y;
}
</script>

input hidden value doesn't send to controller

I'm trying post to my database,everything what i want i can get from my formcollection and my table but input hidden value.My main view is using #model List
Here is my code this my modal popup
#using (Html.BeginForm("update3", "UpdateInfo", FormMethod.Post))
{
<div class="modal fade" role="dialog" id="mymodal">
<form id="stok_formu">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button class="close" type="button" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modal2">
<div class="row">
<label for="names" id="name" name="name"></label>
<input type="hidden" id="names" name="names" />
</div><br />
<div class="row">
<div class="col-md-3">
#Html.Label(" Clothes codes: ")
</div>
<div class="col-md-3">
<input type="number" class="input-sm" id="codes" name="codes" />
</div>
</div><br />
<div class="row">
<div class="col-md-3">
#Html.Label("New Price : ")
</div>
<div class="col-md-3">
<input type="number" class="input-sm" id="newprice" name="newprice" />
</div>
</div>
<input class="btn btn-success" id="change" type = "submit" name="change"/>
</div>
</div>
</div>
</form>
</div>
}
With this javascript code ,i can get my "name" from my table and put on my modal and my problem is begin is here,when i click button submit modal popup doesn't send hidden value to controller but ican get my value of "newprice"
function metot(x) {
namee = document.getElementById("tablo2").rows[0].cells.item(0).innerHTML;
document.getElementById("name").innerHTML = namee;
}
and table from my main view
<tbody id="tablo2">
#foreach(var oge in Model)
{
<tr onclick="metot(this)">
<td>#Html.Encode(oge.name)</td>
<td id="codes">#Html.Encode(oge.codes)</td>
<td id="price">#Html.Encode(oge.price)</td>
<td>
<button id="change" onclick="metot(this)" type="button" data-toggle="modal" data-target="#mymodal" class="btn btn-warning tab-content"><span>Change</span></button>
</td>
</tr>
}
</tbody>
You are setting the text of the label with id name, but you aren't setting the value of the hidden field with id names, hence it is not sent when you submit the form. <label> elements do not send data back to the server.
This should work (I assume the variable namee should actually be called urun_adi):
function metot(x) {
urun_adi = document.getElementById("tablo2").rows[0].cells.item(0).innerHTML;
document.getElementById("name").innerHTML = urun_adi;
document.getElementById("names").value = urun_adi;
}

Call javascript function from modal popup button

I´m can´t make this work. Can anyone help me?
First I have a page that opens a modal popup like this:
<label class="h5"> <button id="btnPopup" name="btnPopup" type="button" class="btn-u-green" data-toggle="modal" data-target="#responsive">Clique aqui</button> <span id="txtEscolherEstabelecimento">para escolher o estabelecimento</span> </label>
<div class="modal fade bs-example-modal-lg" id="responsive" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="myModalLabel4">Escolha o Estabelecimento</h4> <input type="hidden" name="nuEstabelecimentoEscolhido" /> </div>
<div class="modal-body"> <div class="row">
<label class="label"> Qual o Estado?</label>
<div class="col-md-6">
<label class="select">
<select id="cmbUf" name="cmbUf" class="form-control">
<option value="0">::: Selecione :::</option>
<?php
$ufs = $objUfs->getUfs($objConexao);
while($ufs = $objConexao->converterResultado()){
?>
<option value="<?php echo $ufs['CoUf']?>"><?php echo $ufs['NoUf']?></option>
<?php }?>
</select>
<i></i>
</label>
</div> </div>
<div class="row">
<label class="label"> Digite o nome para pesquisa</label>
<div class="col-md-12">
<label class="input">
<i class="icon-append fa fa-search"></i>
<input type="text" id="NoEstabelecimentoPesquisa" name="NoEstabelecimentoPesquisa" placeholder="Digite o nome principal do Estabelecimento">
</label>
</div> </div>
<div class="modal-footer">
<button type="button" class="btn-u btn-u-default" id="btnPesquisarEstabelecimento" name="btnPesquisarEstabelecimento"><i class="fa fa-search"></i> Pesquisar</button> </div>
<table id="grdEstabelecimentosEncontrados" class="table" data-height="300" data-id-field="id" >
<thead style="font-size: 12px;" >
<tr>
<th data-field="Id" data-visible="false">Id</th>
<th data-field="NoEstabelecimento" data-visible="true">Nome</th>
<th data-field="NoTipoEstabelecimento" data-visible="true" >Tipo do Estabelecimento</th>
<th data-field="Endereco" data-visible="true">Endereço</th>
<th data-field="CidadeUf">Cidade/Uf</th>
<th data-field="Acao">Ação</th>
</tr>
</thead>
<tbody style="font-size: 12px"></tbody> </table>
</div>
<div class="modal-footer"> <button type="button" class="btn-u btn-u-default" data-dismiss="modal"><i class="fa fa-close"></i>Fechar</button> </div>
</div> </div>
After modal is opened I have a button on each line from table that I want to call a Javascript from the main page, each line look like this:
<tbody style="font-size: 12px">
<tr>
<td>1</td>
<td>Smaff Hyundai</td>
<td>Particular</td>
<td>Trecho SIA Trecho 1 - até 628 - lado par</td>
<td>Brasília</td>
<td><button id="button1" class="btn btn-success" type="button"><i class="fa fa-check-circle-o" onclick="SelectItem(1);"></i> Selecionar</button></td>
</tr>
</tbody>
Then I have thejavascript function I want to call:
function SelectItem(nuEstabelecimento) {
alert('Here' + nuEstabelecimento);
}
The row is added to table from another script that appends a row, like this:
$.each(dataJSON, function(idx, elem){
newTR = ('<tr>');
newTR += ('<td>'+elem.NuEstabelecimento+'</td>');
newTR += ('<td>'+elem.NoEstabelecimento+'</td>');
newTR += ('<td>'+elem.NoTipoEstabelecimento+'</td>');
newTR += ('<td>'+elem.Endereco+'</td>');
newTR += ('<td>'+elem.CidadeUf+'</td>');
newTR += ('<td><button id="button'+elem.NuEstabelecimento+'" class="btn btn-success" type="button"><i class="fa fa-check-circle-o" onclick="SelectItem(1);"></i> Selecionar</button></td>');
newTR += ('</tr>');
$('#grdEstabelecimentosEncontrados tbody').append(newTR);
});
Everything is work fine but the onclick button added don´t do anything and no error occurs on console.
Any Helps on that? Thanks!!!
Use event delegation instead of adding a click handler to every row:
$('#grdEstabelecimentosEncontrados').on('click', '.btn-success', function(e){
//this code will run for all current
//and future elements with the class of .btn-success
});

Not able to take data from table and set to bootstrap modal

I am working on a piece of code and since I dont have too much experience with jquery or javascript I need your help. I want to take the data from the row when button EditBtn is clicked and set those values to modal. I tried the code below but It was not working.
Below is my code
Table :
<table id="example" class="table table-bordered table-hover">
<thead>
<tr>
<th>Ödeme Türü</th>
<th>Ödeme Başlığı</th>
<th>İçerik</th>
<th>Son Ödeme Tarihi</th>
<th>Tutarı</th>
<th>Ödeme Durumu</th>
<th>Düzenle</th>
</tr>
</thead>
<tbody>
#foreach (OdemeList item in Model)
{
<tr id="#item.Odeme.OdemeID">
<td>#item.Odeme.OdemeType</td>
<td>#item.Odeme.OdemeTitle</td>
<td>#item.Odeme.OdemeContent</td>
<td>#item.Odeme.SonOdemeTarih</td>
<td>#item.Odeme.OdemeTutar</td>
#if (#item.KullaniciOdeme.isPay == true)
{
<td>Odendi</td>
}
else
{
<td>Odenmedi</td>
<td>
<form>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_6pRNASCoBOKtIshFeQd4XMUh"
data-amount="#item.Odeme.OdemeTutar"
data-name="#item.Odeme.OdemeTitle"
data-image="/Content/LoginCssJs/pay.png"
data-locale="auto">
</script>
</form>
</td>
#*<td>
<a data-toggle="modal" data-target=".bootstrapmodal3"><button class="btn btn-success">Öde</button></a>
</td>*#
}
<td>
<a data-toggle="modal" id="EditBtn" class="btn edit" data-target=".bootstrapmodal"><img src="#Url.Content("~/Content/Icons/edit.png")" alt="Düzenle" /></a>
</td>
<td>
<a data-toggle="modal" data-target=".bootstrapmodal2"><img src="#Url.Content("~/Content/Icons/Delete.png")" alt="Sil" /></a>
</td>
</tr>
}
</tbody>
</table>
My modal:
<div class="modal fade bootstrapmodal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button data-dismiss="modal" class="close"><span>×</span></button>
<div class="modal-title">
<h3>Ödeme Düzenle</h3>
</div>
</div>
<div class="modal-body">
<form>
<label>Ödeme Türü</label>
<select class="form-control" id="OdemeTuru">
<option>Aidat</option>
<option>Isınma</option>
<option>Bina Gideri</option>
</select><br />
<div class="form-group">
<label for="odemebasligi">Ödeme Başlığı</label>
<input type="text" class="form-control" id="odemebasligi" placeholder="OdemeTitle">
</div>
<div class="form-group">
<label for="comment">Ödeme içeriği</label>
<textarea class="form-control" rows="5" id="comment" placeholder="-OdemeContent"></textarea>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Tutar</label>
<div class="input-group">
<div class="input-group-addon">TL</div>
<input type="text" class="form-control" id="exampleInputAmount" placeholder="OdemeTutar">
<div class="input-group-addon">.00</div>
</div>
</div>
<div class="form-group">
<label for="odemetarihi">Son Ödeme Tarihi</label>
<input type="text" class="form-control" id="odemetarihi" placeholder="SonOdemeTarih">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary">Kaydet</button>
<button class="btn btn-danger" data-dismiss="modal"> Vazgeç</button>
</div>
</div>
</div>
</div>
Script:
<script>
$('a.edit').on('click', function() {
var myModal = $('.bootstrapmodal');
//// now get the values from the table
//var OdemeTuru = $(this).closest('tr').find('td.OdemeType').html();
var OdemeBaslik = $(this).closest('tr').find('td.OdemeTitle').html();
var OdemeIcerik = $(this).closest('tr').find('td.OdemeContent').html();
var OdemeTutar = $(this).closest('tr').find('td.SonOdemeTarih').html();
var SonOdemeTarihi = $(this).closest('tr').find('td.OdemeTutar').html();
//// and set them in the modal:
//$('#', myModal).val(OdemeTuru);
$('#odemebasligi', myModal).val(OdemeBaslik);
$('#comment', myModal).val(OdemeIcerik);
$('#exampleInputAmount', myModal).val(OdemeTutar);
$('#odemetarihi', myModal).val(SonOdemeTarihi);
// and finally show the modal
myModal.modal({ show: true });
return false;
});
</script>
In script you are targeting <td> class .find('td.OdemeTitle') and in table there are no class defined <td>#item.Odeme.OdemeTitle</td> what you only need is define class which you are targeting e.g
For
var OdemeBaslik = $(this).closest('tr').find('td.OdemeTitle').html();
HTML
<td class="OdemeTitle">#item.Odeme.OdemeTitle</td>
follow above example and set all <td> classes and you will be all set.
minimal fiddle example

JQuery unable to post dynamically added form elements

I have read the previous posts on this, but I can't seem to resolve my issue. I have a form that has static and dynamically created input fields. The static fields are being posted without issue. However, none of the dynamically created :inputs are coming across in the post request.
The form :
<div id="userModal" class="modal fade" style="display:none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="btn btn-primary" style="float:right;margin-bottom:4px;">Delete User
</button>
<h4 class="modal-title">Edit User : <span id="user_webUserProfilePrimaryName"></span></h4>
</div>
<div class="modal-body">
<span id="user_maintain_messages" name="user_maintain_messages"></span>
<form id="editUserForm" name="editUserForm">
<input type="hidden" name="user_maintain_action" id="user_maintain_action" value="update">
<input type="hidden" name="action" id="action" value="sc_admin_updateCustomerFundInfo">
<input type="hidden" name="version" id="version" value="1.1" ;
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="user_webUserLevel">User Level</label>
</div>
<div class="col-md-6">
<select class="form-control" id="user_webUserLevel" name="user_webUserLevel">
<option value="anonymous">Pending</option>
<option value="customer">Customer</option>
<option value="administrator">Admin</option>
<option value="superuser">Super</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="user_webUserProfileStatus">User Status</label>
</div>
<div class="col-md-6">
<select class="form-control" name="user_webUserProfileStatus"
name="user_webUserProfileStatus">
<option value="InReview">In Review</option>
<option value="Approved">Approved</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="user_verified">User Verified</label>
</div>
<div class="col-md-6">
<select class="form-control" id="user_verified" name="user_verified">
<option value="N">Not Verified</option>
<option value="Y">Verified</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-4">
<label for="webUserName">Send Login Confirmation</label>
</div>
<div class="col-md-6">
<span id="user_sendConfirmButton"></span>
</div>
</div>
</div>
<div class="row">
<table class="table" id="user_fundTable">
<thead>
<tr>
<th>Fund(s)</th>
<th>Account #</th>
<th>Administrator</th>
<th>Status</th>
</tr>
</thead>
<tfoot>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" style="background:grey;float:left" data-dismiss="modal">
Cancel
</button>
<button type="button" class="btn btn-primary" onclick="saveUserMaintain()">Update (confirm changes)
</button>
</div>
</div>
</div>
</div>
It is populated with the following data :
{"Result":"OK","Records":[{"webUserProfilePrimaryName":"Johnny Appleseed","verified":"N","webUserProfileId":"24","webUserLevel":"anonymous","webUserProfileStatus":"InReview","webUserProfileReferenceAccount":"19, 30, 3126, 0090","fund":[{"fundName":"PCF","fundFullName":"Private Capital Fund","fundAccess":"RO","fundAccNo":0,"latestStatement":"","fundManager":"","status":"Approved"},{"fundName":"CCIF","fundFullName":"Coast Capital Income Fund","fundAccess":"RO","fundAccNo":0,"latestStatement":"","fundManager":"","status":"Approved"},{"fundName":"SIF2","fundFullName":"Secured Income Fund","fundAccess":"RO","fundAccNo":0,"latestStatement":"","fundManager":"","status":"Approved"}],"sendConfirm":"<button class='btn btn-primary' onclick='sendConfirmEmail(\"24\")'>Email Now<\/button>"}]}
I use this function to populate my form :
function showUserMaintain(webUserProfileId) {
jQuery.post(stonecrestajax.ajaxurl, {
action: "sc_admin_getCustomerFundInfo",
webUserProfileId: webUserProfileId,
version: "1.1"
}, function (data) {
console.log(data['Records'][0]['webUserProfilePrimaryName']);
jQuery("#user_webUserProfilePrimaryName").html(data['Records'][0]['webUserProfilePrimaryName']);
jQuery("#user_webUserLevel").val(data['Records'][0]['webUserLevel']);
jQuery("#user_webUserProfileStatus").val(data['Records'][0]['webUserProfileStatus']);
jQuery("#user_verified").val(data['Records'][0]['verified']);
jQuery("#user_sendConfirmButton").html(data['Records'][0]['sendConfirm']);
jQuery('#user_fundTable tbody').empty();
jQuery.each(data['Records'][0]['fund'], function (fundIdx, fundValues) {
var fundStatusOptions = ["In Review", "New", "Approved"];
var combo = generateDropDownList(fundIdx, fundIdx, fundStatusOptions);
var row = '<tr><td>' + fundValues.fundName + '</td>';
row += '<td><input type="text" name="user_fundAccountNumber[]" id="user_fundAccountNumber_' + fundIdx + '" value="' + fundValues.fundAccNo + '"></td>';
row += '<td><input type="text" name="user_fundManagerName[]" id="user_fundManagerName_' + fundIdx + '" value="' + fundValues.fundManager + '"></td>';
row += '<td id="user_fundStatus_' + fundIdx + '" name="user_fundStatus_' + fundIdx + '"></td></tr>';
jQuery('#user_fundTable').append(row);
//jQuery("#user_fundStatus_" + fundIdx).append(combo);
//console.log(fundValues);
});
jQuery("#userModal").modal('show');
}, "json");
}
As you can see from the function I'm dynamically adding values to existing input fields and dynamically creating some input fields within a table that is within the form.
However, when I try to serialize (post) the form back to the server using this
function :
function saveUserMaintain() {
jQuery.ajax({
type: "POST",
url: url,
data: jQuery("#editUserForm").serialize(),
success: function (data) {
alert(data);
}
});
return false;
}
The only data I see coming across are the fields (inputs) I had statically defined, none of the "user_fundXXXXXX" fields are coming across in the post request.
I'm sure I'm just standing too far inside the box and can't see the obvious here, can anyone give me a hand ?

Categories

Resources