on click event not working after first on click event. - javascript

I am a newbie to jquery. I have a page where I have two buttons. One of them is edit button, and the other one is delete button. When I click edit button it removes these two button and at the same place( the place where delete and edit button were before) I add three elements one of them is "save" button. This save button has a class - "save-btn". I select this button by jquery class selector. And onclick it should do something. But when I click nothing happens. Can anyone suggest whats wrong and give a solution. Thanks in advance.
<div class="container-fluid">
<div class="row">
<div class="col-md-2 "></div>
<div class="col-md-4 ">
<div class="form-tile">
<form action="" method="post">{% csrf_token %}
{% crispy form %}
</form>
</div>
</div>
<div class="col-md-4 tile">
<div class="row">
<div class="col-md-12">
<h2 style="margin-top: 0px;padding-top: 0px;text-align: center">Today's Purchase</h2>
</div>
</div>
<div class="row">
<table class="table table-hover">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td><button class="btn btn-primary edit-btn"><i class="fa fa-pencil-square-o"></i></button>
<button class="btn btn-danger delete-btn"><i class="fa fa-trash"></i></button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="col-md-2 "></div>
</div>
And here is my javascript
<script>
$(function(){
$(".edit-btn").click(function(){
var custom_form = '<td><input type="text" size="10"></td><td><input type="text" size="10"></td> <td><button class="btn btn-primary save-btn">Save</i></button> </td>'
var parent = $(this).parent().parent().html(custom_form);
});
$(".save-btn").click(function(){
alert("asnlas");
});
});
</script>

when you create an element you must assign the event at the same time
Try this....
$(function(){
$(".edit-btn").click(function(){
var custom_form = '<td><input type="text" size="10"></td><td><input type="text" size="10"></td> <td><button class="btn btn-primary save-btn">Save</i></button> </td>'
var parent = $(this).parent().parent().html(custom_form);
$(".save-btn").click(function(){
alert("asnlas");
});
});
});

Related

How can I pass the values of the relevant row into the modal when a click event occurs on a table?

When a click event occurs on a table, I want to pass the values of the relevant row into the modal. I wrote a code like this, but the values of the top row are always passed into the modal. What I want to do is to show the values in the row I clicked in the modal. How can I provide this?
my table codes here:
<table class="table align-middle" id="customerTable">
<thead class="table-light">
<tr>
<th class="sort" data-sort="name">Name Surname</th>
<th class="sort" data-sort="company_name">Phone Number</th>
<th class="sort" data-sort="leads_score">Note</th>
<th class="sort" data-sort="phone">Status</th>
<th class="sort" data-sort="location">Personal Name</th>
<th class="sort" data-sort="tags">Data Name</th>
<th class="sort" data-sort="action">Edit</th>
</tr>
</thead>
<tbody class="list form-check-all">
{% for x in model %}
<tr>
<td class="table-namesurname">{{x.name}}</td>
<td class="table-phonenumber">{{x.phonenumber}}</td>
<td class="table-note">{{x.note}}</td>
<td class="table-status">{{x.status}}</td>
<td class="table-callname">{{x.callname}}</td>
<td class="table-dataname">{{x.dataname}}</td>
<td>
<ul class="list-inline hstack gap-2 mb-0">
<li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Edit">
<a class="edit-item-btn" id="call-button" href="#showModal" data-bs-toggle="modal" data-id="{{x.id}}"><i class="ri-phone-line fs-16"></i></a> <!-- Here is the edit button -->
</li>
</ul>
</td>
</tr>
{% endfor %}
</tbody>
</table>
my modal here
<div class="modal fade" id="showModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-light p-3">
<h5 class="modal-title" id="exampleModalLabel"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="close-modal"></button>
</div>
<form action="">
<div class="modal-body">
<input type="hidden" id="id-field" />
<div class="row g-3">
<div class="col-lg-12">
<div>
<label for="company_name-field" class="form-label">Name Surname</label>
<input type="text" id="call-name-surname" class="form-control" placeholder="Enter company name" value="" required />
</div>
</div>
<div class="col-lg-12">
<div>
<label for="company_name-field" class="form-label">Phone Number</label>
<input type="email" id="call-phone-number" class="form-control" placeholder="Enter company name" value="" required />
</div>
</div>
<!--end col-->
<div class="col-lg-12">
<div>
<label for="leads_score-field" class="form-label">Note</label>
<input type="text" id="call-note-field" class="form-control" placeholder="Enter lead score" value="" required />
</div>
</div>
<!--end col-->
<div class="col-lg-12">
<div>
<label for="phone-field" class="form-label">Status</label>
<input type="text" id="call-status-field" class="form-control" placeholder="Enter phone no" value="" required />
</div>
</div>
<div class="col-lg-12">
<div>
<label for="phone-field" class="form-label">Personal Name</label>
<input type="text" id="call-persnoel-name" class="form-control" placeholder="Enter phone no" value="" required />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="hstack gap-2 justify-content-end">
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Kapat</button>
<button type="submit" class="btn btn-success" id="add-btn">Kaydet</button>
</div>
</div>
</form>
</div>
</div>
</div>
and the my script codes
<script type="text/javascript">
$(document).ready(function () {
$("#call-button").click(function() {
var nameSurname = $(this).closest('tr').find('.table-namesurname').text();
var phoneNumber = $(this).closest('tr').find('.table-phonenumber').text();
var note = $(this).closest('tr').find('.table-note').text();
var status = $(this).closest('tr').find('.table-status').text();
var callName = $(this).closest('tr').find('.table-callname').text();
var dataName = $(this).closest('tr').find('.table-dataname').text();
$("#call-name-surname").val(nameSurname)
$("#call-phone-number").val(phoneNumber)
$("#call-note-field").val(note)
$("#call-status-field").val(status)
$("call-persnoel-name").val(callName)
});
});
</script>
console output
Gökan 905387532589 <empty string> Aranmadı ece datatest
The problem here is that the values of the clicked element in the table are not coming. Whichever I click, the values of the element at the top of the table are displayed. How can I solve this problem?
HTML id attribute should be unique, adding multiple elements with the same id, when you select, you will only get the first element that has this id, you need to select the rows by class, you have edit-item-btn class for the button.
<script type="text/javascript">
$(document).ready(function () {
$(".edit-item-btn").click(function() {
var nameSurname = $(this).closest('tr').find('.table-namesurname').text();
var phoneNumber = $(this).closest('tr').find('.table-phonenumber').text();
var note = $(this).closest('tr').find('.table-note').text();
var status = $(this).closest('tr').find('.table-status').text();
var callName = $(this).closest('tr').find('.table-callname').text();
var dataName = $(this).closest('tr').find('.table-dataname').text();
$("#call-name-surname").val(nameSurname)
$("#call-phone-number").val(phoneNumber)
$("#call-note-field").val(note)
$("#call-status-field").val(status)
$("call-persnoel-name").val(callName)
});
});

How to display data in the same column of two fields of the model depending on the option chosen from the radio button in Django?

I have a question. It turns out that I have a form that when you click on a radio button, certain inputs are enabled, and when you click on another radio button option, other inputs appear.
The inputs save different information depending on the option you chose in the radio buttons, for example, in one input you have to put the name of the person, in another input it is the name of the corporation.
When displaying the information in the list, I would like a column to say 'Name' and either the client name or the corporation name to appear. I would not like to place two columns, one that says client name and another corporation name, but in only one that says name, they appear. How can I do that?
This is how i have my html
and this is how I would like it to be
html
<form method="post">
{% csrf_token %}
<div class="d-flex justify-content-between">
<a href="{% url 'Clientes:clientes_add' %}">
<button type="button" class="btn btn-success mb-3 waves-effect waves-light" onclick="addNewCustomer()">Add new</button>
</a>
<div class="col-md-6 mb-3 d-flex align-items-center">
<label class="m-0 col-md-2 text-right">Date range: </label>
<input type="date" name="fromdate" class="form-control">
<input type="date" name="todate" class="form-control">
<input type="submit" value="Search" class="btn btn-light">
</div>
</div>
<div class="card">
<div class="card-body">
{% if clientes %}
<div class="table-rep-plugin">
<div class="table-responsive mb-0" data-pattern="priority-columns">
<table id="tech-companies-1" class="table">
<thead>
<tr>
<th>Customer ID</th>
<th data-priority="1">Customer type</th>
<th data-priority="1">Name</th>
<th data-priority="1">Corporation Name</th>
<th>Register since</th>
<th data-priority="1">Actions</th>
</tr>
</thead>
<tbody>
{% for cliente in clientes %}
<tr>
<td>{{cliente.id}}</td>
<td>{{cliente.tipo}}</td>
<td>{{cliente.nombre}}</td>
<td>{{cliente.corporacion}}</td>
<td>{{cliente.fecha_registro}}</td>
<td>
<i class="uil-search-alt font-size-18"></i>
</td>
<td>
<i class="uil-edit-alt font-size-18"></i>
</td>
<td>
<i class="uil uil-trash-alt font-size-18"></i>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endif %}
</div>
</form>
model.py
class Clientes(models.Model):
tipo = models.CharField(max_length=200)
corporacion=models.CharField(max_length=200,blank=True)
nombre = models.CharField(max_length=200, blank=True)
def __str__(self):
return f'{self.nombre}'
forms.py
TIPO = (
('Corporativo', 'Corporativo'),
('Persona', 'Persona'),
)
class ClientesForm(forms.ModelForm):
tipo = forms.ChoiceField(
choices=TIPO,
widget=forms.RadioSelect(attrs={'class':'custom-radio-list'}),
)
class Meta:
model = Clientes
fields = ['tipo','nombre','corporacion']
widgets = {
'corporacion': forms.TextInput(
attrs={
'class': 'form-control'
}
),
'nombre': forms.TextInput(
attrs={
'class': 'form-control'
}
),
}

Laravel re-show modal with same data when validation error

I have Table showing data from database inside each row there is a button
opening a modal with the current clicked row id like following:
<tbody>
#foreach($receivedShipments as $shipment)
<tr>
<th class="text-center" scope="row">
{{ $loop->iteration }}
</th>
<td class="font-w600 font-size-sm">
<button type="button" class="btn btn-sm btn-light js-tooltip-enabled push"
data-toggle="modal" data-target="#modal_handle_national_id" data-id="{{$shipment->id}}"
data-original-title="{{trans('validation.attributes.deliver_to_receiver_customer')}}">
{{trans('validation.attributes.deliver_to_receiver_customer')}}</button>
</td>
</tr>
#endforeach
</tbody>
the Modal modal_handle_national_id is :
<div class="modal fade" id="modal_handle_national_id" >
<div class="modal-content">
<form class="js-validation" id="handleForm" action="" method="POST">
#csrf
#if(count($errors)>0)
<div class="alert alert-danger ">
<ul>#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<input type="text" class=" col-xl-8" id="receiver_customer_nationalId"
name="receiver_customer_nationalId"
value="{{ old('receiver_customer_nationalId') }}">
<button type="submit">Submit</button>
</form>
</div>
</div>
i have script to hadle the action link of the form according to clicked button row id:
<script>
#if (count($errors) > 0)
$('#modal_handle_national_id').modal('show');
#endif
$('#modal_handle_national_id').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
$('#handleForm').attr("action", "");
var id = button.data('id');
var url = '{{ route("shipments.handle", ":id") }}';
url = url.replace(':id', id);
$('#handleForm').attr("action", url);
});
</script>
i need the modal to be re-showed with the same old clicked button id when there is a Laravel validation error
Any Help please?
You can use hidden.bs.modal event:
This event is fired when the modal has finished being hidden from the
user (will wait for CSS transitions to complete).
The snippet:
$('#modal_handle_national_id').on('hidden.bs.modal', function(e) {
$(this).find('form').trigger('reset');
})

Put minimum length in jquery?

I am trying to make an minimum length in my plugin live search in jquery. I am done doing the live search that connected to my table when I searched. But i would like to put some validation through my live search, like the user must input minimum of 3 characters before the search will begin.. I tried to put the minlength through my js but its not working.. Any suggestion why?
View
#extends('layout.default')
#section('content')
<br><br>
<br><br>
<div class="container">
<h4>Live Search using Laravel</h4>
<div class="col-md-6 col-lg-6 pull-right" >
<p class="pull-right">Click on the zip logo to download the file:<p>
<a href="/live_search_laravel.zip" download="live-search(laravel).zip">
<br><br>
<img border="0" src="/images/ziplogo.png" class="pull-right" alt="AngularJS" width="50" height="42">
</a>
</div>
</div>
<br>
<div class="col-md-12 col-sm-6 col-xs-12">
<div class="x_panel">
<div class="x_content">
<table class="search-table table table-hover">
<thead>
<tr>
<th>
Original File Name
</th>
<th>
Change File Name
</th>
<th>
File Extension
</th>
<th>
Image
</th>
<th>
Category
</th>
<th>
Status
</th>
</tr>
</thead>
<tbody>
#foreach($data as $file)
<tr>
<td>{{ $file->original_filename}}</td>
<tD>{{ $file->rs_filename}}</td>
<td>{{ $file->file_extension}}</td>
<td><img src = "files/images/{{ $file->rs_filename}}"></td>
<td>#if($file->category=="1"){{ "Laravel" }}#endif</td>
<td>
#if($file->status=="0")
<form action="/activateImage/{{ $file->id}}" method="post">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button type="submit" class="btn btn-primary">Activate</button>
</form>
#else
<form action="{{ url('deactivateImage', ['id' => $file->id]) }}" method="post">
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<button type="submit" class="btn btn-primary">Deactivate</button>
</form>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<h4>All Activated Images using Foreach</h4>
#foreach($data as $file)
#if($file->status=="1")
<div class ="row">
<div class ="form-group">
<img src="/files/images/{{ $file->rs_filename }} " width ="50px" height ="50px">
</div>
</div>
#endif
#endforeach
<h4>All Images using the index</h4>
<div class ="row">
<div class ="form-group">
<img src="/files/images/{{ $data[0]['rs_filename']}} " width ="50px" height ="50px">
</div>
</div>
<div class="col-md-6 col-lg-4 pull-right">
<img src="/files/images/{{ $data[1]['rs_filename']}} " width ="50px" height ="50px">
</div>
#stop
#section('select2_js')
<script type="text/javascript" src="/js/live_search_laravel/select2.js"></script>
#stop
The plugin js
/**
**options to have following keys:
**searchText: this should hold the value of search text
**searchPlaceHolder: this should hold the value of search input box placeholder
**/
(function($){
$.fn.tableSearch = function(options){
if(!$(this).is('table')){
return;
}
var tableObj = $(this),
searchText = (options.searchText)?options.searchText:'Search: ',
searchPlaceHolder = (options.searchPlaceHolder)?options.searchPlaceHolder:'',
divObj = $('<div style="font-size:20px;">'+searchText+'</div><br /><br />'),
inputObj = $('<input style="min-width:25%;max-width:50%;margin-left:1%" type="text" placeholder="'+searchPlaceHolder+'" />'),
caseSensitive = (options.caseSensitive===true)?true:false,
searchFieldVal = '',
pattern = '';
inputObj.off('keyup').on('keyup', function(){
searchFieldVal = $(this).val();
if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function(){
var currentRow = $(this);
currentRow.find('td').each(function(){
if(pattern.test($(this).html())){
currentRow.show();
return false;
}
});
});
}
});
tableObj.before(divObj.append(inputObj));
return tableObj;
}
}(jQuery));
My JS
$(document).ready(function(){
$('table.search-table').tableSearch({
searchText:'Search:'
});
});

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

Categories

Resources