jquery $(this).data selector - javascript

// Rate videos start
$('[value="bad"]').click(function (e) {
console.log($(this));
alert($(this).data("primary"));
});
echo '<div class="carousel-inner">';
echo '<div class="item active">';
echo '<h4>' . $vid->VIDEO_NAME . '</h4>';
echo '<input type="text" class="" data-primary="' . $vid->ID . '" value="' . $vid->ID . '">';
echo '<video width="500" height="281" controls>';
echo '<source src="' . base_url() . $vid->VIDEO_URL . '" type="video/mp4">';
echo 'Your browser does not support the video tag.';
echo '</video>';
echo '</div>';
echo '</div>';
echo '</div>';
I'm trying to get the ID of each video element but it returns undefined.

Set an identifier like id or class on your text field, then add a listener to the click event on that object:
// If you set by Class
$('.textToClick').click(function (e)
{
alert($(this).data("primary"));
});
// If you set by ID
$('#textToClick').click(function (e)
{
alert($(this).data("primary"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Setting identifier by Class -->
<input type="text" class="textToClick" data-primary="dataPrimaryFromClass" value="Class identifier">
<!-- or setting identifier by id -->
<input type="text" id="textToClick" data-primary="dataPrimaryFromID" value="ID identifier">

Related

Duplicate comment when trying to reply to comment

Good day to all, I ran into such a problem that when I try to reply to a certain comment, all comments are duplicated and at the same time duplicate comments are not displayed in the database, but only on the page. It feels like when you send a comment, not only one comment is sent, but some else, at least, it seems, the request to the database is made correctly + information is displayed in the same way:
enter image description here enter image description here enter image description here enter image description here
Php code:
<?php foreach ($showcomn as $result) {?>
<?php foreach ($showreplycom as $resultreply) {?>
<?php
if (isset($_SESSION['all-good'])) {
echo '<p id="user-comment-info">'.$result['name'].' '.$result['date'].'<br></p>',
'<div id="comment-user">',
'<p id="stealth-'.$result['id'].'">'.$result['comment'].'</p>',
'</div>',
'<form method="post" action="./check%20info/editsavechanges.php">';
if ($findid['id'] === $result['userID']){
echo '<textarea id="id-edit-save-'.$result['id'] .'" name="id-each-user" hidden>'.$result['id'].'</textarea>',
'<textarea name="edit-comment" id="edit-user-comment-'.$result['id'].'" class="edit-style" hidden >'.$result['comment'].'</textarea>',
'<div id="buttons-edit">',
'<button type="submit" name="save-edit-comment" id="save-edit-user-comment-'.$result['id'].'" hidden>Save</button>',
'<button type="button" onclick="cancelEdit('.$result['id'].')" id="cancel-edit-user-comment-'.$result['id'] .'" hidden>Cancel</button>',
'</div>',
'<div id="buttons-forms">',
'<button type="button" onclick="showForm('.$result['id'].')" id="open-edit-'.$result['id'].'" >Edit</button>',
'<button type="submit" name="delete-edit-comment" id="delete-edit-'.$result['id'].'" >Delete</button>',
'</div>';
}
echo '<div id="buttons-forms-reply">',
'<button type="button" onclick="showformReply('.$result['id'].')" id="reply-edit-'.$result['id'].'" >Reply</button>',
'</div>',
'<textarea name="reply-userid" id="comment-userid-reply" class="edit-style-user-id" readonly hidden>'.$findid['id'].'</textarea>',
'<textarea name="reply-user-name" id="comment-name-reply" class="edit-style-user" readonly hidden>'. $_SESSION['all-good']['login'] .'</textarea>',
'<textarea id="reply-save-comment'.$result['id'] .'" name="reply-comment-id" hidden>'.$result['id'].'</textarea>',
'<input type="hidden" name="reply-user-date">',
'<textarea name="reply-comment" id="reply-text-'.$result['id'].'" class="edit-style-reply" hidden ></textarea>';
echo '<div id="reply-buttons">',
'<button type="submit" name="save-reply-comment" id="save-reply-edit-'.$result['id'] .'" hidden>Save</button>',
'<button type="button" onclick="cancelReply('.$result['id'].')" id="cancel-reply-edit-'.$result['id'] .'" hidden>Cancel</button>','<br>',
'</div>',
'<div id="show-comments-reply">',
'<button type="button" onclick="showallReply(' . $resultreply['id'] . ')" id="show-reply-all-' . $resultreply['id'] . '" class="all_reply_button">Show all comments</button>',
'<button type="button" onclick="closeallReply(' . $resultreply['id'] . ')" id="close-reply-all-' . $resultreply['id'] . '" class="close_reply_button" hidden>Close all comments</button>',
'</div>',
'<div id="new_box_reply">',
'<p id="all-reply-com-' . $resultreply['id'] . '" class="reply_box" hidden>' . $resultreply['name'] . ' ' . $resultreply['date'] . '<br>' . $resultreply['comment'] . '</p>',
'</div>',
'</form>';
Here realization reply form
<?php include_once "../connection/coments_connection.php";
date_default_timezone_set('Europe/Kiev');
if (isset($_POST['save-reply-comment'])) { $commentID = $_POST['reply-comment-id'];
$name = $_POST['reply-user-name'];
$userID = $_POST['reply-userid'];
$comment = $_POST['reply-comment'];
$data = date('Y-m-d H:i:s');
$replyBase = "INSERT INTO `replycom`(`commentID`, `name`, `comment`, `date`, `userID`) VALUES ('$commentID', '$name', '$comment', '$data', '$userID')";
$resultReply = $Gcom->prepare($replyBase);
$resultReply->execute([
'reply-comment-id' => $commentID,
'user-name' => $name,
'reply-comment' => $comment,
'reply-user-date' => $data,
'reply-userid' => $userID,
]);
header('Location: ../index.php#contacts'); }
Here's a Foreach loop for the main comments:
<?php
include_once "./connection/coments_connection.php";
$showcomn = $Gcom->query("SELECT * FROM `comments` ORDER BY date DESC ");
$showcomn = $showcomn->fetchAll();
Here's a Foreach loop for reply comments:
<?php
include_once "./connection/coments_connection.php";
$showreplycom = $Gcom->query("SELECT * FROM `replycom` ORDER BY date DESC ");
$showreplycom = $showreplycom->fetchAll();

Why is JavaScript not setting the value of a hidden field?

I have a PHP form to submit and I'm trying to get (vanilla) JavaScript to set the value of a hidden field. For some reason, the hidden field (deleteRowId) is coming through as blank. Any help would be much appreciated.
Here is my code:
<?php
if (isset($transcribercertifications)) {
echo form_open('user/deletecertification/' . $tid, 'id="deleteCert"');
echo '<table>';
$count = 0;
if ($transcribercertifications) {
foreach ($transcribercertifications as $transcribercertification) {
echo '<tr><td>' . $transcribercertification . '</td>';
echo '<input type="hidden" name="certification[' . $count . ']" id="certification[' . $count . ']" value="' . $transcribercertification . '">';
echo '<input type="hidden" id="deleteRowId" name="deleteRowId" value="">';
echo '</td><td title="Delete certification"><button data-row-id="' . $count . '" id="deleteCert" onclick="deleteRow(' . $count . ');">X</button></td></tr>';
$count++;
}
}
echo '</table>';
echo form_close();
}
?>
<script type="text/javascript">
function deleteRow(rowCount) {
event.preventDefault()
alert('This will delete the certification. Are you sure ?');
alert(rowCount); // This value comes through correctly.
document.getElementById('deleteRowId').value = rowCount;
document.getElementById('deleteCert').submit();
}
</script>
When the function gets called, deleteRowId is always blank. If there's another way to set the value of deleteRowId so the function knows which certification to delete, I would be interested in seeing that too.
First of all id="deleteRowId" must be unique
and you can use setAttribute method
worked exampe
<input type="hidden" value="111" id="uniqID1">
<input type="hidden" value="111" id="uniqID2">
<script>
let aaa = document.getElementById("uniqID1");
aaa.setAttribute('value',222);
console.log(aaa.value)
</script>
Id cannot repeat.
in foreach loop use as id="deleteRowId"'.$count.'"" id="deleteCert"'.$count.'""
foreach ($transcribercertifications as $transcribercertification) {
echo '<tr><td>' . $transcribercertification . '</td>';
echo '<input type="hidden" name="certification[' . $count . ']" id="certification[' . $count . ']" value="' . $transcribercertification . '">';
echo '<input type="hidden" id="deleteRowId"'.$count.'"" name="deleteRowId"'.$count.'"" value="">';
echo '</td><td title="Delete certification"><button data-row-id="' . $count . '" id="deleteCert"'.$count.'"" onclick="deleteRow(' . $count . ');">X</button></td></tr>';
$count++;
}
and in JS function
getElementByID('deleteRowId'+rowCount).
getElementByID('deleteCert'+rowCount)

Add new dynamic boostrap card does not work

I will insert new boostrap card inside my page. My problem, I have not success to include a new card inside my content.
When i click on insert, the card is not displayed
Below the code
display a new boostrap card if record exist
<div class="row">
<button type="button" class="btn btn-primary" aria-label="Insert" id="insert">
<span aria-hidden="true">Insert</span>
</button>
</div>
<div class="row">
<ul class="row list-unstyled" id="list">
<?php
$i = 0;
while ($QoptionValue->fetch()) {
.....
?>
<li class="col-md-4" id="element'<?php echo $i; ?>">
<div class="card">
<h4 class="card-header">Card title <a class="close" href="#">×</a></h4>
<div class="card-body">
<div class="card-text">
<div><?php ..... ?></div>
</div>
</div>
</li>
<?php
$i++;
}
?>
</ul>
</div>
Display a new card or first card inside the content
<?php
$card = '<li class="col-md-4" id="element0">';
$card .= '<div class="card">';
$card .= '<h4 class="card-header">Card title <a class="close" href="#">Remove</a></h4>';
$card .= '<div class="card-body">';
$card .= '<div class="card-text">';
$card .= '<div>';
for ($l=0, $n=count($languages); $l<$n; $l++) {
$card .= Language->getImage($languages[$l]['code']) . ' ' . HTML::inputField('option_value[' . $i . '][option_value_description][name][' . $l . ']', $options_name) . '<br />';
$card .= HTML::hiddenField('option_value[' . $i . '][option_value_description][language_id][' . $l . ']', $options_name);
}
$card .= '</div>';
$card .= '<div>';
$card .= HTML::inputField('option_value[' . $i . '][sort_order]', $QoptionValue->value('sort_order'), 'id="sort_order[' . $i . ']"');
$card .= '</div>';
$card .= '<div>';
$card .= '</div>';
$card .= '</div>';
$card .= '</li>';
?>
<script>
$('#insert').click(function(){
$( "ul#list" ).append( "<?php echo $card; ?>" );
});
</script>
<script type="text/javascript">
$('.close').click(function(){
var $target = $(this).parents('li');
$target.hide('slow', function(){ $target.remove(); });
})
</script>
console error
it seems on this line has a problem :
$( "ul#list" ).append(""<li class=\"col-md-4\" id=\"element0\"><div class=\"row\"><div class=\"col-md-12\"><div class=\"card\"><h4 class=\"card-header\"><a class=\"close\" href=\"#\">Supprimer<\/a><\/h4><div class=\"card-body\">Nom de la valeur<div><img src=\"http:\/\/localhost\/test_option\/shop\/sources\/third_party\/flag-icon-css\/flags\/4x3\/gb.svg\" alt=\"Anglais\" title=\"Anglais\" width=\"16\" height=\"12\" \/> <input type=\"text\" name=\"option_value[0][option_value_description][name][0]\" class=\"form-control\" \/><br \/><input type=\"hidden\" name=\"option_value[0][option_value_description][language_id][0]\" \/><img src=\"http:\/\/localhost\/test_option\/shop\/sources\/third_party\/flag-icon-css\/flags\/4x3\/fr.svg\" alt=\"Francais\" title=\"Francais\" width=\"16\" height=\"12\" \/> <input type=\"text\" name=\"option_value[0][option_value_description][name][1]\" class=\"form-control\" \/><br \/><input type=\"hidden\" name=\"option_value[0][option_value_description][language_id][1]\" \/><\/div><div class=\"row\"><span class=\"col-md-4\">Ordre de tri<\/span><\/div><\/div><\/div><\/div><\/div><\/li>"");
Uncaught SyntaxError: missing ) after argument list
It's good practice to pass any PHP variable to javascript using json_encode(). Using json_encode() you'll always get a properly formatted JavaScript object with the quotes escaped.
<script>
$('#insert').click(function(){
$( "ul#list" ).append(<?php echo json_encode($card); ?>);
});
</script>

Hide / show table with javascript

I have a little problem to hide and show table. I tred this, I haven't error in console but it does'nt work. Maybe I forget something wrong or make a mistake.
I saw the data inside the code but it does'nt appear when I click on the link.
Thank you
$i = 0;
foreach($option_attributes_name as $value) {
$content .= ' <li class="col-md-12"><a onclick="showTabOption' . $i .'" class="nav-link" data-toggle="tooltip" data-target="#section_ProductsAttributesNewApp_content" href="' . OSCOM::link('index.php?A&Catalog\Products&Edit&cPath=' . $_GET['cPath'] . '&pID=' . $_GET['pID'] . '#tab-option' . $i) . '"><i class="fa fa-minus-circle"></i> ' . $value['name'] . '</a></li>';
// $i++;
$t++;
}
$Qoption = $this->app->db->prepare('select option_id, type
from :table_test_products_options_attributes');
$Qoption->execute();
$i =0;
while ($Qoption->fetch()) {
$content .= '<div id="tab-option' . $i . '" style="display:none;">';
$content .= '<h4>' . $Qoption->value('type') . '</h4>';
$content .= '<table width="100%" cellpadding="5" cellspacing="0" border="0">
</table>
</div>
';
$content .= '
<script type="text/javascript"><!--
function showTabOption' . $i . '() {
$("a[href=\'#tab-option' .$i . '\']").parent().remove();
$(\'#tab-option'. $i . '\').remove();
$(\'#option a:first\').div(\'show\');
}
//--></script>
';
$i++;
}
You can settle a few issues first by adjusting how you are doing things with the js and jquery use.
1) Setting up the elements you will click with just a class, and data-tableid:
$content .= '<li class="col-md-12"><a class="showTabOption nav-link" data-tableid="'. $i .'" ... etc etc ...</a>';
^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
2) Fix this in your first loop: Change $t++; to $i++;.
3) You do not need to adjust the table builds (the ones from the while loop):
$content .= '<div id="tab-option'. $i .'" style="display:none;">';// this is ok
4) Then adjust your SINGLE javascript function. Have it output OUTSIDE of the while loop (since this must only be done once):
<script language="Javascript" type="text/javascript">
$( document ).ready(function() {
$(".showTabOption").click(function(e) {
e.preventDefault(); // stop the a href from firing off
var tableid = $(this).data('tableid'); // the table in question
$(this).parent().remove(); // remove what you clicked?
$("#tab-option"+ tableid ).show(); // show your options table
});
});
</script>
This should get you rolling on making that table (the div surrounding it) show up when you click one of those links. Of course it looks like you have much more going on in there, table rows, something with the href link value, and the sort, but you only asked about showing the table div.
TL;DR: Full example of your example code adjusted:
<?php
$i = 0;
foreach($option_attributes_name as $value) {
$content .= '<li class="col-md-12"><a class="showTabOption nav-link" data-tableid="'. $i .'" data-toggle="tooltip" data-target="#section_ProductsAttributesNewApp_content" href="'. OSCOM::link('index.php?A&Catalog\Products&Edit&cPath='. $_GET['cPath'] .'&pID='. $_GET['pID'] .'#tab-option'. $i) .'"><i class="fa fa-minus-circle"></i> '. $value['name'] .'</a></li>';
$i++;
}
$Qoption = $this->app->db->prepare('select option_id, type
from :table_test_products_options_attributes');
$Qoption->execute();
$i = 0;
while ($Qoption->fetch()) {
$content .= '<div id="tab-option'. $i .'" style="display:none;">';
$content .= '<h4>'. $Qoption->value('type') .'</h4>';
$content .= '<table width="100%" cellpadding="5" cellspacing="0" border="0">';
// table tr rows go here
$content .= '</table>';
$content .= '</div>';
$i++;
}
?>
<script language="Javascript" type="text/javascript">
$( document ).ready(function() {
$(".showTabOption").click(function(e) {
e.preventDefault(); // stop the a href from firing off
var tableid = $(this).data('tableid'); // the table in question
$(this).parent().remove(); // remove what you clicked?
$("#tab-option"+ tableid ).show(); // show your options table
});
});
</script>

Return a Javascript array to a hidden input value

I am having trouble that will change the value of a hidden input type. I have a search that has multiple checkboxes created with a PHP while loop. I want to pass the items that are checked into a variable in PHP once submitted. This is the form with checkboxes and hidden value.
$search_sql = "SELECT * FROM `company` WHERE `groups` = '$groups' AND (`companyname` LIKE '%$search%' OR `directurl` LIKE '%$search%' OR `email` LIKE '%$search%' OR `phone` LIKE '%$search%' OR `groups` LIKE '%$search%' OR `notes` LIKE '%$search%')";
$result = mysql_query($search_sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
//remove the http from the links
$website = $row['directurl'];
$website = str_replace("http//", "", "$website");
$website = str_replace("http://", "", "$website");
$website = str_replace("https://", "", "$website");
$website = str_replace("https//", "", "$website");
//button to change colour
//display contacted companies
if($row['contact'] == 0){
//not contacted
$changecolor = '1';
$contacted = '<tr class="nocontact border">';
$button = '<td>
<form name="change_colour" method="post">
<input type="hidden" name="id" value="' . $row['id'] . '">
<input type="hidden" name="change_colour" value="' . $changecolor . '">
<input type="hidden" name="search" value="' . $row['companyname'] . '">
<input type="hidden" name="groupselected" value="' . $groups . '">
<input type="submit" value="C"></form>';
}
//contacted
elseif($row['contact'] == 1){
$changecolor = '2';
$contacted = '<tr class="contact border">';
$button = '<td>
<form name="change_colour" method="post">
<input type="hidden" name="id" value="' . $row['id'] . '">
<input type="hidden" name="change_colour" value="' . $changecolor . '">
<input type="hidden" name="search" value="' . $row['companyname'] . '">
<input type="hidden" name="groupselected" value="' . $groups . '">
<input type="submit" value="C"></form>';
}
//positive feedback
elseif($row['contact'] == 2){
$changecolor = '3';
$contacted = '<tr class="positive border">';
$button = '<td>
<form name="change_colour" method="post">
<input type="hidden" name="id" value="' . $row['id'] . '">
<input type="hidden" name="change_colour" value="' . $changecolor . '">
<input type="hidden" name="search" value="' . $row['companyname'] . '">
<input type="hidden" name="groupselected" value="' . $groups . '">
<input type="submit" value="C"></form>';
}
//negative feedback
elseif($row['contact'] == 3){
$changecolor = '0';
$contacted = '<tr class="negative border">';
$button = '<td>
<form name="change_colour" method="post">
<input type="hidden" name="id" value="' . $row['id'] . '">
<input type="hidden" name="change_colour" value="' . $changecolor . '">
<input type="hidden" name="search" value="' . $row['companyname'] . '">
<input type="hidden" name="groupselected" value="' . $groups . '">
<input type="submit" value="C"></form>';
}
else {echo 'error with the display';}
//button to select companies
$select_comp = '<form name="select_comp" method="post">
<input type="checkbox" id="' . $row['id'] . '" name="id" onclick="compTrig(' . $row['id'] . ')">
<input type="hidden" id="return_comp" name="return_comp" value="me">
<input type="submit" name="select_comp" value="Selected"></form></td>';
//Display link to website if available
if ($website !== ''){
$webdisplay = $contacted . $button . $select_comp . '<td><a target="_blank" href="http://' . $website . '">' . $row['companyname'] . '</a></td>';
}
else{
$webdisplay = $contacted . $button . '<td class="red">' . $row['companyname'] . '</td>';
}
//check if email has been submitted
if ($row['email'] !== ''){
$email = '<td>Email</td>';
}
else{
$email = '<td class="red">None</td>';
}
//display company details
echo $webdisplay;
echo '<td>' . $row['contactname'] . '</td>';
echo $email;
echo '<td>' . $row['town'] . '</td>';
echo '<td>' . $row['phone'] . '</td>';
echo '<td>' . $row['notes'] . '</td></tr>';
$companyfind = $row['id'];
}
and the Javascript below:
var select_comp = new Array();
var element = document.getElementById('return_comp');
function compTrig(clickedid)
{
if (document.getElementById(clickedid).checked == false)
{
return false;
}
else
{
select_comp.push(clickedid);
var clicked = clickedid;
var box= confirm(select_comp);
if (box==true)
return true;
else
document.getElementById(clickedid).checked = false;
var index = select_comp.indexOf(clicked);
if (index > -1)
{
select_comp.splice(index, 1);
}
}
select_comp.toString();
element.value(select_comp);
}
I can get a confirmation box to display the correct values but i cannot change the value of the hidden value which would work. I was thinking that it may be because the form is in a while loop and the form should be outside of the loop. Any help of this matter will be greatly appreciated.
You're doing this the opposite way 'round how it should be done and exposing too much information to be tampered with in the front-end. It's also causing a lot of unnecessary redundancy (redundancy is the programmer's mortal enemy). No Javascript is needed for this task.
All you should be passing to the browser is the relevant company information to populate a single form; then building the appropriate output in PHP after submission.
search_results.php
echo "<form name=\"select_comp\" method=\"POST\" action=\"select_comp.php\">";
$search_sql = "
SELECT id FROM `company` WHERE `groups` = '$groups'
AND (`companyname` LIKE '%$search%'
OR `directurl` LIKE '%$search%'
OR `email` LIKE '%$search%'
OR `phone` LIKE '%$search%'
OR `groups` LIKE '%$search%'
OR `notes` LIKE '%$search%')";
$result = mysql_query($search_sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<input type=\"checkbox\" name=\"id[{$row['id']}]\" value=\"1\"> {$row['company_name']}<br>";
// echo other company details
}
echo '
<input type="submit" value="C">
</form>';
This will give you an array of selected checkboxes in the $_POST variable:
select_comp.php
// $_POST['id'] will contain an array of selected checkboxes
// implode array into a comma-separated list for use with MySQL IN operator
// escaping a string where the numbers have been tampered with will cause an error, but it will be safe from injection
$sql = "
SELECT * FROM `company` WHERE `id`
IN (" . mysql_real_escape_string(implode(',', $_POST['id'])) . ")";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
switch ($row['id']) {
// first company
case '0':
// build styling here
break;
// second company
case '1':
// build more styling here
break;
// and so on
}
// output HTML with styling information computed above
}
But, what you should really be doing is setting the styling dynamically with values entered into the database and/or determined by file naming convention (while involving absolute validation of dynamically-generated styling specifications, of course).

Categories

Resources