Hide / show table with javascript - 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>

Related

Link not opening in DIV using Jquery

I'm trying to use jquery to click a link in one div and have it open an HTML document in another div (named infoblock) that sits beside the original div. I found an example here but I can't get it to work. I found a couple other variations on the net, but still no luck. Part of the link needs to transmit a variable so I'm not sure if that's part of the problem. I tried attaching the click function to a div surrounding the link with an ID of "nav" as well as the link itself with an ID of "details". When I click on the link, it opens the correct page in the full window, not in the div it's supposed to go to. Thank you in advance for any help.
$(document).ready(function() {
$("#reservename").click(function() {
$("#infoblock").load("createhandle.html");
});
$("#uploadpic").click(function() {
$("#infoblock").load("uploadpic.php");
});
$("#deletechar").click(function() {
$("#infoblock").load("selectdelete.php");
});
$("#nav").click(function() {
$("#infoblock").load($(this).find("a").attr("href"));
return false;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="charlist" class="block">
<b>Your Characters:<b>
<br>
<button id="reservename">Reserve A Name</button>
<button id="uploadpic">Upload A Picture</button>
<button id="deletechar">Delete</button>
<?php
$result5 = mysqli_query($con,"SELECT * FROM handle WHERE user='$handle' ORDER BY charname ASC");
while($row = mysqli_fetch_array($result5))
{
echo "<table>";
echo "<tr>";
echo "<td rowspan=5 align=left><img src='../pictures/" . $row['face'] . "' border=3></td>";
echo "<th align=left><a href='chat.php?charname=" . $row['charname'] . "'>" . $row['charname'] . "</a></th>";
echo "</tr>";
echo "<tr>";
echo "<th align=left><a href='choosepic.php?charname=" . $row['charname'] . "'>Choose Picture</a></th>";
echo "</tr>";
echo "<tr>";
echo "<th align=left><div id='nav'><a id='details' href='../details.html?charname=" . $row['charname'] . "'>Details</a></div></th>";
echo "</tr>";
if ($row['type'] == 'new'){
echo "<tr>";
echo "<th align=left><a href='createsheet.php?charname=" . $row['charname'] . "'>Create</a></th>";
echo "</tr>";
}
echo "<hr>";
echo "</table>";
}
?>
</div>
<p id="infoblock" class="block"></p>
You have to prevent the default behaviour when anchor tag is clicked In order to do that that you have to be listen for click on the anchor itself not div and return false in order to prevent its default behaviour. So your code will become like this
$('#details').click(function(e){
{
e.preventDefault(); //instead of this you can also return false
$("#infoblock").load($('#details').attr("href"));
}
});
This works for me:
$(document).ready(function(){
$('#details').click(function(e){
e.preventDefault();
$("#infoblock").html('<object type="text/html" data="'+$('#details').attr("href")+'" >');
});
});

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>

I had an issue with bootstrap's datetime picker on MozilaFirefox

Hello guys I had an issue with datetimepicker on FF. In other browsers its doing good with the code I wrote. The problem is I have three drop down options. In each one I had, time is inserted by the user using datetimepicker but unfortunately the picker works only on one of the three of them. Any idea why this is happening
PHP CODE
<?php
echo '<div class="table-rsponsive overlap">';
echo '<table class="table" >';
$workingDaysNum = array();
$counter = 0;
for ($i = 0; $i < 3; $i++) {
echo '<tr>';
for ($j = 0; $j < 7/* count($spec) */; $j++) {
if ($i == 0) {
echo '<td>' . $days[$j] . '</td>';
} else {
$counter++;
$workingDaysNum[] = 'datetimepicker' . $counter;
?>
<td>
<div class="input-group date datetimepicker" id="<?php echo $workingDaysNum[$counter - 1] ?>">
<input class="form-control " id="filter-date" size="16" type="text" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</td>
<?php
}
}
echo '</tr>';
}
JQUERY CODE
$(function () {
<?php
foreach ($workingDaysNum as $workDay) {
echo '$(' . $workDay . ').datetimepicker({';
echo 'format: \'HH:mm\',';
echo 'stepping: 30';
echo '});';
}
?>
<?php
foreach ($workingDaysNum as $workDay) {
echo '$("' . $workDay . '").on("dp.change",function (e) {';
echo 'saveSpec1Modal("' . $workDay . '", $("' . $workDay . '").data(\'date\'))';
//echo 'console.log($("#'.$workDay.'").data(\'date\'))';
echo '});';
}
?>
});
Ditch the loops in the jQuery.
Instead of activating datetimepicker by ID, you have already given them all a class, so you can run it once instead of looping.
$(function () {
$('.datetimepicker').datetimepicker({
format: 'HH:mm',
stepping: 30
});
});
Same applies to the change function.

How pull innerHTML of element created by javascript function

Question:
I have a div element with id of "tableholder" which is purely to hold the output on a javascript function that pulls data via ajax from a PHP file.
Within the tableholder element, is a list.js table that works if we simply include he php file instead of calling it via ajax and setting it via innerHTML = "".
How do I use the contents of innerHTML of the tableholder div when it has been created dynamically?
Code so far:
PHP File called:
<?php
// Connection details for the database being called.
include 'connection.php';
// Putting the query to the database in a variable called "$assets".
$assets = "SELECT * FROM assetregister.getassets";
$assetPull = $conn->query($assets);
$output = "";
// Pulling all of the details from the database and displaying them on the page within the inidividual divs.
if ($assetPull->num_rows > 0) {
$output .= "<div id='users'>";
$output .= "<input class='search form-control mt-2' placeholder='Search...' />";
$output .= "<div class='m-2'>";
$output .= "<button class='sort btn' data-sort='model'>Sort By Model</button>";
$output .= "<button class='sort btn ml-2' data-sort='domain'>Sort By Domain</button>";
$output .= "<button class='sort btn ml-2' data-sort='location'>Sort By Location</button>";
$output .= "</div>";
$output .= "<table class='table table.hover list'>";
$output .= "<thead>";
$output .= "<th style='text-align: center;'>Model</th>";
$output .= "<th style='text-align: center;'>Serial Number</th>";
$output .= "<th style='text-align: center;'>Asset Number</th>";
$output .= "<th style='text-align: center;'>Domain</th>";
$output .= "<th style='text-align: center;'>Location</th>";
$output .= "<th style='text-align: center;'>Type</th>";
$output .= "</thead>";
while ($row = $assetPull->fetch_assoc()) {
$output .= "<tbody class='list' style='text-align: center;'>";
$output .= "<td class='model'>" . $row['modelName'] . "</td>";
$output .= "<td class='serialNumber'>" . $row['serialNumber'] . "</td>";
$output .= "<td class='assetNumber'>" . $row['assetNumber'] . "</td>";
$output .= "<td class='domain'>" . $row['domain'] . "</td>";
$output .= "<td class='location'>" . $row['locationName'] . "</td>";
$output .= "<td class='type'>" . $row['type'] . "</td>";
}
$output .= "</tbody>";
$output .= "</table>";
$output .= "</div>";
// If there is no rows in the table that is being called then they will display 0 Results... See below.
} else {
$output .= "0 results";
}
echo $output;
$conn->close();
?>
This works:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<?php include 'scripts/getAsset.php'; ?>
</main>
</div>
</div>
</div>
<script>
populatetable('tableholder');
window.onload = function () {
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
</script>
This outputs the table and all of the list.js functions work fine as expected.
This Doesn't Work:
<div class="container-fluid">
<div class="container">
<div class="row">
<main class="col-12" style="margin-top: 80px;">
<button class="btn btn-primary" onclick="assetSubmit()" style="width: 100%;">Add An Asset</button>
<!-- Pulling in the results of the assets (most recent assets) -->
<div id="tableholder"></div>
<!-- end -->
</main>
</div>
</div>
</div>
<!-- PHP include for the footer -->
<?php include 'assets/layout/footer.php'; ?>
<!-- end -->
<script>
populatetable('tableholder');
window.onload = function (){
var options = {
valueNames: [ 'model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList = new List('users', options);
};
function populatetable(name){
$.ajax({
url: "scripts/getAssets.php",
success: function(data){
document.getElementById(name).innerHTML = data;
}
})
}
</script>
What I can assume:
From the various console.log lines and php echos I have put in to test the code, it would appear that the issue it that the javascript command for initiating the list.js table isn't able to find the "user" table that is created by the document.getElementById(name).innerHTML = data; in the populatetable() function. I know this because the folllowing shows blank:
console.log(document.getElementById(tableholder).innerHTML);
What am I doing wrong, or is it not possible to pull the innerHTML data of a dynamically created element?
The problem is that by the time you're calling List(), the ajax call hasn't finished yet, since it's asynchronous.
Try this instead:
var options = {
valueNames: ['model', 'serialNumber', 'assetNumber', 'domain', 'location', 'type']
};
var userList;
$(document).ready(function() {
populatetable('#tableholder');
});
function populatetable(id) {
$.ajax({
url: "scripts/getAssets.php",
success: function(data) {
$(id).html(data);
userList = new List('users', options);
}
});
}
Here I'm using jQuery everywhere it's useful, and I'm calling List() only after the data is actually inserted.
Also note, that like I mentioned in my comment, you need to move the <tbody> line outside the loop.

Attach event for PHP created elements via JQuery

Using ajax I insert table rows in a dropdown menu. It works and displays it. I'd like to attach events for when the rows are clicked, however, what I've tried doesn't work. What could be the problem?
PHP
<?php
for($i=1; $i<=2; $i++){
echo "<div class='medium-block dropdown'>
<div class='dropdown-toggle stat-dropdown not-added' id='away" . $i . "' data-toggle='dropdown'>
<p class='vertical-center add-player' id='add-player" . $i . "' style='margin:0;'>Add Player</p>
</div>
<ul class='dropdown-menu drop-scroll' style='margin:0; padding:0; border-radius:0;'>
<table class='table table-hover' style='margin:0;'>
<tbody id='choose-player-away" . $i . "'>
</tbody>
</table>
</ul>
</div>";
}
for($i=3; $i<=5; $i++){
echo "<div class='medium-block dropup'>
<div class='dropdown-toggle stat-dropdown not-added' id='away" . $i . "' data-toggle='dropdown'>
<p class='vertical-center add-player' id='add-player" . $i . "' style='margin:0;'>Add Player</p>
</div>
<ul class='dropdown-menu drop-scroll' style='margin:0; padding:0; border-radius:0;'>
<table class='table table-hover' style='margin:0;'>
<tbody id='choose-player-away" . $i . "'>
</tbody>
</table>
</ul>
</div>";
}?>
JQuery
<script type="text/javascript">
$(document).ready(function(){
scalability();
$(window).resize(scalability);
$(".not-added").each(function(i){
$(this).click(function(){
var identifier = $(this).attr('id').charAt(4);
var teamid = $(this).attr('id').substring(0,4);
if($(this).hasClass("not-added")){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("choose-player-"+teamid+identifier).innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getPlayerlist.php?team="+teamid+"&id="+identifier,true);
xmlhttp.send();
$(".player").on('click',function(){
alert("working");
});
}
});
});
});
</script>
PHP file that is fetched by AJAX
<?php
$team = $_GET["team"];
$id = $_GET["id"];
$con = mysqli_connect('localhost','root','','sportacus');
$query = "SELECT * FROM " . $team . "_team WHERE incourt = 0 ORDER BY number";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)){
echo "<tr class='player' id='" . $team . "-player" . $row['id'] . "'>
<td>" . $row['number'] . "</td>
<td>" . $row['first_name'] . " " . $row['last_name'] . "</td>
</tr>";
}
mysqli_close($con);
?>
I want the rows with class .player, which are created by the AJAX fetched php file, to be clickable.
NOTE: I am using bootstrap library if that helps. Everything else works, except for the part:
$(".player").on('click',function(){
alert("working");
});
Like reported in event binding on dynamically created elements you need to delegate the event.
In your case, you need to change from:
$(".player").on('click',function(){
to:
$(document).on('click', ".player", function () {
alert("working");
});

Categories

Resources