There is jquery dialog (#dialog-message1) where table (tableINFO) is append.
Each row of the table shows some information regarding product with a picture link in last column.
I would like to create an on-click event where some actions are taken i.e. table row deletion and (potrawy1Engine.php) script call.
I tried creating (.confirmation2),but it does not work as expected - link is followed instead.
Can somebody help me and advice on the js script, please?
What I would like to do is to delete a row in the table tableINFO, where a link was clicked after it was clicked.
.confirmation1 and .confirmation work fine, only .confirmation2 does not work.
Maybe the problem is that the table and the link are created dynamically in jquery?
Here is the js:
$("#dialog-message").hide();
$('.confirmation').on('click', function(e) {
e.preventDefault();
var lnk = $(this).attr('href');
$("#dialog-message").dialog({
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
window.location.href = lnk;
},
Anuluj: function() {
$(this).dialog("close");
}
}
});
});
$("#dialog-message1").hide();
$('.confirmation1').on('click', function(e) {
e.preventDefault();
var lnk = $(this).attr('href');
var product_name = $(this).parents("tr").find("td").first().html();
$( "#dialog-message1" ).hide();
$( "#dialog-message1 table" ).remove();
$( "#dialog-message1 #labelINFO" ).remove();
$("#dialog-message1").append("<table id='tableINFO'> </table>");
$("#dialog-message1 table").append("<tr><th width='350px' >Nazwa produktu</th><th width='70px'>Waga (g)</th><th width='100px'>Kalorie (Kcal)</th> <th width='80px'>Białko (g)</th> <th width='90px'>Tłuszcze (g)</th><th width='120px'>Węglowodany (g)</th><th width='30px'> </th> </tr>");
$.ajax({
method: "POST",
url: "potrawyINFOEngine.php",
data: {"nazwa": product_name},
}).done(function( data ) {
var result = $.parseJSON(data);
var len = result.length;
for(var i=0; i<len; i++){
var T_nazwaproduktu = result[i].produkt;
var T_waga = result[i].waga;
var T_kalorie = result[i].kalorie;
var T_bialko = result[i].bialko;
var T_tluszcze = result[i].tluszcze;
var T_weglowodany = result[i].weglowodany;
var tr_str = "<tr>" +
"<td align='left'>" + T_nazwaproduktu + "</td>" +
"<td align='right'>" + T_waga + "</td>" +
"<td align='right'>" + T_kalorie + "</td>" +
"<td align='right'>" + T_bialko + "</td>" +
"<td align='right'>" + T_tluszcze + "</td>" +
"<td align='right'>" + T_weglowodany + "</td>" +
"<td align='center'>" +
"<a href='usunProduktPotrawa.php?nazwaPotrawy=" + product_name + "&nazwaProduktu=" + T_nazwaproduktu + "' title='Usuń produkt' class='confirmation2'><img src='pictures/cross16.jpg' width='10' height='10' style='margin: 0px 0px' /></a>" ;
"</td>" +
"</tr>";
$("#dialog-message1 table").append(tr_str);
}
console.log(data);
});
$.ajax({
method: "POST",
url: "potrawyINFOOpisEngine.php",
data: {"nazwa": product_name},
}).done(function( data ) {
var result = $.parseJSON(data);
console.log(result);
$("#dialog-message1").append("<label id='labelINFO'>" + result + "</label>");
$( "#dialog-message1" ).show();
});
$("#dialog-message1").dialog({
height: "auto",
width: 950,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
$( "#dialog-message1 table" ).remove();
$( "#dialog-message1 #labelINFO" ).remove();
}
}
});
});
$("#dialog-message2").hide();
$('.confirmation2').on('click', function(e) {
e.preventDefault();
var lnk = $(this).attr('href');
var product_name = $(this).parents("tr").find("td").first().html();
$( "#dialog-message2" ).hide();
$.ajax({
method: "POST",
url: "potrawy1Engine.php",
data: {"nazwa": product_name},
}).done(function( data ) {
var result = $.parseJSON(data);
console.log(result);
$( "#dialog-message2" ).show();
});
$("#dialog-message2").dialog({
height: "auto",
width: 450,
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
});
HTML part is here:
<div id="dialog-message" title="Usuwanie potrawy">
<p>
<span class="ui-icon ui-icon-help" style="float:left; margin:0 7px 50px 0;"></span>Czy chcesz usunąć wybraną potrawe?
</p>
<p>
Naciśnij OK aby kontynuować.
</p>
</div>
<div id="dialog-message1" title="Składniki i opis potrawy">
</div>
<div id="dialog-message2" title="Test">
</div>
Thanks in advance for your help.
Related
Before I use it DateTimePicker everything was working fine, but after adding some javascript code for datetimepicker I am getting ArgumentNullException for
#Html.DropDownListFor(x => x.LeagueId, new SelectList(ViewBag.Leagues, "Id", "LeagueType"), "", new { #class = "form-control", id="liga" }), first player is added successfully but when I want to one more, my application crashes.
Input for date
<div class="form-group">
<label asp-for="Player.Birth" class="control-label">#DbResHtml.T("Датум на раѓање","Resources")</label>
<input asp-for="Player.Birth" type="text" class="form-control datepicker" required id="birth" />
<span asp-validation-for="Player.Birth" class="text-danger"></span>
</div>
After adding this lines of code my app crashes
<script>
$(document).ready(function() {
$.datetimepicker.setDateFormatter('moment');
$(".datepicker").datetimepicker({
timepicker: false,
format: 'DD/MM/YYYY',
});
})
</script>
Other scripts for Create page
<script>
$(document).ready(function() {
$('#select2-3').find('option').not(':selected').remove();
var count = 0;
$('#liga').on('change', function() {
var selectedText = $(this).find('option:selected').text();
var selectedVal = $(this).val();
var leagueAjax = $.ajax({
type: "POST",
url: "#Url.Action("GetClubsForLeague", "Player")",
data: {
id: selectedVal
},
success: function(data) {
if (count == 0) {
var s = '<option value="-1"></option>';
}
count++;
$('#select2-3').find('option').not(':selected').remove();
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
}
$('#select2-3').append(s);
var mycode = {};
$("select[id='select2-3'] > option").each(function() {
if (mycode[this.text]) {
$(this).remove();
} else {
mycode[this.text] = this.value;
}
});
},
error: function(req, status, error) {
ajaxErrorHandlingAlert("error", req.status);
}
})
})
})
</script>
<script>
$(document).ready(function() {
$('#select2-3').change(function() {
var cc = $('#select2-3').val();
var ids = [];
for (let i = 0; i < cc.length; i++) {
ids.push(cc[i]);
}
$.ajax({
type: "POST",
url: "#Url.Action("GetClubsById","Player")",
data: { "ids": ids },
success: function(data) {
console.log(data);
$('#clubsTBody tr').remove();
var counter = 1;
for (let i = 0; i < data.length; i++) {
$("#clubsTBody").append("<tr><td>" + counter + "</td>"
+ "<td>" + data[i].name + "</td>"
+ "<td>" + data[i].league.leagueType + "</td>"
+ "<td>" + '<button class="mb-1 btn bg-danger fas fa-trash-alt deleteBtn" title=#DbResHtml.T("Delete", "Resources")></button>' + "</td>"
+ "</tr >");
counter++;
}
},
error: function(req, status, error) {
console.log(msg);
}
});
})
$('#clubs').on('click', '.deleteBtn', function() {
$(this).parents('tr').remove();
var value = $(this).closest('tr').children('td:eq(1)').text();
$(`#select2-3 option:selected:contains("${value}")`).prop("selected", false).parent().trigger("change");
});
})
</script>
I am debugging for 3 days, but still nothing.
I have problem inserting modal button inside my html table. I'm using AJAX and append built in function. I tried this approach
" Open modal"
but it did'nt work. I tried to remove the button properties like 'class', 'type' , etc and it worked but I need those. Any approach for this. Thank you.
This is my code
<script type=text/javascript>
$(document).ready(function() {
});
function getData(id){
$('#myModal').modal('show');
$.ajax({
type: "GET",
url: "getproducts/",
dataType: 'json',
data: {id: id},
success: function (response) {
var len = 0;
if(response['data'] !=null){
len = response['data'].length;
}
$('#userTable tbody').empty();
if(len > 0){
for(i = 0; i < len; i++) {
var p_id = response['data'][i].p_id;
var p_name = response['data'][i].p_name;
var p_amount = response['data'][i].p_amount;
var m_fname = response['data'][i].m_fname;
var tr_str =
"<tr>" +
"<td>" + p_id + "</td>"+
"<td>" + p_name + "</td>" +
// HOW CAN I ADD MODAL BUTTON HERE THIS APPROACH DOESN'T WORKED
"<td> <button type="button" class="btn btn-primary" data-bs-toggle="modal"
data-bs-target="#myModal2">Open modal</button></td>"
"<tr>";
$('#userTable tbody').append(tr_str);
}
}
}
});
};
</script>
Expected output should be like this
I think the problem with string concatenation
I am giving a code. please replace it.
"<td> <button type='button' class='btn btn-primary' data-bs-toggle='modal'
data-bs-target='#myModal2'>Open modal</button></td>"
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I am working for dynamic table from a jquery/ajax function that will display a list of files depending on the clicked category.
Once the list of file is displayed, the user can click on table row (checkbox will also be checked) to display/preview the file but the row can't have a jquery event.
I have tried it on a plain html table with the function below and it worked.
What could be the solution for this?
function directoryAction(obj){
var directory = obj.value
var editDer = directory.replace("./","");
$(".content-main").html("<button class='btn btn-default'><i class='fa fa-folder-o'></i></button>"+
"<button class='btn btn-default' value='"+ directory +"' onclick='addDocument(this);'><i class='fa fa-upload'></i></button>");
$(".content-main").append("<h5>"+editDer+"</h5>");
$(".content-main").append("<table class='record_table'>"+
"<thead>"+
"<tr>"+
"<th class='check'><input type='checkbox' class='form-control '/></th>"+
"<th>File Name</th>"+
"<th>Uploader</th>"+
"<th>Date Modefied</th>"+
"</tr>"+
"</thead>"+
"<tbody class='fileTbody'></tbody></table");
var dataString = "directory=" + directory + "&getFileInDirectory="
$.ajax({
url: "main.php",
type: "GET",
data: dataString,
dataType: "json",
contentType: false,
cache: false,
processData: false,
success:function(data){
var id = 0;
$.each(data,function(i,element){
var fName = element.namef;
var uploader = element.uploader;
var datestamp = element.datestamp;
var fileId = element.id;
$(".fileTbody").append("<tr class='clickRow' id='"+ id + "'><td><input id='file"+ id +"' type='hidden' value='"+ fileId +"'>"+
"<input type='checkbox' id='chk"+ id + "' class='form-control'/></td>"+
"<td>"+ fName +"</td><td>"+uploader+"</td><td>"+datestamp+"</td></tr>");
id++;
});
}
});
}
$(function(){
$(document).ready(function() {
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
});
Change from
$('.record_table tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
to
$('body').on('click', '.record_table tr', function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
or
$('.content-main').on('click', '.record_table tr', function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
This is code i have written to get checkbox value and add rows
can anyone have look on this and find what's the problem with this code
$('.dm_list_data').on('change', function() {
var $sel = $(this);
val = $(this).val();
$opts = $sel.children();
prevUnselected = $sel.data('unselected');
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
var currSelected = $('.dm_list_data').val();
var post_data = {
'deliver_id': currSelected
}
console.log(post_data);
$.ajax({
type: "POST",
url: base_url + 'curriculum/topicadd/get_deliver_method_details',
data: post_data,
datatype: "JSON",
success: function(msg) {
var JSONObject = JSON.parse(msg);
JSONObject.forEach(function(element) {
var delivery_mtd_name = element.delivery_mtd_name;
var ftfl_hours = element.ftfl_hours;
var assessment_hours = element.assessment_hours;
var slt_hours = element.slt_hours;
var markup = "<tr><td><input type='text' name='record' value='" + delivery_mtd_name + "'></td><td><input type='text' name='record' value='" + ftfl_hours + "'></td><td><input type='text' name='record' value='" + assessment_hours + "'></td><td><input type='text' name='record' value='" + slt_hours + "'></td></tr>";
$("table tbody").append(markup);
});
}
});
});
Rows are getting multipe if i checked thrice please go through image
I will suggest create a hashmap which contains checked elements. Triggering Onchange will just update your hashmap and call a function to create/delete rows. hashmaps are way faster and easy to code.Make your keys as id of table row. Depending on check or uncheck condition, call function which is required.
Before you create a new element and append, just check whether it exists. If does not exist, then add it. Just add id for text box and if condition. Below code may have syntax error, i just tested in browser. Maybe little tweaks needed.
$('.dm_list_data').on('change', function() {
var $sel = $(this);
val = $(this).val();
$opts = $sel.children();
prevUnselected = $sel.data('unselected');
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
var currSelected = $('.dm_list_data').val();
var post_data = {
'deliver_id': currSelected
}
console.log(post_data);
$.ajax({
type: "POST",
url: base_url + 'curriculum/topicadd/get_deliver_method_details',
data: post_data,
datatype: "JSON",
success: function(msg) {
var JSONObject = JSON.parse(msg);
JSONObject.forEach(function(element) {
var delivery_mtd_name = element.delivery_mtd_name;
var ftfl_hours = element.ftfl_hours;
var assessment_hours = element.assessment_hours;
var slt_hours = element.slt_hours;
if($('#'+delivery_mtd_name).length==0)///added this line
{
//updated below line
var markup = "<tr><td><input type='text' name='record' value='" + delivery_mtd_name + "' id='" + delivery_mtd_name + "'></td><td><input type='text' name='record' value='" + ftfl_hours + "'></td><td><input type='text' name='record' value='" + assessment_hours + "'></td><td><input type='text' name='record' value='" + slt_hours + "'></td></tr>";
$("table tbody").append(markup);
}
});
}
});
});
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
In open cart I have a custom module - with ajax filter - when trying to use the filter i'm getting following errors.
<script type="text/javascript">
$("#btnForm").fancybox({
width: 1000,
height: 1050,
autoSize : false,
fitToView : false,
closeBtn : false,
maxWidth : '100%'
});
$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: <?php echo $max_price ?>,
values: [ <?php echo $start_price ?>, <?php echo $end_price ?> ],
slide: function( event, ui ) {
$( "#amount" ).val( "<?php echo $curr ?>" + ui.values[ 0 ] + " - <?php echo $curr ? >" + ui.values[ 1 ] );
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
clearTimeout(wto);
wto = setTimeout(function() {
filter();
}, 100);
}
});
$( "#amount" ).val( "<?php echo $curr ?>" + $( "#slider-range" ).slider( "values", 0 ) + " - <?php echo $curr ?>" + $( "#slider-range" ).slider( "values", 1 ) );
});
var wto;
$(".checkish").change(function() {
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
clearTimeout(wto);
wto = setTimeout(function() {
filter();
}, 100);
});
$("input[type='text']").change(function() {
$("#results").html('<img src="catalog/view/theme/pollishop2/image/ajax-loader.gif" />');
$("#pagination").html('');
filter();
});
function mrvidaloca(filter, page) {
$.ajax({
url: 'index.php?route=information/jewels/xml' + filter,
dataType: 'json',
success: function(json) {
all_jewels = json.all_jewels;
pagination = json.pagination;
doolittle = '';
$.each( all_jewels, function( key, value ) {
doolittle += '<div style="text-align:left;padding-bottom:10px;margin- right:1px;">';
doolittle += '<div class="image"><img src="' + value.image + '" /></div>';
doolittle += '<div class="name"><a style="font-size:16px;" href="' + value.view + '">' + value.title + '</a></div>';
doolittle += '<div class="description" style="display:block;">' + value.description + '</div>';
doolittle += '<div class="rating" style="right:10px;position:absolute;z-index:3;top:0;"><img src="catalog/view/theme/pollishop2/image/stars-' + value.rating + '.png" /></div>';
doolittle += '</div>';
});
if(doolittle){
$("#results").html(doolittle);
$("#pagination").html(pagination);
} else {
$("#results").html('<?php echo $no_results ?>');
$("#pagination").html('');
}
}
});
}
function filter(page) {
url = '';
var filter_named = $('#mans').find('input[name="searchjewellery"]').val();
if (filter_named) {
url += '&term=' + filter_named;
}
var filter_name = $('input[name=\'price\']').attr('value');
if (filter_name) {
filter_name = filter_name.replace(/<?php echo $curr ?>/g, '');
filter_name = filter_name.split(' ').join('');
filter_name = filter_name.split('-');
url += '&start_price=' + filter_name[0] + '&end_price=' + filter_name[1];
}
var filter_cat = $('input[name=\'cat\']').attr('value');
if (filter_cat) {
url += '&jewels_category_id=' + filter_cat;
}
var vali = [];
$('#god :checkbox:checked').each(function(i){
vali[i] = $(this).val();
});
lashes = vali.join(',');
if(lashes) {
url += '&difficulty=' + lashes;
}
var valio = [];
$('#bios :checkbox:checked').each(function(i){
valio[i] = $(this).val();
});
helium = valio.join(',');
if(helium) {
url += '&designer_id=' + helium;
}
if(page){
url += '&page=' + page;
} else {
url += '&page=1';
}
mrvidaloca(url,page);
}
</script>
Console shows:
GET http://test.risetea.co.uk/index.php?route=information/jewels/xml&start_price=$0&end_price=$500&jewels_category_id=5&difficulty=1&pa ge=1 500 (Internal Server Error)
jquery-1.8.3.min.js?j2v=2.3.3:2 v.support.ajax.v.ajaxTransport.send
jquery-1.8.3.min.js?j2v=2.3.3:2 v.extend.ajax
index.php?route=information/jewels&jewels_category_id=5:989 mrvidaloca
index.php?route=information/jewels&jewels_category_id=5:1054 filter
index.php?route=information/jewels&jewels_category_id=5:980 (anonymous function)`
It is not Javascript error. It is 500 (Internal Server Error) which means that you have problems on your server side.