update charcount of multiple divs with single function - javascript

I am trying to use a code snippet I found online to implement charcount. It works for one single text area. I have multiple text areas with different count limits. Here is the code that works for one single form.
Javascript:
function countChar(val,count,focus){
var len = val.value.length;
var lim=count;
var focussed=focus;
if (len >= lim) {
$('#charNum').text(lim - len);
$('#charNum').addClass('exceeded');
/* val.value = val.value.substring(0, lim);*/
}else {
if(focussed===0){
$('#charNum').html('<a> </a>');
}
else {
$('#charNum').text(lim - len);
$('#charNum').removeClass('exceeded');
}
}
};
HTML:
<div id='charNum' class='counter'> </div>
<textarea id='description' name='description' onkeyup=\"countChar(this,200,1)\" onblur=\"countChar(this,200,0)\" rows='10' cols='20'></textarea>
If I have two text areas, how can I modify this code to work ? I know how to get the id of the div in the script, But I dont know how to correctly update the counter div, say #charNum1, and #charNum2. Appreciate some hints. Thanks
EDIT:
I was thinking, I can name the counter div as "Charnum+divName" if that helps

If you attach your event handler(s) with jQuery you can use this within the handler to refer to whichever element the event was triggered on, thus avoiding having to hardcode element ids inside your function.
I'd suggest adding an attribute with the max chars allowed and removing the inline event handlers:
<div id='charNum' class='counter'> </div>
<textarea id='description' name='description' data-maxChars="200" rows='10' cols='20'></textarea>
<div id='charNum2' class='counter'> </div>
<textarea id='otherfield' name='otherfield' data-maxChars="400" rows='10' cols='20'></textarea>
Then:
$(document).ready(function() {
$("textarea[data-maxChars]").on("keyup blur", function(e) {
var $this = $(this),
$counter = $this.prev(),
len = $this.val().length,
maxChars = +$this.attr("data-maxChars");
$counter.text(maxChars - len).toggleClass("exceeded", len > maxChars);
});
});
Demo: http://jsfiddle.net/nnnnnn/GTyW3/

If each textarea is going to have it's own div, you can just add an extra parameter to the countChar function which would be the name of the div. So you'd have something like:
function countChar(val,count,focus, charCountDiv)
then, instead of hardcoding it in the function, the jQuery would be:
$(charCountDiv)
That should do what I think you are looking to do.

Related

For loop with eval not working

My first time writing my own javascript/jQuery for-loop and I'm running into trouble.
Basically, I have a series of divs which are empty, but when a button is clicked, the divs turn into input fields for the user. The input fields are there at the outset, but I'm using CSS to hide them and using JS/jQuery to evaluate the css property and make them visible/hide upon a button click.
I can do this fine by putting an id tag on each of the 7 input fields and writing out the jQuery by hand, like this:
$('#tryBTN').click(function(){
if ( $('#password').css('visibility') == 'hidden' )
$('#password').css('visibility','visible');
else
$('#password').css('visibility','hidden');
}
Copy/pasting that code 7 times and just swapping out the div IDs works great, however, being more efficient, I know there's a way to put this in a for-loop.
Writing this code as a test, it worked on the first one just fine:
$('#tryBTN').click(function() {
for(i = 1; i <= 7; i++) {
if($('#input1').css('visibility') == 'hidden')
$('#input1').css('visibility', 'visible');
}
});
But again, this only works for the one id. So I changed all the HTML id tags from unique ones to like id="intput1" - all the way out to seven so that I could iterate over the tags with an eval. I came up with this:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
if ($(eval('input' + i)).css('visibility') == 'hidden')
$('input' + i).css('visibility', 'visible');
}
});
When I put in the eval stuff - it doesn't work. Not sure what I'm doing wrong. A sample of the HTML looks like this:
<form>
<div class="form-group">
<label for="page">Description: Specifies page to return if paging is selected. Defaults to no paging.</label>
<input type="text" class="form-control" id="input7" aria-describedby="page">
</div>
</form>
You were forgetting the #:
$('#tryBTN').click(function () {
for (i = 1; i <= 7; i++) {
var el = $('#input' + i); // <-- The needed `#`
if (el.css('visibility') == 'hidden') {
el.css('visibility', 'visible');
}
}
});
#Intervalia's answer explains the simple error in your code (the missing #), and the comments explain why you should never use eval() unless you absolutely know it's the right tool for the job - which is very rare.
I would like to add a suggestion that will simplify your code and make it more reliable.
Instead of manually setting sequential IDs on each of your input elements, I suggest giving them all a common class. Then you can let jQuery loop through them and you won't have to worry about updating the 7 if you ever add or remove an item.
This class can be in addition to any other classes you already have on the elements. I'll call it showme:
<input type="text" class="form-control showme" aria-describedby="page">
Now you can use $('.showme') to get a jQuery object containing all the elments that have this class.
If you have to run some logic on each matching element, you would use .each(), like this:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
if( $(element).css('visibility') == 'hidden' ) {
$(element).css( 'visibility', 'visible' );
}
});
});
But you don't need to check whether an element has visibility:hidden before changing it to visibility:visible. You can just go ahead and set the new value. So you can simplify the code to:
$('#tryBTN').click( function() {
$('.showme').each( function( i, element ) {
$(element).css( 'visibility', 'visible' );
});
});
And now that the only thing we're doing inside the loop is setting the new visibility, we don't even need .each(), since jQuery will do the loop for us when we call .css(). (Thanks #TemaniAfif for the reminder.)
So the code becomes very simple:
$('#tryBTN').click( function() {
$('.showme').css( 'visibility', 'visible' );
});

using OOP on .click function in javascript

I am making a webpage that has a baseball strikezone with 25 buttons that will be clickable in 25 locations. I need to know if there is a easier way to do this then what I am doing. Maybe something that will take up far less lines. The button is clicked and then the counter is added by one to another table.
$('#one').click(function(){
counter++;
$('#ones').text(counter);
});
var countertwo = 0;
$('#two').click(function(){
countertwo ++;
$('#twos').text(countertwo);
});
A bit of a guess here, but:
You can store the counter on the button itself.
If you do, and you give the buttons a common class (or some other way to group them), you can have one click handler handle all of them.
You can probably find the other element that you're updating using a structural CSS query rather than id values.
But relying on those ID values:
$(".the-common-class").click(function() {
// Get a jQuery wrapper for this element.
var $this = $(this);
// Get its counter, if it has one, or 0 if it doesn't, and add one to it
var counter = ($this.data("counter") || 0) + 1;
// Store the result
$this.data("counter", counter);
// Show that in the other element, basing the ID of what we look for
// on this element's ID plus "s"
$("#" + this.id + "s").text(counter);
});
That last bit, relating the elements by ID naming convention, is the weakest bit and could almost certainly be made much better with more information about your structure.
You can use something like this:
<button class="button" data-location="ones">One</button>
...
<button class="button" data-location="twenties">Twenty</button>
<div id="ones" class="location">0</div>
...
<div id="twenties" class="location">0</div>
$('.button').on('click', function() {
var locationId = $(this).data('location')
, $location = $('#' + locationId);
$location.text(parseInt($location.text()) + 1);
});
Also see this code on JsFiddle
More clean solution with automatic counter
/* JS */
$(function() {
var $buttons = $('.withCounter'),
counters = [];
function increaseCounter() {
var whichCounter = $buttons.index(this)+1;
counters[whichCounter] = counters[whichCounter] ? counters[whichCounter] += 1 : 1;
$("#counter"+whichCounter).text(counters[whichCounter]);
}
$buttons.click(increaseCounter);
});
<!-- HTML -->
<button class="withCounter">One</button>
<button class="withCounter">Two</button>
<button class="withCounter">Three</button>
<button class="withCounter">Four</button>
<p id="counter1">0</p>
<p id="counter2">0</p>
<p id="counter3">0</p>
<p id="counter4">0</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

RemoveChild does not work

I have a problem with the use of the javascript removeChild function.
Here's my script:
////function to add element by ID////
var i=1;
$("#buttonAdd").live('click',function() {
$("#list1 li:last-child").parent().append('<li>'+
'<label for=njajal[]>njajal'+
'<textarea class="tinymce" name="njajal[]" id="aaa'+i+'"></textarea>'+
'<span><a class="delIt" id="'+i+'"><b>Hapus</a></span></label>'+
'</li>');
tinyMCE.execCommand('mceAddControl', false, 'aaa'+i);
console.log('add '+i);
i++;
});
////Function to delete element by ID/////
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('njajal');
parentEle.removeChild(ele);
}
What is the problem?
Here's the HTML code:
<div id="form">
<form method="post" action="">
<fieldset>
<ol id="list1">
<li>
<label for="njajal[]">njajal
<textarea name="njajal[]" class="tinymce" ></textarea>
</label>
</li>
</ol>
<div id="addOpt">
<a id="buttonAdd" class="bt"><b>Tambah</a>
</div>
</fieldset>
</form>
</div>
Screnshot:
You use jQuery in your first function, so the easiest way to remove that element would be with jQuery:
$('#myElementID').remove();
Here's how you can accomplish the same thing with plain javascript:
var myElement = document.getElementById('myElementID');
myElement.parentNode.removeChild(myElement);
EDIT:
To make things simpler read > as "child of:
From what I can tell the problem is thattextarea > label > li > ol. The only element actually having an id is <ol> so to remove the label (as you show in the image) change delIt to:
function deleteLabelTextArea(){
var elementRemove = document.getElementById("list1").firstElementChild.firstElementChild;
elementRemove.parentNode.removeChild(elementRemove);
}
Old Answer:
As we cannot see the HTML I am not certain what the problem is other than as Marc B has mentioned that 'njajal' is not the parent of eleID. To fix that I would recommend:
function delIt(eleId){
var ele = document.getElementById(eleId);
ele.parentNode.removeChild(ele);
}
The solutions presented till now won't work because tinymce IS NOT the textarea!!
Tinymce gets initialized using the content of a specified html-element - a textarea in this case. After initialization an iframe with a contenteditable body is created where users may edit html content.
In order to get rid of the tinymce editor you need to shut it down first:
tinymce.execCommand('mceRemoveControl', false, 'content'); // your textarea got no id, then tinymce uses 'content' as default editor id
Second, you may remove the initial html elements like label and textarea as the other solutions to your question show.
I just wonder why you have have two tinymce editors on your page?
For me it looks like you might prefer to initialize just one them instead of removing the second one afterwards.

How to Reduce Size of This jQuery Script and Make it More Flexible?

I just created script that shows/hides (toggles) block of HTML. There are four buttons that each can toggle its HTML block. When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button... it hides that HTML block and shows new one.
Here is what I have at the moment:
$('.btn_add_event').click( function() {
$('.block_link, .block_photos, .block_videos').hide();
$('.block_event').toggle();
});
$('.btn_add_link').click( function() {
$('.block_event, .block_photos, .block_videos').hide();
$('.block_link').toggle();
});
$('.btn_add_photos').click( function() {
$('.block_event, .block_link, .block_videos').hide();
$('.block_photos').toggle();
});
$('.btn_add_videos').click( function() {
$('.block_event, .block_link, .block_photos').hide();
$('.block_videos').toggle();
});
Any ideas how to reduce code size? Also, this script isn't very flexible. Imagine to add two new buttons and blocks.
like Sam said, I would use a class that all the blocks share, so you never have to alter that code. Secondly, you can try 'traversing' to the closest block, therefore avoiding it's name. That approach is better than hard coding each specific block, but if the html dom tree changes you will need to refactor. Last, but best, you can pass in the class name desired block as a variable to the function. Below is something you can copy paste that is close to what you started with.
$('.myAddButtonClass').click( function() {
$('.mySharedBlockClass').filter(':visible').hide();
//find a good way to 'traverse' to your desired block, or name it specifically for now.
//$(this).closest(".mySharedBlockClass").show() complete guess
$('.specificBlockClass').show();
});
I kept reading this "When any HTML block is opened, but user has been clicked on other button than that HTML block's associated button" thinking that my eyes were failing me when Its just bad English.
If you want to make it more dynamic, what you can do is add a common class keyword. Then
when the click event is raise. You can have it loop though all the classes that have the
keyword and have it hide them all (except the current one that was clicked) and then show the current one by using the 'this' keyword.
you can refer below link,
http://chandreshmaheshwari.wordpress.com/2011/05/24/show-hide-div-content-using-jquery/
call function showSlidingDiv() onclick event and pass your button class dynamically.
This may be useful.
Thanks.
try this
$('input[type=button]').click( function() {
$('div[class^=block]').hide(); // I resumed html block is div
$(this).toggle();
});
Unfortunatly I couldn't test it, but if I can remember right following should work:
function toogleFunc(clickObject, toogleTarget, hideTarget)
{
$(clickObject).click(function()
{
$(hideTarget).hide();
$(toogleTarget).toggle();
});
}
And the call:
toogleFunc(
".btn_add_videos",
".block_videos",
".block_event, .block_link, .block_photos"
);
and so far
Assuming the buttons will only have one class each, something like this ought to work.
var classNames = [ 'btn_add_event', 'block_link', 'block_photos', 'block_videos' ];
var all = '.' + classNames.join(', .'); // generate a jquery format string for selection
$(all).click( function() {
var j = classNames.length;
while(j--){
if( this.className === classNames[j] ){
var others = classNames.splice(j, 1); // should leave all classes but the one on this button
$('.' + others.join(', .')).hide();
$('.' + classNames[j]).toggle();
}
}
}
All the buttons have the same handler. When the handler fires, it checks the sender for one of the classes in the list. If a class is found, it generates a jquery selection string from the remaining classes and hides them, and toggles the one found. You may have to do some checking to make sure the strings are generating correctly.
It depends by how your HTML is structured.
Supposing you've something like this
<div class="area">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
</div>
...
<div class="sender">
<a class="one"></a>
<a class="two"></a>
<a class="three"></a>
</div>
You have a class shared by the sender and the target.
Your js would be like this:
$('.sender > a').click(function() {
var target = $(this).attr('class');
$('.area > .' + target).show().siblings().hide();
});
You show your real target and hide its siblings, which aren't needed.
If you put the class postfixes in an array, you can easily make this code more dynamic. This code assumed that it doesn't matter in which order toggle or hide are called. If it does matter, you can just remember the right classname inside the (inner) loop, and toggle that class after the loop.
The advantage to this approach is that you can extend the array with an exta class without needing to modifying the rest of the code.
var classes = new Array('videos', 'event', 'link', 'photos');
for (var i = 0; i < classes.length; ++i)
{
$('.btn_add_' + classes[i]).click(
function()
{
for (var j = 0; j < classes.length; ++j)
{
if (this.hasClass('btn_add_' + classes[j]))
{
$('.block_' + classes[j]).toggle();
}
else
{
$('.block_' + classes[j]).hide();
}
}
});
}
You could make this code more elegant by not assigning those elements classes like btn_add_event, but give them two classes: btn_add and event, or even resort to giving them id's. My solution is based on your description of your current html.
Here is what I think is a nice flexible and performant function. It assumes you can contain your links and html blocks in a parent, but otherwise it uses closures to precalculate the elements involved, so a click is super-fast.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script>
<script type="text/javascript">
// Enables show/hide functionality on click.
// The elements within 'container' matching the selector 'blocks' are hidden
// When elements within 'container' matching the selector 'clicker' are clicked
// their attribute with the name 'clickerAttr' is appended to the selector
// 'subject' to identify a target, usually one of the 'blocks'. All blocks
// except the target are hidden. The target is shown.
//
// Change clickerAttr from 'linkTarget' to 'id' if you want XHTML compliance
//
// container: grouping of related elements for which to enable this functionality
// clicker: selector to element type that when clicked triggers the show/hide functionality
// clickerAttr: name of the DOM attribute that will be used to adapt the 'subject' selector
// blocks: selector to the html blocks that will be shown or hidden when the clicker is clicked
// subject: root of the selector to be used to identify the one html block to be shown
//
function initToggle(container,clicker,clickerAttr,blocks,subject) {
$(container).each(
function(idx,instance) {
var containerElement = $(instance);
var containedBlocks = containerElement.find(blocks);
containerElement.find(clicker).each(function(idxC, instanceClicker) {
var tgtE = containerElement.find(subject+instanceClicker.getAttribute(clickerAttr));
var clickerBlocks = containedBlocks.not(tgtE);
$(instanceClicker).click(function(event) {
clickerBlocks.hide();
tgtE.toggle();
});
});
// initially cleared
containedBlocks.hide();
}
);
}
$(function() {
initToggle('.toggle','a.link','linkTarget','div.block','div.');
});
</script>
</head>
<body>
Example HTML block toggle:
<div class="toggle">
a <br />
b <br />
c <br />
<div class="A block"> A </div>
<div class="B block"> B </div>
<div class="C block"> C </div>
</div> <!-- toggle -->
This next one is not enabled, to show scoping.
<div class="toggle2">
a <br />
<div class="A block">A</div>
</div> <!-- toggle2 -->
This next one is enabled, to show use in multiple positions on a page, such as in a portlet library.
<div class="toggle">
a <br />
<div class="A block">A</div>
</div> <!-- toggle (2) -->
</body>
</html>

tag cloud filter

I have a div that contains many spans and each of those spans contains a single href.
Basically it's a tag cloud. What I'd like to do is have a textbox that filters the tag cloud on KeyUp event.
Any ideas or is this possible?
Updated question: What would be the best way to reset the list to start the search over again?
Basically, what you want to do is something like this
$('#myTextbox').keyup(function() {
$('#divCloud > span').not('span:contains(' + $(this).val() + ')').hide();
});
This can probably be improved upon and made lighter but this at least gives the functionality of being able to hide multiple tags by seperating your input by commas. For example: entering this, that, something into the input will hide each of those spans.
Demo HTML:
<div id="tag_cloud">
<span>this</span>
<span>that</span>
<span>another</span>
<span>something</span>
<span>random</span>
</div>
<input type="text" id="filter" />
Demo jQuery:
function oc(a){
var o = {};
for(var i=0;i<a.length;i++){
o[a[i]]='';
}
return o;
}
$(function(){
$('#filter').keyup(function(){
var a = this.value.replace(/ /g,'').split(',');
$('#tag_cloud span').each(function(){
if($(this).text() in oc(a)){
$(this).hide();
}
else {
$(this).show();
}
})
})
})

Categories