Creating a dynamic link based on the value of a previous Class - javascript

Hopefully I am using the proper words in my title here.
What I am hoping to achieve is creating a link that varies automatically based on the value of a previously found class. Below is the code I am using, and I'd like the XXXX.jpg to change based on the numbers found in the Class directly before the link.
<?php
$crim_url = "<a href=../images/vinyl/crim/numbers/XXXX.jpg>Link</a>";
?>
<tbody>
<tr>
<td><? print $bluewhite ?></td><td class=num>0002</td><td>Name</td><td><? print $crim_url ?></td></tr><tr>
<td><? print $bluewhite ?></td><td class=num>0004</td><td>Name</td><td><? print $crim_url ?></td>
</tr>
</tbody>
So in this example, I'd like to have the $crim_url grab the data in the previously found < td class=num> and replace the XXXX.jpg with 0002.jpg and 0004.jpg respectively. I don't even know where to start with this. I have nearly 1000 links, and I'd like to automate this instead of writing code manually. I'm not sure if it's possible with the setup I'm using, but any tips in the right direction would be great!
Thank you!

Use a loop to create the HTML, so you can substitute the same number into both the <td> and $crim_url.
<?php
$numbers = ['0002', '0004'];
?>
<tbody>
<tr>
<?php
foreach ($numbers as $number) {
$crim_url = "<a href=../images/vinyl/crim/numbers/$number.jpg>Link</a>";
?>
<td><? print $bluewhite ?></td><td class=num><?= $number ?></td><td>Name</td><td><?= $crim_url ?></td></tr><tr>
<? php
} ?>
</tr>
</tbody>

Because you tagged Javascript in your question, here is a pure JS solution for you.
If you already have the table rows parsed in the DOM within the table, you can loop over the elements and get the textContent of each element and then find its closest parent element and query the target tr element that will hold the formatted link and then set its innerHTML to the formatted link. Format the link using a method that returns the textContent of the current iteration of the num element.
// function to return the link formatted with the proper address
// maybe you want to add more attributes like a class or a dataset
function parseLink(address, className) {
return `<a class="${className}" href=../images/vinyl/crim/numbers/${address}.jpg>Link - ${address}</a>`
}
// get all elements with a class of num
const nums = document.querySelectorAll('.num')
// loop over the elements with a class of num
nums.forEach(num => {
// get the closest parent row and query the 4th child to display the link
let val = num.closest('tr').querySelectorAll('td')[3]
// set the innerHTML of that 4th child to the formatted link
val.innerHTML = parseLink(num.textContent, 'blue-white link')
})
.blue-white:hover {
color: white;
background: blue;
}
.link {
text-decoration: none;
}
<table>
<tbody>
<tr>
<td>
<? print $bluewhite ?>
</td>
<td class='num'>0002</td>
<td>Name</td>
<td>
</td>
</tr>
<tr>
<td>
<? print $bluewhite ?>
</td>
<td class='num'>0004</td>
<td>Name</td>
<td>
</td>
</tr>
</tbody>
</table>

Related

Uncaught TypeError: scrollIntoView is not a function

I can't figure out why, but scrollIntoView() function doesn't work. The browser displays an error: Uncaught TypeError: element.scrollIntoView is not a function at .... The element element is defined and displayed in console. I haven't been able to find any answer in the Internet. Below is simplified code:
[...]
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php
if (is_array($array)) {
foreach ($array as $element) { ?>
<tr data-someid="<?= $element->some_id ?>">
<th><?= $element->id ?></th>
<td><?= $element->name ?></td>
<td><?= $element->surname ?></td>
</tr>
<?php }
} ?>
</tbody>
</table>
[...]
<script>
var element= document.querySelectorAll('[data-someid="' + someId + '"]');
console.log(element); // displays the element well
element.scrollIntoView();
</script>
[...]
Do somebody have any ideas why it doesn't work?
document.querySelectorAll() returns a list of DOM elements. Right now you're trying to access a method .scrollIntoView on the returned NodeList which of course doesn't exist.
You probably meant to use document.querySelector() which returns a single element.

Apply jQuery to every instance of foreach loop but only operating on the element clicked upon

I am looking to apply jQuery to every instance of foreach loop but only operating on the element clicked upon.
The php foreach loop is below:
#foreach ($entries as $entry)
<?php $row = DB::table('workout_trainings')->where('date', $entry->format('Y-m-d'))->where('user_id', Auth::user()->id)->count(); ?>
<tr style="border-top: 2px solid black;">
<th rowspan={{$row}}><p>{{ $entry->format('l- d/m/Y') }}</p>
<button class="btn btn-default" id="goals_btn">Goals</button>
<button class="btn btn-default" id="logs_btn">Log Workout</button>
</th>
<?php $ws = DB::table('workout_trainings')->where('date', $entry->format('Y-m-d'))->where('user_id', Auth::user()->id)->get(); ?>
#foreach ($ws as $w)
<td>{{$w->exercise}}</td>
<td>{{$w->weight}}</td>
<td>{{$w->sets}}</td>
<td>{{$w->reps}}</td>
</tr>
#endforeach
<tr id="goals">
<td colspan='5'>.</td>
</tr>
<tr id="logs">
<td colspan='5'>.</td>
</tr>
#endforeach
</tbody>
</table>
<?php echo $entries->setPath('')->render(); ?>
The jQuery I have is simply:
$(document).ready(function(){
$("#goals").css("display","none");
$("#goals_btn").click(function(){
$("#goals").toggle(200);
});
});
Which obviously works for the top item.
UPDATE
Slide now works however only on elements with less than two rows filled.
Wednesday doesn't work but Thursday and Friday do in this example.
Thanks
$(document).ready(function(){
$("#goals").css("display","none");
$("#goals_btn").click(function(){
$(this).find("#goals").toggle(200); // use this to point clicked instance
});
});
You need to change the HTML your PHP code is generating as you will have lots of elements with the same id attribute which is invalid; they must be unique within the document. A class would seem more appropriate in this case.
From there you can use the this keyword to reference the element that raised the event and traverse the DOM to find the related tr.goals. Try this:
.goals {
display: none;
}
$(document).ready(function(){
$(".goals_btn").click(function(){
$(this).closest('tr').next('.goals').toggle(200);
});
});

Copy data between specific <td> tags using jquery

I've a table like this:
<table>
<tr>
<td class="type">Order</td>
<td class="orderid">1002</td>
<td><button class="copy">Copy Row</button></td>
</tr>
<tr>
<td class="type">Order</td>
<td class="orderid">1004</td>
<td><button class="copy">Copy Row</button></td>
</tr>
<tr>
<td class="type">Refund</td>
<td class="orderid">1004</td>
<td><button class="copy">Copy Row</button></td>
</tr>
</table>
I've a script to copy data from a particular "#id" or ".class" element. What, I needed is to find a way to get the data of that particular row whenever, the Copy button is pressed. I want the columns 'orderid' and 'type' values of that particular row to be copied, but I'm not able to find a way to extract the data between the <td> tags with same class names.
Simple answer:
$('.copy').click(function(){
var order_id = $(this).parent().parent().find('.orderid').text();
var type = $(this).parent().parent().find('.type').text();
alert(order_id); ///this wil get you the value
});
I made the result here: http://codepad.viper-7.com/ahsVfB
check it.
<tr>
<td class="type">Refund</td>
<td class="orderid">1004</td>
<button class="copy">Copy Row</td>
</tr>
$(".copy").click(
function(event)
{
var copy=($(event.target).parent().find('.type'));
var order=($(event.target).parent().find('.orderid'));
}
);
You must paste that copied date somewhere. Make this copy and order as global variables. When you click paste, use this variable's value
take a look on this fiddle http://jsfiddle.net/3p29x2s9/11/
var buttons=document.getElementsByClassName("copy");
console.log(buttons);
for(var i=0;i<buttons.length;i++){
buttons[i].onclick=function(){
var columns = this.parentElement.parentElement.getElementsByTagName("td");
var type= columns[0].innerText;
var orderid=columns[1].innerText;
alert(type + " "+orderid);
}
}

multiple child rows in datatable

I have an exiting PHP/javascript application that generates a table with some rows and corresponding child rows(there can be many of them, all are retrived from DB at once), which are hidden by default. Child rows are shown after user clicks button placed in table row.
It looks like this(one parent, two children):
http://i.imgur.com/hul9fT9.png
It is generated like this from php:
for($i = 0; $i < count($shipArr); $i++)
{
echo '
<tr>
<td><span>'.$shipArr[$i]["orderNo"].'</span></td>
</tr>
<tr>
<td>
<table id="details">
;'
for($j = 0; $j < count($shipDetailsArr[$i]); $j++)
{
echo '
<tr>
<td>
<p>
<span>Order Number: </span><span>'.$shipDetailsArr[$i][$j]["lineNo"].'</span>
</p>
</td>
</tr>
';
}
echo '</table>;'
}
Can I use somehow objects $shipArr and $shipDetailsArr populated from db to create the same effect using datatables plugin? How can I achieve this?
Thanks for any help.
I dont't think there is a database plugin which can automatically generate a table. You should use something like a table generator. You can program it yourself in e.g. PHP.
If this is hard for you there are already classes which can do this. Two examples are:
http://www.dyn-web.com/php/table_class/example.php
https://github.com/naomik/htmlgen
Good luck!
I know this question is quite old, but I thought I'd chime in with some support considering another answer here linked to my project.
To solve this problem, I wrote htmlgen, mirrored on packagist. It makes HTML generation with PHP quite nice, if I do say so myself !
use function htmlgen\html as h;
use function htmlgen\map;
$beeData = [
'pop' => 'yup',
'candy' => 'sometimes',
'flowers' => 'so much',
'water' => 'not really',
'sand' => 'indifferent',
'donuts' => 'most definitely'
];
echo h('table',
h('thead',
h('tr',
h('td', 'item'),
h('td', 'do bees like it?')
)
),
h('tbody',
map($beeData, function($value, $key) { return
h('tr',
h('td', $key),
h('td', $value)
);
})
)
);
Output (whitespace not included in actual output)
<table>
<thead>
<tr>
<td>item</td>
<td>do bees like it?</td>
</tr>
</thead>
<tbody>
<tr>
<td>pop</td>
<td>yup</td>
</tr>
<tr>
<td>candy</td>
<td>sometimes</td>
</tr>
<tr>
<td>flowers</td>
<td>so much</td>
</tr>
<tr>
<td>water</td>
<td>not really</td>
</tr>
<tr>
<td>sand</td>
<td>indifferent</td>
</tr>
<tr>
<td>donuts</td>
<td>most definitely</td>
</tr>
</tbody>
</table>

Using slideToggle with table rows (nesting a div) not working

After reading around it seems that a good solution to using slideToggle() on table rows is to nest a div inside. I've tried the following, but it doesn't seem to work at all.
jQuery
function toggle_dropdown(entry_id) {
$(".library-dropdown-animation").slideUp("slow"); // Slide up any that are open
$(".library-edit-dropdown").style.display = "none"; // Set their table row displays to none
$("#library-dropdown-animation-" + entry_id ).slideDown("slow"); // slide the clicked one down
$("#library-edit-dropdown" + entry_id ).style.display = "block"; // set it's parent table row's display to block
}
HTML
<tr class="library-item-header">
<td class="library-item-title" onclick="toggle_dropdown(123);" style="cursor: pointer;">
<?php echo $anime_name; ?>
</td>
</tr>
<tr id="library-edit-dropdown-123" class="library-edit-dropdown" style="display: none;">
<td colspan="4">
<div class="library-dropdown-animation" id="library-edit-animation-123">
</div>
</td>
</tr>
<tr class="library-item-header">
<td class="library-item-title" onclick="toggle_dropdown(124);" style="cursor: pointer;">
<?php echo $anime_name; ?>
</td>
</tr>
<tr id="library-edit-dropdown-124" class="library-edit-dropdown" style="display: none;">
<td colspan="4">
<div class="library-dropdown-animation" id="library-edit-animation-124">
</div>
</td>
</tr>
<tr class="library-item-header">
<td class="library-item-title" onclick="toggle_dropdown(125);" style="cursor: pointer;">
<?php echo $anime_name; ?>
</td>
</tr>
<tr id="library-edit-dropdown-125" class="library-edit-dropdown" style="display: none;">
<td colspan="4">
<div class="library-dropdown-animation" id="library-edit-animation-125">
</div>
</td>
</tr>
So essentially, I've got a td in another row that when it's clicked it slides it's content row (right beneath it) down while sliding any other row up. Since we can't use slide on table row (hide() and show() and toggle() works perfectly fine by the way) i've used a containing div that has content, in this example i've left the content out. In any case, clicking on the td does nothing using this jQuery.
Here is a jsFiddle: http://jsfiddle.net/wxu3E/
Please check this solution: http://jsfiddle.net/wxu3E/2/
i added the events on the Anchor itself not the row by adding a class to it, also I added attribute entry_id
Click
and in the JQuery code the event will be attached to elements with class toggle_dropdown
$(".toggle_dropdown").click
Working Jsfiddle: http://jsfiddle.net/patelmilanb1/LzaZT/
Suggestion: data-attributes might come in handy here... i have added data-attribute in your HTML, please look at the HTML carefully in jsfiddle.
data-id="123"
so your final Jquery looks like this:
$(document).on("click", ".library-item-title", function (e) {
e.preventDefault();
var entry_id = $(this).data("id");
toggleDropdown(entry_id);
});
function toggleDropdown(entry_id) {
$(".library-edit-dropdown").slideUp("slow");
$("#library-edit-dropdown-" + entry_id).slideDown("slow");
}
Error in your code: you are missing - at the end in this line, as your DIV id deos contain -
$("#library-edit-dropdown" + entry_id ).style.display = "block";
try this fiddle for animation: http://jsfiddle.net/patelmilanb1/LzaZT/1/
function toggleDropdown(entry_id) {
$(".library-edit-dropdown").hide("slow");
$("#library-edit-dropdown-" + entry_id).show("slow");
}

Categories