JavaScript — функция JS для кнопки не работает

У меня есть страница php, которая показывает таблицу записей, и в одном из столбцов у меня есть кнопка «Печать»:

<td>
<input type="button" class="btn-print" value="Print" id="printrec">
</td>

У меня есть файл javascript, добавленный в php:

<script type="text/javascript" src="js/logic.js"></script>

Функция в logic.js:

$(document).ready(function() {
// Print selected record's entry form
$('#printrec').click(function() {
alert("Print btn pressed");
});
});

Другие кнопки на странице работают, вызывая соответствующую функцию js по ID, но ничего не происходит, когда я нажимаю «Печать». Есть идеи?

редактировать
searchEntries.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Adobe GoLive" />
<title>Contest Entry Search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/logic.js"></script>
</head>
<body>
<form>
<input type="text" id="entry-number" class="form-control" placeholder="Entry # (separate multiple entries with commas)" value="" name="con-year" />
<input type="button" id="formsearch" class="btn btn-default" value="Search" />
</form>
<table id="show-entries">
<tr class="tbhead">
<th> Select </th>
<th style="display:none"> ID </th>
<th> Entry # </th>
<th> Barcode </th>
<th> Entrant Name </th>
<th> Title of Entry </th>
<th> Category </th>
<th> Paid </th>
<th> Date Paid </th>
<th> Date Created </th>
<th> Date Last Updated </th>
<th> Last Updated By </th>
<th> Print </th>
</tr>
</table>
</body>
</html>

searchentries.php

<?php
.
.
.
$stmt = $conn->prepare($sql);
$stmt->execute($params);

if ($stmt->rowCount() > 0) {
// Loop through resultset and add to JSON object
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row = $stmt->fetch()) {
$json[] = $row;
}
// Return encoded JSON object to logic.js
echo json_encode($json);
} else {
echo "NoResults";
}

logic.js

$(document).ready(function() {

var check="checklist";
var unCheck ="unchecked-list";
var cantCheck ="cantCheck";

//select all button
$('#selectall').click(function() {
if(this.checked) {
//checked here
$('#show-entries .unchecked-list').prop('checked', true);
$('#show-entries .unchecked-list').attr('class', 'checklist');
}
else {
//unchecked here
$('#show-entries .checklist').prop('checked', false);
$('#show-entries .checklist').attr('class', 'unchecked-list');
}
});

//checking checkbox
$(document).on('change','.checklist, .unchecked-list',function() {
if(this.checked) {
//checked here
$(this).attr('class', 'checklist');
}
else {
//unchecked here
$(this).attr('class', 'unchecked-list');
}
});

$('#formsearch').click(function() {

//getting values of text boxes
var  contestYear= $('#contest-year').val();
var  entryNumber= $('#entry-number').val();
var  barCode= $('#barcode').val();
var  firstName= $('#first-name').val();
var  lastName= $('#last-name').val();
var  title= $('#title-name').val();

//remvoing previous row
$('.child').remove();

$.ajax({
type: "POST",
url: "php/searchreceive.php",
data:{"c_year": contestYear, "e_number": entryNumber, "bCode":barCode, "fName":firstName, "lName": lastName, "title":title}

}).done(function(status) {
status=status.trim();
if(status=="NoResults") {
alert("No records found - please try again.");
}
else {
var result = JSON.parse(status);
var p;
var paidOp;

for(var i=0; i<result.length; i++) {
// Loop through each record in 'status'

//getting date paid
var datePaid =result[i]["DatePaid"];
if(datePaid==null) {
datePaid = "";
}

//getting yes no for paid
p = result[i]["Paid"].trim();
if(p==1) {
paidOp="Yes";
}
else {
paidOp="";
//datePaid="";
}

//getting date created
var dateCreated =result[i]["DateCreated"];
if(dateCreated==null) {
dateCreated = "";
}

//getting date last updated
var dateUpdated =result[i]["DateLastUpdated"];
if(dateUpdated==null) {
dateUpdated = "";
}

//getting last updated by
var updatedBy =result[i]["LastUpdatedBy"];
switch(updatedBy) {
case "wf_boxoffice":
updatedBy = "Box Office";
break;
case "wf_anon":
updatedBy = "Entrant";
}

$('#show-entries').append('<tr class="child"><td ><input type="checkbox" class='+unCheck+'  id='+result[i]["ID"]+'></td>\
<td style="display:none">'+result[i]["ID"]+'</td>\
<td>'+result[i]["Entry_Form_Number"]+'</td>\
<td>'+result[i]["Barcode_Text"]+'</td>\
<td>'+result[i]["Entrant_Name"]+'</td>\
<td>'+result[i]["Model_Name"]+'</td>\
<td>'+result[i]["Category_Name"]+'</td>\
<td>'+paidOp+'</td>\
<td>'+datePaid+'</td>\
<td>'+dateCreated+'</td>\
<td>'+dateUpdated+'</td>\
<td>'+updatedBy+'</td>\
<td><input type="button" class="btn-print"  value="Print" id="printrec"/></td>\n\
</tr>');

//checking paid or not  and disabling checkbox if FALSE
if(result[i]["Paid"]==1) {
//disabling unpaid checkboxes
$('#'+result[i]["ID"]).prop('disabled', true);

//changing classs name of unchecked
$('#'+result[i]["ID"]).attr('class', 'cantCheck');
}
}
}
});
});

// Proceed button click
$('#paid').click(function() {
//getting ids of checkboxes
var idArray = [];
$('.checklist').each(function () {
idArray.push(this.id);
});

if(idArray.length>0) {
//call ajax for updating rows
$.ajax({
type: "POST",
url: "php/updatepaid.php",
data:{idArray:idArray}

}).done(function(status) {
status=status.trim();
alert(status);
window.location.href = '../index.php';
});
}
else {
alert("No row selected");
}
});

// Reset all data
$('#formreset').click(function() {
//remvoing table rows
$('.child').remove();
});

// Print selected record's entry form
$('#printrec').click(function() {
alert("Print btn pressed");
});
});

Редактировать # 2 — logic.js

$(document).ready(function() {

setTimeout(function(){
addClickHandlers('.printrec');
}, 1000);

var check="checklist";
var unCheck ="unchecked-list";
var cantCheck ="cantCheck";

//select all button
$('#selectall').click(function() {
if(this.checked) {
//checked here
$('#show-entries .unchecked-list').prop('checked', true);
$('#show-entries .unchecked-list').attr('class', 'checklist');
}
else {
//unchecked here
$('#show-entries .checklist').prop('checked', false);
$('#show-entries .checklist').attr('class', 'unchecked-list');
}
});

//checking checkbox
$(document).on('change','.checklist, .unchecked-list',function() {
if(this.checked) {
//checked here
$(this).attr('class', 'checklist');
}
else {
//unchecked here
$(this).attr('class', 'unchecked-list');
}
});

$('#formsearch').click(function() {

//getting values of text boxes
var  contestYear= $('#contest-year').val();
var  entryNumber= $('#entry-number').val();
var  barCode= $('#barcode').val();
var  firstName= $('#first-name').val();
var  lastName= $('#last-name').val();
var  title= $('#title-name').val();

//remvoing previous row
$('.child').remove();

$.ajax({
type: "POST",
url: "php/searchreceive.php",
data:{"c_year": contestYear, "e_number": entryNumber, "bCode":barCode, "fName":firstName, "lName": lastName, "title":title}

}).done(function(status) {
status=status.trim();
if(status=="NoResults") {
alert("No records found - please try again.");
}
else {
var result = JSON.parse(status);
var p;
var paidOp;

for(var i=0; i<result.length; i++) {
// Loop through each record in 'status'

//getting date paid
var datePaid =result[i]["DatePaid"];
if(datePaid==null) {
datePaid = "";
}

//getting yes no for paid
p = result[i]["Paid"].trim();
if(p==1) {
paidOp="Yes";
}
else {
paidOp="";
//datePaid="";
}

//getting date created
var dateCreated =result[i]["DateCreated"];
if(dateCreated==null) {
dateCreated = "";
}

//getting date last updated
var dateUpdated =result[i]["DateLastUpdated"];
if(dateUpdated==null) {
dateUpdated = "";
}

//getting last updated by
var updatedBy =result[i]["LastUpdatedBy"];
switch(updatedBy) {
case "wf_boxoffice":
updatedBy = "Box Office";
break;
case "wf_anon":
updatedBy = "Entrant";
}

$('#show-entries').append('<tr class="child"><td ><input type="checkbox" class='+unCheck+'  id='+result[i]["ID"]+'></td>\
<td style="display:none">'+result[i]["ID"]+'</td>\
<td>'+result[i]["Entry_Form_Number"]+'</td>\
<td>'+result[i]["Barcode_Text"]+'</td>\
<td>'+result[i]["Entrant_Name"]+'</td>\
<td>'+result[i]["Model_Name"]+'</td>\
<td>'+result[i]["Category_Name"]+'</td>\
<td>'+paidOp+'</td>\
<td>'+datePaid+'</td>\
<td>'+dateCreated+'</td>\
<td>'+dateUpdated+'</td>\
<td>'+updatedBy+'</td>\
<td><input type="button" class="btn-print printrec" value="Print"/></td>\n\
</tr>');

//checking paid or not  and disabling checkbox if FALSE
if(result[i]["Paid"]==1) {
//disabling unpaid checkboxes
$('#'+result[i]["ID"]).prop('disabled', true);

//changing classs name of unchecked
$('#'+result[i]["ID"]).attr('class', 'cantCheck');
}
}
}
});
});

// Proceed button click
$('#paid').click(function() {
//getting ids of checkboxes
var idArray = [];
$('.checklist').each(function () {
idArray.push(this.id);
});

if(idArray.length>0) {
//call ajax for updating rows
$.ajax({
type: "POST",
url: "php/updatepaid.php",
data:{idArray:idArray}

}).done(function(status) {
status=status.trim();
alert(status);
window.location.href = '../index.php';
});
}
else {
alert("No row selected");
}
});

// Reset all data
$('#formreset').click(function() {
//remvoing table rows
$('.child').remove();
});
});

function addClickHandlers(identifier) {
$(identifier).click(function() {
data = "";
$(this).parents('tr').children().each(function() {
data += $(this).text() + " ";
});
alert("Print btn pressed from " + data);
});
}

Правка № 3
Мне нужно только значение из первого столбца таблицы, чтобы передать в файл php, но так как это скрытый столбец, я не могу использовать .text () следующим образом:

data = $(this).parents('tr').find("td:first").text();

Есть ли другой способ получить одно значение столбца только из строки, если она скрыта? Решение отлично работает для получения всех значений столбца, даже первого скрытого, но, похоже, оно не работает само по себе.

-3

Решение

Вот минимальная попытка того, чего вы, возможно, пытаетесь достичь:

Использование PHP для генерации кнопки:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#printrec').click(function() {
alert("Print btn pressed");
});
});
</script>
</head>
<body>
<?php
echo '<table>'.
'<tr>'.
'<td>'.
'<input type="button" class="btn-print" value="Print" id="printrec">'.
'</td>'.
'</tr>'.
'</table>';
?>
</body>
</html>

Использование простого HTML для генерации кнопки:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#printrec').click(function() {
alert("Print btn pressed");
});
});
</script>
</head>
<body>
<table>
<tr>
<td>
<input type="button" class="btn-print" value="Print" id="printrec">
</td>
</tr>
</table>
</body>
</html>

Можете ли вы проверить код по приведенному фрагменту?

Обновление 1: после того, как ОП опубликовал больше деталей в комментариях.

Если HTML-ввод добавляется динамически, тогда вызовите функцию addClickHandlers () с идентификатором HTML-ввода, с которым вы хотите связать событие click. Посмотрите на приведенный ниже фрагмент для примера.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setTimeout(function(){
addClickHandlers('#printrec');
}, 3000);
});
function addClickHandlers(id) {
$(id).click(function() {
alert("Print btn pressed");
});
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input type="button" class="btn-print" value="Print" id="printrec">
</td>
</tr>
</table>
</body>
</html>

Обновление 2: после ОП выложено больше подробностей в комментариях и оригинальном посте.

$(document).ready(function() {
setTimeout(function(){
addClickHandlers('.printrec');
addClickHandlers('.printrec');
}, 1000);
});
function addClickHandlers(identifier) {
$(identifier).off("click");
$(identifier).click(function() {
data = "";
$(this).parents('tr').children().each(function() {
data += $(this).text() + " ";
});
alert("Print btn pressed from " + data);
});
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table border="1">
<tr>
<td>
Row 1 Data 1
</td>
<td>
Row 1 Data 2
</td>
<td>
Row 1 Data 3
</td>
<td>
<input type="button" class="btn-print printrec" value="Print">
</td>
</tr>
<tr>
<td>
Row 2 Data 1
</td>
<td>
Row 2 Data 2
</td>
<td>
Row 2 Data 3
</td>
<td>
<input type="button" class="btn-print printrec" value="Print">
</td>
</tr>
</table>
</body>
</html>
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector