get table row data on checkbox check - javascript

Edit : I would like to rephrase my question
I am simple trying to get anchor tag text inside <td> on checkbox check.
Problem is that anchor tag doesn't have id or class
This is a sample of my table
<table class="wp-list-table widefat fixed striped users">
<tbody id="the-list" data-wp-lists="list:user">
<tr id="user-18">
<th scope="row" class="check-column">
<label class="screen-reader-text" for="user_18">Select abc</label>
<input type="checkbox" name="users[]" id="user_18" class="subscriber" value="18">
</th>
<td class="username column-username has-row-actions column-primary" data-colname="Username">
abc
</td>
</table>
I have searched some post and tried to create some function
<script type ="text/javascript">
$('#changeit').click(function(){
var values = [];
$(".wp-list-table input[name='users[]']:checked").each(function(){
row = $(this).closest("tr");
});
alert($(row).find("a")[0]);
});
</script>
this gave me anchor tag href data, but I need text enclosed in anchor tag.
I tried
alert($(row).find("a")[0].text());
alert($(row).find("a")[0].val());
alert($(row).find("a")[0].val);
But they are not giving me the anchor tag text.
Any suggestion will be helpful.

Try this:
function Bindthis() {
$('#changeit').on('click', function() {
alert('1'); //this is hitting
var values = [];
$('.subscriber').attr('checked', true).each(function() {
alert('2');
row = $(this).closest("tr");
});
});
}

This is easily traceable by following some good coding practices.
First, you need your code well indented. Indentation is a must if you want to write good, clean and error free code. Error free because indentation helps a lot to identify different scopes.
Second, ALWAYS look for logs. I know that you don't look for logs because you use alert() instead of console.log(), and also, if you open the console (F12) with your code, you will notice this error:
Uncaught Error: Syntax error, unrecognized expression: #the-list input[name=users[]]:checked
With this, is easy to understand that the selector syntax is wrong. Searching a bit around internet and learning about selectors, you will notice that the syntax needs some quotes, like this #the-list input[name='users[]']:checked.
Seems that you don't understand well how selectors work, so, to avoid this problem and future ones, I recommend you to read a bit about them. This way you will avoid repeating the same selectors questions here. Here is a good reference website, with an online tester: http://www.w3schools.com/cssref/css_selectors.asp

finally I made this code which is working for me
$(".wp-list-table input[name='users[]']:checked").each(function(){
row = $(this).closest("tr");
anchor = $(this).closest('tr').find("a:first");
});
alert($(anchor).text());

Related

Unable to make collapsible work on webpage

I'm attempting to made a collapsible (and hopefully simple) DIV and was working with another answer I had found here on stack overflow but I cannot seem to get it to work on my website. I do have a fiddle with the full links and coding which shows that its actually working (in the fiddle) but then I input the code into my page and it hides the stuff beneath the first picture (using that as the divider) but when I click on it nothing happens (it doesn't display)
Below is the snippet of HTML coding:
<p class="expand-one"> <img src="https://www.mywebsite.net/something/vip1.png"></p>
<p class="content-one">
<td width="33%" align="center" valign="top">
<br>
</td>
<td width="33%" align="center" valign="top">
<a href="http://www.mywebsite.net/bigslice" title="The Big Slice: Home of the Edge">
<font color="#dace77">[ m u s i c ]</font>
</a><br>
<font color="#FAF9B6">$ROOMNAME bigslice$</font><br>$USERLIST bigslice$<br>
</td>
</tr>
</p>
and up in my CSS I have the simple addition of:
<style>p.content-one {
display: none;
}
</style>
And down before the body ends where all my JS scripts are I have
<script>
$('.expand-one').click(function() {
$('.content-one').slideToggle('slow');
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Since the answer was as simple as jQuery not loading before the code using it, I thought I'd post the troubleshooting steps I suggested as an answer. The question may be marked as a duplicate, but if not, maybe someone will stumble upon it and be helped... idk.
Ensure any code using jQuery is added after the jQuery library is included (typically I include jQuery at the end of the body and any custom script after that, but that's personal preference).
Check the brower console (F12) for errors- typically these are easy to grok, or you can search for the error message.
If jQuery attempts to select an element before the element is added (either because the jQuery comes before the HTML code, or because the HTML code is dynamically added after loading), it won't find an element- thus adding a listener won't do anything. Either ensure the code comes after the element, attach the listener to a parent/ancestor and specify which element to listen for (e.g. $(document).on('click', 'p', function() { /*...*/ }) will attach a listener to the entire document which will only run when a paragraph is clicked), or use $(function() { /* code here */ }) to ensure your code doesn't run until the page is done loading.
console.log() is extremely helpful if you're not sure if code just won't run, or if it's running and just not affecting anything. If nothing logs, the code isn't running.

JQuery selector, partial DOM searching for performances

I'm actually working with Jquery and at some point I use Jquery selectors to make my page work. The issue here is that the HTML I work with can get very long depending on the data I work with and it looks like this.
HTML
<div class="mailing"></div>
<input type="text" class="mail_subject"/>
<input type="text" class="mail_body"/> <!-- I can have 1 to n number of these -->
<!-- Preview tags -->
<p class='main_subject'></p>
<p class='main_body'></p>
<!--
And a few more things we don't use here
-->
</div>
<div id="table1">
<table id="ranking">
<tbody>
<!-- Data, can have 0 to ~3500 rows -->
</tbody>
</table>
</div>
As you can see, my page is more or less divided in two parts, the <div class="mailing">, which contains a few forms, and the <div id="table1"> that is about displaying lots of data.
In my mailing div I have a few inputs and an auto-updated preview that takes the data from the inputs. What I have here is a kind of "mail builder" with the preview giving me the result with html formatting.
The problem here is about performance, my JQuery is slowed by the table and I got lag when I type in a form and I don't want it to search the whole document as I already know my data will be in the mailing div.
JS
$('.mailing').on('change click keyup keydown', function () {
// Here I append the mail_subject input to the preview
var text = $(this).val();
$('.main_subject').text($('.subject_select').val());
// Here I append each mail_body input to the preview
$('.bodies_select').each(function () {
text = $(this).val();
/*
* Some computation for the text
*/
jQuery('<span/>', {text: text}).appendTo('.main_body');
});
});
I have a few more functions like theses and a few more computation, but I think we got the idea of what my code looks like.
My question is, is there a way, when I use JQuery selectors like $('.main_subject') or $('.bodies_select') to not search the whole DOM document but only in my mailing div for example? The problem is that I can store my elements in variable since it as multiple occasion to be updated.
You can use context with jQuery to improve performances :
$('.bodies_select', '.mailing')
http://api.jquery.com/jquery/#jQuery1
You can even optimize the selectors with some technics :
https://learn.jquery.com/performance/optimize-selectors/
Sure, you just need to place the parent elemenent before
$('.mailing .main_subject')
You should probably read a bit about selectors
https://api.jquery.com/category/selectors/

How to Modify Content in a Text Block

I have some HTML that looks like this:
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
**Text I want to modify**
<span>more content</span>
</td>
targetTD iterates a dynamic number of times depending on the content being rendered. For each iteration, I need to remove a substring of ": " from the beginning of the code in the text block. Unfortunately it's not in its own element and I don't have the ability to wrap it in a neat and tidy id/class. I did some searching and found some js I thought might do the trick:
<script>
var myString = $('.targetTD').html();
myString = myString.replace(': ','');
$('.targetTD').html(myString);
</script>
But that spits out a console error:
Unable to get property 'replace' of undefined or null reference.
Final Update (Solution)
Thanks to #Vaibhav for coming up with a fix! This script did the trick:
<script type="text/javascript">
$(function() {
$('.targetTD').each(function () {
$(this).html($(this).html().replace(/\:\s/g, ''));
});
});
</script>
Update 1
Thanks to #BenM I was able to stop the error from producing by using the following code:
<script>
$(function() {
$('.targetTD').html(function() { $(this).html().replace(': ', ''); });
});
</script>
Although I now don't get an error message, this still isn't removing the ": " from the text block. Any ideas on why this might be?
Update 2
To provide some SharePoint specifics broadly, in response to a comment from #ElvisLikeBear:
The specific task I'm trying to accomplish is hiding the column name from a grouped by list. In SP2010 this was easy to do by hiding the ms-gb class. In 2013, Microsoft has lumped in the expand/collapse button with this class so hiding it wholesale is not an option. I've successfully hid the span with the column name (in my code above, the span wrapped in the a), but the ": " is unhelpfully still in the text block, and now it's just floating there at the beginning of each category name.
The code is being deployed at the page level as a snippet, using the Script Editor web part.
Brendan, issue with your code is you are replacing the ':' with '' but you are not assigning it to the same td again.
Replace(':','') function replaces only first occurance of ':'.Please follow my code. it will replace all the ':' with ''.
With reference from "targetTD iterates a dynamic number of times depending on the content being rendered"
I assume you need foreach loop to iterate over all the Tds.
Html :-
<table>
<tr>
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
Test:Test1
<span>more content</span>
</td>
</tr>
<tr>
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
Test:Test1:test2
<span>more content</span>
</td>
</tr>
<tr>
<td class="targetTD">
<a href="http://foo.com">
<span>content</span>
</a>
Test:Test1:test3:test4
<span>more content</span>
</td>
</tr>
</table>
Jquery :-
<script type="text/javascript">
$(function() {
$('.targetTD').each(function () {
$(this).html($(this).html().replace(/\:/g, ''));
});
});
</script>
Script is tested and works fine.
Make sure the DOM is ready:
<script>
$(function() {
$('.targetTD').html(function() { $(this).html().replace(': ', ''); });
});
</script>
Your tag indicates that this is executing on a SharePoint site which is why your code isn't firing. You need to deploy it properly for SharePoint.
You can do this in a solution or feature, or if it's a one page script you should use a script web part (called the Content Editor webpart in SharePoint 2010 and 2007), you could also add a code snippet to the page in SharePoint 2013.
You could also add the script into the tag via SharePoint designer however I do not believe that would be best practice except in some very specific scenarios (however it would be the easiest approach for a non-SharePoint Devleoper).

jQuery: Preserve user-inputted line breaks in <textarea>

I've been scouring Google and SO for hours but can't seem to find an answer to this for the life of me!
All I want to do is preserve the line breaks entered into a <textarea> element by the user, to post the content via a jQuery $.ajax() call. If I simply submit the form to a page as usual, this works, but I've been told by my boss to use REST/AJAX.
Many, many posts on SO and across the net in general mention replacing \n's with <br />'s, or using white-space: pre-wrap; in the element's CSS. These solutions do not work for me as the line breaks simply don't show up in Chrome Developer Tools.
Code snippet:
<form id="addPostForm" role="form" method="post" action="/blog">
<div class="form-group">
<textarea rows="5" id="postBody" name="postBody"></textarea>
...more input controls
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<script type="text/javascript">
$(document).on('submit', '#addPostForm', function() {
var postBody = $(this)[0].postBody.value;
...more code
});
</script>
When I enter e.g.:
"This is the first paragraph.
And here is another.
And yet another."
The postBody variable's value is:
"This is the first paragraph. And here is another. And yet another."
This is driving me crazy! Surely this shouldn't be as hard as it seems to be!
P.S. I don't think it should make a difference, but just in case anyone is wondering, I'm using Python/Pyramid, Jinja2 and Bootstrap 3 for this project.
Use this in JS
$("input[type=submit]").click(function(){
$.ajax({
type: "POST",
url: "yoururl",
data: $("#addPostForm").serialize()
(...)
});
});
In your server side code you can get POST value postBody with original spaces.
It would appear to me that this problem stems from the Chrome Dev Tools stripping the line breaks. Change the tool settings, or try something else like firebug.
Try splitting the lines by '\n' (yes I have tested this) and rejoin them with tags, check this out:
$('textarea').val().split('\n')
put this in your onclick function and set a breakpoint on it if you are using Chrome, it splits the lines into an array. if you join them with
.join('<br>')
you should be good to go.
Oops sorry for wasting your time, it was as simple as using $('#postBody').val() instead of $(this)[0].postBody.value. Thanks anyway to all commenters and answerers!

How to connect clickable row to specific data sections retrieved from database?

The title might be a little misleading but it's quite a difficult one to put into words.
I've been trying all day and failed even with attempts from stackoverflow, so I must ask once again for help.
I am retrieving a list of article information from MySQL and displaying them in a table. Once displayed these table rows are clickable by using jQuery .click function, when clicked ckeditor (which is with a display:none;) opens from a <section></section> and hides the whole table.
The issue that I am having is when I click on a row, it should display the data from those specific articles inside the ckeditor, but no matter what the first row data always shows up even if I click on a different row, I can point out that it is due to not having an id so the .click function cannot distinguish which section it is trying to show, but I cannot figure out how to connect the table with the section information.
This is how I am retrieving the data and displaying it in a table, using foreach.
<?php
$getInfo = $articleClass->get_all_article_info();
foreach($getInfo as $data)
{
$article_title = $data['article_title'];
$article_content = substr(htmlentities($data['article_content']),0,50).'...';
$article_content_full = $data['article_content'];
$article_uid = $data['article_uid'];
echo '
<tr id="tr_id" class="'.$article_uid.'">
<td class="marker">
<i class="fa fa-align-left"></i>
</td>
<td class="title">
'.$article_title.'
</td>
<td class="content">
'.$article_content.'
</td>
</tr>
<section id="post_info_id" style="display:none;">
<textarea id="editor1">
<div style="width:468px;">
'.$article_content_full.'
</div>
</textarea>
</section>
';
}
?>
And this is the click function; jQuery.
<script type="text/javascript">
$(document).on('click', '#tr_id', function ()
{
$("#post_info_id").css("display", "block");
$("#table_id").hide();
});
window.onload = function()
{
CKEDITOR.replace( 'editor1' );
};
</script>
I know that the problem is that when I click on the tr, it cannot distinguish the #post_info_id, because it just retrieves about 20 rows of information but the $post_info_id has no specific id to match with the #tr_id, but I have no idea how I could even accomplish this.. I have retrieved the article_uid which is an incremented number when the articles are inserted into the database, and could use that to mark both the #tr_id and #post_info_id but with jQuery I have no idea how to accomplish after what I tried.
I don't want to make this a long question, considering the more I write the less likely I will get an answer but here is what I have tried.
I tried setting the article_uid as the id, but I cannot retrieve the id's of the articles as they're in random, and there's nothing specific that I was able to connect both the post_info_id and tr_id by using .attr('id').
This can be achieved by using the Jquery next() function.
You could change your onclick method to this:
$(document).on('click', '#tr_id', function ()
{
$(this).next('section').css("display", "block");
$("#table_id").hide();
});
And all elements should always have unique ids so here's a way to achieve that:
'<section id="post_info_id"'.$counter.' style="display:none;">
<textarea id="editor'.$counter.'">
<div style="width:468px;">
'.$article_content_full.'
</div>
</textarea>
</section>'
Then declare a variable to keep count outside your loop:
$counter = 0;
Finally, increment the counter at the end of the loop:
$counter++;

Categories