Collapsing Table is applying to all tables on page - javascript

Hoping I can get some help with this, I'm building a page that has 5 tables on them.
2 of them are sortable using (http://www.kryogenix.org/code/browser/sorttable/)
A rather large one I want it to be collapsible, and I tried using this:
HTMl drilldown table: Design
However, when I enable it, all the tables become collapsable, this is the jQuery from the above question.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('thead').on('click', function(){
$(this).next('tbody').toggleClass('collapsed');
});
});
I'm not familiar with jQuery, so wasn't sure how to modify it so it only used the one table. I tried using the table ID but it didn't work.
<?php
$qcTable = "<table id ='thcol'>";
foreach($tableArray as $cat=>$catData)
{
$title = ucwords(str_replace("_"," ",$cat));
$score = number_format($catData['sc'],2);
$qcTable .= "<thead><tr><th>$title ($score%)</th></tr></thead><tbody class='collapsed'>";
foreach($catData as $td=>$subCatData)
{if($td != 'a' && $td != 'b' && $td != 'c' && $td != 'sc'){
$getSubCat = explode("__",$subCatData['b']);
if(sizeof($getSubCat) ==1)
$subTitleBuild = $getSubCat[0];
else
{
unset($getSubCat[0]);
$subTitleBuild = implode(" > ",$getSubCat);
}
$subtitle = ucwords(str_replace("_"," ",$subTitleBuild));
$subscore = number_format($subCatData['sc'],2);
$qcTable .= "<tr><td>$subtitle ($subscore%)</td></tr>";
}
} $qcTable .= "</tbody>";
}
$qcTable .= "</table>";
echo $qcTable;
?>
The other two tables theads look like this:
<table class = 'sortable'><thead><th class='sorttable_numeric'>
Ticket ID</th><th>Game</th><th>Agent</th><th>Score</th><th>Star</th></thead><tbody>
Thank you in advance,
C

Your line
$('thead').on('click', ...);
put an handler for the click event on all your <thead></thead> tags, you should put a class on the ones you want to be able to collapse like <thead class="collapsable"></thead> when you write them in PHP, then your line of JavaScript will be :
$('thead.collapsable').on('click', ...);
In that way, only your thead tags with the class collapsable will be able to trigger the collapse.

Related

How to get either select .val() or div .text() from dynamically created elements with same id?

Depending on the user type, my page dynamically creates either a select element (for admins to change) or a div with text (for regular users) using the same id.
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher' >teacher</option>";
echo "</select></td></tr>";
}
else echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
When the page submits, I need either the .val() from the select element or the .text() from the div element.
I can't use .val() on the div element and I can't use .text() on the select element.
Is there a way in jQuery / javascript to get one or the other, depending on which element type was created?
make the else statement as so (use input[type=hidden], to use the .val())
else echo
"<tr>
<td>Type:</td>
<td>
<!-- div to show the value -->
<div>$user_type</div>
<!-- hidden input type to get the value via jQuery .val() -->
<input type='hidden' id='type' value='$user_type'>
</td>
</tr>";
Oh by the way, you can use PHP variables inside strings that are defined with double quotes echo "$someVar";
Since you are printing out from PHP the HTML out put, by the same time you can print a Javascript variable who has what method use to get the value/text. Then, use the variable in your Javascript to perform one query or other.
Something like :
if ($user_type == 'admin') {
echo "<tr><td>Type:</td><td><select id='type' >";
echo "<option value='student' >student</option><option value='teacher'>teacher</option>";
echo "</select></td></tr>";
echo "<script> var method = 'val'</script>";
}
else
{
echo "<tr><td>Type:</td><td><div id='type'>" . $user_type . "</div></td></tr>";
echo "<script> var method = 'text'</script>";
}
You can check it with the following simple code in javascript:
if(document.getElementById("type").tagName == "SELECT") {
//Your code for admin
}
else
{
//Your code if it is not admin
}
You can have the text or the value with a simple and elegant ternary condition :
var result = $("#type").val() !== undefined ? $("#type").val() : $("#type").text();

Get attribute from many divs to toggle class

So I am trying to check a bunch of divs on an inbox page and I am returning an array from an AJAX call to know which divs to change the font-style of. To achieve this, I have to first check their data-value attribute and then add/remove a class(bold vs. normal fro read/unread messages). The problem is that when I refer to the messageDiv object, it toggles all the messages on the page. Looping through the messages makes the most sense to me, but I do not know how to store a div an array to achieve this.
data['messages']=[3,5,8,9]
var messageDiv=$('.widget .inbox-row');
if (data['status']=='A'){//read
if ($.inArray(messageDiv.data('value'),data['messages']) && messageDiv.hasClass('unread-msg')) {
messageDiv.removeClass('unread-msg').addClass('read-msg');
}
}
if (data['status']=='N'){//unread
if ($.inArray(messageDiv.data('value'),data['messages']) && messageDiv.hasClass('read-msg')) {
messageDiv.removeClass('read-msg').addClass('unread-msg');
}
}
This is what a message looks like, iterated many times on the page:
<div class="<?php echo $message_read_status; ?> inbox-row" data-value="<?php echo $messageid; ?>" >
<?php echo $body; ?>
</div>
Sincere thanks for any help. Sorry if this is a pretty specific question. I tried to make it as non-specific as possible.
The problem is e is a set of elements, so when you say messageDiv.data('value'), it will return teh data-value of the first element in the set.
You need to iterate over each item in the array and run the conditions against each one
var messageDiv = $('.widget .inbox-row');
messageDiv.each(function () {
var $this = $(this);
if (data['status'] == 'A') { //read
if ($.inArray($this.data('value'), data['messages']) > -1 && $this.hasClass('unread-msg')) {
$this.removeClass('unread-msg').addClass('read-msg');
}
} else if (data['status'] == 'N') { //unread
if ($.inArray($this.data('value'), data['messages']) > -1 && $this.hasClass('read-msg')) {
$this.removeClass('read-msg').addClass('unread-msg');
}
}
})

No event listener for x-editable table elements

I have a dynamic table, with one column set to have editable elements. Once the page is rendered, I can edit the entry in the first row, but thereafter none of the other rows have event listeners for the id: name. I can't understand why. Here is my code:
$(document).ready(function(){
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'popup';
//make name editable
$('#name').editable();
... });
<tbody>
<?php foreach ($action_lists as $list_item) {
echo "<tr>";
echo "<td> {$list_item["ActionList"]["name"]}</td>";
echo "</tr>";
}?>
</tbody>
$('#name') will query the document based on id so it will return the first matched element so just use class name instead of id and use $(".name"), Then it will apply to all the element
I think instead of calling it from ID, you need to call it using class name, same class can be applied to each column/row and on click at each column/row click event will fire. After that use of "$(this)" will help you.
Try using class instead of id
$(document).ready(function(){
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'popup';
//make name editable
$('.name').editable();
... });
<tbody>
<?php foreach ($action_lists as $list_item) {
echo "<tr>";
echo "<td> <a href=\"#\" class=\"name\" data-pk=\"{$list_item["ActionList"]["list_index"]}\">
data-url=\"/post\" data-type=\"text\" data-placement=\"right\"
data-title=\"Enter new name.\" class=\"editable
editable-click\">{$list_item["ActionList"]["name"]}</a></td>";
echo "</tr>";
}?>
</tbody>
This should work properly

Pass checkbox value to Edit (using href)

I'm trying to get the value of the selected checkbox to be transfered to the next page using href. I'm not in a position to use submit buttons.I want this to be done using JavaScript.
My checkbox is populated with value from a table row-docid. Here is my code for Checkbox in view.php:
... mysql_connect("$host", "$dbuser", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $doctbl_name";
$result=mysql_query($sql);
if(!$result ){ die('Could not get data: ' . mysql_error()); }
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
<tr><td><input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>"
value="<?php echo $row['docid'];?>"></td> ...
I have an EDIT Link as a menu in the top in view.php.
<a href="editdoc.php>Document</a>
My question : How do I pass the value of the checked checkbox when I click the edit link.
Note :I searched for a similar question, but could not find one. If I missed any similar question please provide me with the link.
Thanks in advance.
Lakshmi
Note: changed the id of the checkbox from chk_docid to the dynamic row value ($row['docid']) as suggested by Jaak Kütt.
I found a solution!!!
Though I did it in a different way, I thank Jaak Kütt for all the support and helping me to think of a possible way..
This is what I did.. I named the form as showForm and moved to editdoc.php through the function itself.
My Check Box :
<form name="showForm">
<input type="checkbox" name="chk_docid[]" id="<?php echo $row['docid'];?>" value="<? php echo $row['docid'];?>">
My Link:
<a id="a_editdoc" onclick="getchkVal();" title="Edit Document">Document</a>
The corresponding script:
<script>
function getchkVal() {
var contents, vals = [], mydocid = document.forms['showForm']['chk_docid[]'];
for(var i=0,elm;elm = mydocid[i];i++) {
if(elm.checked) {
vals.push(encodeURIComponent(elm.value));
}
}
contents = vals.join(',');
window.location="editdoc.php"+"?v="+contents;
}
</script>
In the editdoc.php :
<?php
$cval=$_GET['v'];
?>
Thanks.
make sure your inputs have different id-s..
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { ?>
...<input type="checkbox" name="chk_docid[]" class="chk_input"
id="chk_docid<?php echo $row['docid'];?>" value="<?php echo $row['docid'];?>">...
using jQuery:
Document
$("#editdoc").click(function(){
var selection=$("input.chk_input:checked");
if(selection.length){
var href=$(this).attr('href')+'?'+selection.serialize();
$(this).attr('href',href);
}
return true;
});
non-jQuery:
<a onclick="submitWithChecked(this,'chk_input')" href="editdoc.php">Document</a>
function submitWithChecked(e,className){
// fetch all input elements, styled for older browsers
var elems=document.getElementsByTagName('input');
for (var i = 0; i < elems.length; ++i) {
// for each input look at only the ones with the class you are intrested in
if((elems[i].getAttribute('class') === className || elems[i].getAttribute('className') === className) && elems[i].checked){
// check if you need to add ? or & infront of a query part
e.href+=(!i && e.href.indexOf('?')<0)?'?':'&';
// append elements name and value to the query
e.href+=elems[i].name+'='+encodeURIComponent(elems[i].value);
}
}
return true;
}
in editdoc.php fetch the values with php using $_GET['name_of_input_element']

Trying to use Javascript to populate a hidden input

I have this code:
while($row = mysql_fetch_array($res)) {
$name = $row['advertiser'];
$id = $row['id'];
if($row['id'] % 4 == 1 || $row['id'] == 1)
{
echo "<tr>";
}
if($row['availability'] == 0)
{
$td = "<td id='green'>";
}
if($row['availability'] == 1)
{
$td = "<td id='grey'>";
}
if($row['price'] == 0)
{
mysql_query("UPDATE booklet SET availability = 0 WHERE id = '$id'");
}
echo $td . $row['id'] . "<br/><p style='font-size: 6pt;'>" . $name[0] . "<p><img src=" . $row['image'] . "></td>";
if($row['id'] % 4 == 0)
{
echo "</tr>";
}
}
It creates a table. What I want to do is this: if you click on a td, I want to pass the value of that td, for example - the number one (1), if you clicked on the first td - I want to pass this value over to a hidden input so I may later use it elsewhere.
The table looks fine. I know what to do when I have the value in a hidden input. I just need to be able to have the table, when I click on a td, to pass the value over. Or to do anything. onClick doesn't work. Even the absolute simplest isolated JQuery statements don't even come close to parsing. The most complex Javascript that actually has worked on this page is a document.write(). Everything else stumps any known browser.
So, using absolutely any methods, is it a possibility, within the realm of current technology, to have code that does what I want?
Again, I need to have a table cell, when clicked on, pass a variable to a hidden input. I've tried everything.
You'll need to add the click event with JQuery and then use Jquery to set the value... Something like this should work.
$(function() {
$("table#mytable td").mouseover(function() {
//The onmouseover code
}).click(function() {
//The onclick code
$("#hiddenInputID").val(text);
});
});
<td onclick="document.forms[0]['nameofhiddenfield'].value = this.id"> ... </td>
Try to validate your html, you might have mismatched quotes/square brackets somewhere, which breaks Javascript.

Categories

Resources