Limit textarea characters by ID jquery - javascript

The goal: I'm trying to limit all my text boxes in all DIV ID named #boom1.
The problem: Can't get them all (a problem with the loop method in my opinion)
$(function () {
var maxL = 300;
$('#boom1').each(function (i, div) { //I got lost with syntax over here
var text = $('#boom1').text();
if(text.length > maxL) {
var begin = text.substr(0, maxL),
end = text.substr(maxL);
$('#boom1').html(begin)
.append($('<a class="readmore"/>').attr('href', '#').html('read more...'))
.append($('<div class="hidden" />').html(end));
}
});
$(document).on('click', '.readmore', function () {
$(this).next('.hidden').slideDown(750);
})
})
I'll be glad to get some help, with syntax if possible..
Thanks.
Attaching a DEMO

try using following code, working fine
$(function () {
var maxL = 300;
$('.wp-caption-text').each(function (i, div) {
//alert("dfs");
var text = $(this).text();
if(text.length > maxL) {
var begin = text.substr(0, maxL),
end = text.substr(maxL);
$(this).html(begin)
.append($('<a class="readmore"/>').attr('href', '#').html('read more...'))
.append($('<div class="hidden" />').html(end));
}
});
$(document).on('click', '.readmore', function () {
$(this).next('.hidden').slideDown(750);
})
})

$(function () {
var maxL = 300;
$('#boom1').each(function () { // If you don't use them you won't need them here
var text = $('#boom1').text();
if(text.length > maxL) {
var begin = text.substr(0, maxL),
end = text.substr(maxL);
$('#boom1').html(begin)
.append($('<a class="readmore"/>').attr('href', '#').html('read more...'))
.append($('<div class="hidden" />').html(end));
}
});
$(document).on('click', '.readmore', function () {
$(this).next('.hidden').slideDown(750);
});
});

DEMO
id must be unique.
Use classes for multiple usage .
added class boom to each div.
added read less... and read more... toggling feature too.
$(this) refers to the current element in the loop.
$(function () {
var maxL = 300;
$('.boom').each(function (i, div) {
var text = $(this).text();
if (text.length > maxL) {
var begin = text.substr(0, maxL),
end = text.substr(maxL);
$(this).html(begin)
.append($('<a class="readmore"/>').attr('href', '#').html('read more...'))
.append($('<div class="hidden" />').html(end));
}
});
$(document).on('click', '.readmore', function () {
$(this).html(function(_,ctr){
return (ctr == 'read more...') ? 'read less...':'read more...'
});
$(this).next('.hidden').slideToggle(750);
});
});

.each() makes you loop through all instances of an element, so you shouldn't use an ID. The following would iterate on every "some-class" element.
<div class="some-class"></div>
<div class="some-class"></div>
$('.some-class').each(function (i, div) {/* code*/ });

I don't think you can use each on an id - it will only get you the first one. Identifiers should be unique and only appear once per page. So only the first one will be used.
Try adding a class to each '#boom1'.. for example '.boom-class' and then doing jQuery each on it.

Related

jquery cannot get div to show using this selector

I am querying the Twitch API for a list of users in my database, to see if they are online.
I am essentially listing them all, with "display: none" and then unhiding if online:
$('.online_list').each(function (index) {
var tnick = $(this).data('tnick');
$.getJSON("https://api.twitch.tv/kraken/streams?client_id={:twitch_key}&channel="+tnick+"", function(a) {
if (a["streams"].length > 0)
{
alert(tnick);
$(this).show();
console.log(index + ": " + $( this ).text());
}
});
});
In my testing, the alert(tnick) works perfectly, so I know it's running. The problem is $(this).show(); just isn't working.
Here's example HTML:
<div class="online_list" data-tnick="test" style="display: none;">test:Twitch <span>(Online)</span></div>
<div class="online_list" data-tnick="test2" style="display: none;">test2:Twitch <span>(Online)</span></div>
this is the current scope object!
to fix your code you can do the following:
$('.online_list').each(function (index) {
var $that = $(this); // create a temp var that
var tnick = $that.data('tnick');
$.getJSON("https://api.twitch.tv/kraken/streams?client_id={:twitch_key}&channel="+tnick+"", function(a) {
if (a && a["streams"] && a["streams"].length > 0) {
alert(tnick);
$that.show(); // use that instead of this
console.log(index + ": " + $that.text());
}
});
});
Check out this resource for more information on scope & this: http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
EDIT:
Also, like #djxak suggests, you can use the element parameter of the callback, that is more simple and clean in my opinion.
The #djxak suggests:
$('.online_list').each(function (index, element) {
//... (scope1 code)
$.getJSON("", function(a) {
//... (scope2 code)
$(element).show();
});
});
My approach:
$('.online_list').each(function (index) {
//... (scope1 code)
var $current = $(this);
$.getJSON("", function(a) {
//... (scope2 code)
$current.show();
});
});
Info about each function and element parameter in jQuery docs: https://api.jquery.com/each/#each-function

How to create html tags each with their ID via a button with JavaScript?

I have a button in html to click it executes a JavaScript function that creates a new field with id in a hidden div.
I wanted each new field (tag) has created its "ID" specifies, not an ID for everyone as is my code (below). I need to be different to record in the database that is entered in each.
Can you help me ?
$(document).ready(function () {
$('#addpergunta').click(function () {
var x = 1;
var div = $('#perg-box');
var divtext = $('<div />');
var text = $('<select />');
text.attr('class', 'form-control').attr('id', 'id-pergunta' + x);
divtext.append(text);
div.append(divtext);
$('#div_perg').show();
});
});
Here:
$(document).ready(function () {
var count = 1
$('#addpergunta').click(function () {
var div = $('#perg-box');
var divtext = $('<div />');
var text = $('<select />');
text.attr('class', 'form-control').attr('id', 'id-pergunta' + count);
divtext.append(text);
div.append(divtext);
count++;
$('#div_perg').show();
});
});

Print values associated with checkboxes in HTML on button click event of JavaScript

Planning to get the specific ID values from the selection on the HTML page (selection here means checked boxes). Here is my code for a button click event(button will fetch the row numbers or ids):
$("a", button).click(function () {
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
console.log($(this));
}
});
});
This returns addtional information on rows + tr tag, however, I just want the ID part of it. Here is sample output I am getting out of above code:
[tr#row-12150.row.oddSelected, context: tr#row-12150.row.oddSelected]
[tr#row-12151.row.evenSelected, context: tr#row-12151.row.evenSelected]
This means I have selected 12150 and 12151 out of the #groups table. How do I just pull the row numbers 12150 and 12151 and not the entire detailed output and I want this to store in an array/(JS array) for multiple row numbers.
You have the row as per the .find('tr'), your should just be able to go:
console.log($(this).attr('id')); //this should show the id in your console.
so your code becomes:
$("a", button).click(function () {
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
console.log($(this).attr('id'));
}
});
});
Then to just get the number you can use:
var number = $(this).attr(id).split('-')[1] //assuming it's always row-<<some number>>
putting it all together:
$("a", button).click(function () {
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var number = $(this).attr('id').split('-')[1] //assuming it's always row-<<some number>>;
console.log(number);
}
});
});
To store it in an array:
$("a", button).click(function () {
var checkedRows = []; //define empty array.
var count = 0; //keep a counter to use for the array.
$('#groups').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
var number = $(this).attr('id').split('-')[1];
checkedRows[count] = number; //add the number to our array.
count++; //increase the count
}
});
});
Make sure your form and your button have id's first then try this instead:
$('#buttonId').click(function(){
$('#formId input:checked').each(i, e){
console.log($(e).attr('id'));
}
});

jQuery dictionary alphabet filter to SharePoint list

I have a list in SP2013 which I am pulling the list items using Javascript on a publishing page. I need to apply alphabetic filtering to this list, but the filter doesn't functioning on this list; however, the filter works perfectly on plain static text. Here is my code to pull the list items:
$(function () {
if (glossaryQuery && glossaryQuery.Rows) {
var liGlossaryHTML = [];
$('#glossary_list').toggle();
$.each(glossaryQuery.Rows, function (index, r) {
liGlossaryHTML.push('<li><strong>' + r.Title + '</strong><br/>' + r.Definition + '</li>');
});
$('#glossary_list ul').html(liGlossaryHTML.join(''));
}
});
and here is the filter:
var triggers = $('ul.alphabet li a');
var filters = $('#glossary_list ul li');
triggers.click(function() {
var takeLetter = $(this).text(), result = 0;
filters.parent().hide();
filters.each(function(i) {
if ( RegExp('^'+takeLetter).test($(this).text()) ) {
result += 1;
$(this).parent().fadeIn(222);
}
});
});
and the HTML:
<div id="glossary_list" style="display:none;">
<ul></ul>
</div>
Any help is so appreciated.
My suspicion is that because you're adding the list items after page load that filters doesn't actually match anything at the time that it is run. I suggest moving the assignment inside the click handler. There are some other improvements you could make to make it more efficient/readable as well.
$('ul.alphabet li a').click(function() {
var takeLetter = $(this).text(),
result = 0
expr = new RegExp('^' + takeLetter);
var filters = $('#glossary_list ul li')
.parent()
.hide();
filters.each(function(i) {
var $filter = $(this);
if (expr.test($filter.text())) {
result += 1;
$filter.parent().fadeIn(222);
}
});
});

Reusable jQuery truncate function

So I have created the following code to deal with one instance of a string that requires truncating with expandable and collapsable click events.
$(document).ready(function () {
var Element = $("[class*='truncate']");
var FullText = $(".truncate").text();
var Show = "<span class='show'> [...]</span>";
var Hide = "<span class='hide'> [ ]</span>";
var shortString = FullText.substring(0, 5);
if (FullText.length > 5) {
$(Element).html(shortString + Show);
}
$(Element).on("click", ".show", function () {
$(Element).html(FullText + Hide);
});
$(Element).on("click", ".hide", function () {
$(Element).html(shortString + Show);
});
});
Which truncates the following HTML
<div class="truncate">MBK-40B-FRLBBLCSLWLHBLHSLSALSAS32PDL</div>
The above code works perfectly for one instance of the class .truncate but when adding more things get a bit messy. How can I make this code work when there are many elements with this class, some of which will need to be truncated while others won't?
We can learn about the .each() jQuery method, here are some docs: http://api.jquery.com/each/
.each() will go through each element that was found with the selector and give you access to it through the this keyword, allowing you to run your code for one element at a time.
$(document).ready(function () {
var Show = "<span class='show'> [...]</span>";
var Hide = "<span class='hide'> [ ]</span>";
$(".truncate").each(function(){
var Element = this;
var FullText = $(Element).text();
var shortString = FullText.substring(0, 5);
if (FullText.length > 5) {
$(Element).html(shortString + Show);
}
$(Element).on("click", ".show", function () {
$(Element).html(FullText + Hide);
});
$(Element).on("click", ".hide", function () {
$(Element).html(shortString + Show);
});
});
});
There are better ways to do this, but .each() is a quick fix. What I would be concerned about is turning all those listeners off, I'm not sure what you are doing with your code later, but you don't want memory problems. Any suggestions?
https://jsfiddle.net/5dtmm9kn/
The JS
$('[truncate]').each(function( index ) {
var howmuch = $(this).attr('truncate');
var title = $( this ).text();
var shortText = jQuery.trim(title).substring(0, howmuch)
.split(" ").slice(0, -1).join(" ") + " <span>...</span>";
$( this ).html(shortText);
});
The html
<h3 truncate="40">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h3>
The css
[truncate] span{
font-size: 0.6em;
opacity: 0.6;
}

Categories

Resources