I want to decrease the character count of the given text-area as user enters.
I used the below code
var txtArea = $('<textarea class="txtStyle"></textarea>').appendTo('.txtArea');
var rem_txt = 500;
var text = "Characters remaining";
$('.txtStyle').keyup(function () {
debugger;
var txt_txtarea = $(this).val().length;
rem_txt = rem_txt - txt_txtarea;
});
$('<div id="rem">' + text + '=' + rem_txt + ' </div>').appendTo('.txtArea');
But the div is not updating the value of count. please help DEMO HERE
You're not updating the html inside your handler for the keyup, you're just recalculating the remaining amount and not updating the UI.
If you update the inner text inside the event handler you'll see the remaining text:
http://jsfiddle.net/5Lszd/4/
var lengthAllowed = 500,
txtArea = $('<textarea class="txtStyle"></textarea><div id="rem">Characters remaining ' + lengthAllowed + '</div>').appendTo('.txtArea');
$('.txtStyle').keyup(function () {
var charsSoFar = $(this).val().length,
remaining = lengthAllowed - charsSoFar;
$('#rem').text('Characters remaining='+remaining);
});
You haven't handled when the maximum text has been reached though.
Your problem is that you show the initial value outside the keyup function. Fiddle here: http://jsfiddle.net/5Lszd/3/
You can reduce the complexity of your code somewhat to this:
Markup:
<textArea class="txtStyle" maxlength="500"></textArea>
<div id="txtRemaining"></div>
Script
$('.txtStyle').keyup(function () {
$('#txtRemaining').html('Characters remaining ' + (500 - $(this).val().length));
});
Fiddle Demo here
You need to update the content on each keyup event
var txtArea = $('<textarea class="txtStyle"></textarea>').appendTo('.txtArea');
var rem_txt = 500;
var text = "Characters remaining";
$('.txtStyle').keyup(function () {
var txt_txtarea = $(this).val().length;
rem_txt = rem_txt - txt_txtarea;
$('#rem').html(text + '=' + rem_txt); // update the value of #rem
});
$('<div id="rem">' + text + '=' + rem_txt + ' </div>').appendTo('.txtArea');
You need to update the txt, also do not update rem_txt, which supposed to be const
//this should be a const
var rem_txt = 500;
var text = "Characters remaining";
$('.txtStyle').keyup(function() {
var txt_txtarea = $(this).val().length;
updateRemain(rem_txt - txt_txtarea);
});
function updateRemain(rem_txt) {
var rem = $('#rem');
if (!rem.length) {
rem = $('<div id="rem"></div>').appendTo('.txtArea');
}
rem.html(text + '=' + rem_txt);
}
updateRemain(rem_txt);
http://jsfiddle.net/rooseve/WRj5a/1/
you don't update the value after keyup ...
add $('#rem').html(text + '=' + rem_txt); and you should be fine!
http://jsfiddle.net/artificialflow3r/5Lszd/5/
You can simplify your code like this
The main issue is that you are setting rem_txt to 500 subtracting any new characters from an amended value and not from 500. Your code should look a bit more like this
var txtArea = $('<textarea class="txtStyle"></textarea>').appendTo('.txtArea');
$('<div id="rem">Characters remaining = 500 </div>').appendTo('.txtArea');
var text = "Characters remaining";
$('.txtStyle').keyup(function () {
var rem_txt = 500 - $(this).val().length; //Calculate your new length from 500 each time
if($('#rem')) $('#rem').html('Characters remaining = '+rem_txt);
});
I'm creating the div with the initial value in first and then in your keyup function amending it's HTML. You were previously trying to update the HTML for the div outside of the keyup event, so in fact it was only ever running that piece of code once.
fiddle here
Related
I'm attempting to insert a value before and after a selection within my textbox (upon click of a button).
<script type="text/javascript">
$(document).ready(function(){
$('.boldbutton').on('click', function(){
var body = $("#id_body").val();
var start = body.selectionStart;
var end = body.selectionEnd;
var selection = '<' + body.substring(start, end) + '>';
text = body.substring(0, start) + selection + body.substring(end);
$("#id_body").val(text);
});
});
</script>
If I select 'a' and click the boldbutton, this is what appears in the textbox:
a<a>a
What should appear is
<a>
Any thoughts on why this is happening?
thanks!
Try the following:
$('.boldbutton').on('click', function(){
var body = $("#id_body");
var len = body.value.length;
var start = body.selectionStart;
var end = body.selectionEnd;
var selection = body.value.substring(start, end);
var replace = '<' + selection + '>';
body.value = body.value.substring(0,start) + replace + body.value.substring(end,len);
});
The problem could be that the text field has lost its focus by the time the button gets clicked, hence the empty text selection. One thing you could do is to keep a reference to the selected text before it actually loses the focus (with .blur()), and use this data on the button click handler instead of reading from the current state of the selection, which is again, empty.
$('#id_body').blur(function(e) {
$(this).data('selection', {
start: this.selectionStart,
end: this.selectionEnd
});
})
$('.boldbutton').click(function() {
var $body = $('#id_body');
var sel = $body.data('selection');
var text = $body.val();
var start = sel.start;
var end = sel.end;
var selection = '<' + text.substring(start, end) + '>';
if (end) {
text = text.substring(0, start) + selection + text.substring(end);
$body.val(text);
$body[0].selectionStart = start;
$body[0].selectionEnd = start + selection.length;
}
$body.focus();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="id_body" rows="4">Select some text</textarea>
<button class="boldbutton">Bold me</button>
I have a problem in setting width of an element dynamically. I have multiple .each loops and then I append an element which should have calculated width. This is the code I have
$.each(roomsArray, function(index, row) {
$.each(datesArray, function (dateIndex, date) {
$.each(row.calendarList, function(calendarIndex, cal) {
if(cal.roomId == row.id && new Date(cal.dateFrom).toDateString() == new Date(date).toDateString()) {
var cellElements = $(".day[data-date='" + new Date(date).toDateString() + "']");
$.each(cellElements, function (indexElement, element) {
if (element.parentElement.attributes[1].value == cal.roomId) {
var to = new Date(cal.dateTo);
var from = new Date(cal.dateFrom);
//the width should be 44*numOfDays
var numOfDays = Math.ceil((to.getTime() - from.getTime()) / (1000 * 3600 * 24));
console.log(element);
$(element).append(`
//This element needs to take the width
<div id="` + element.attributes[0].value + element.attributes[1].value + `" class="draggable"></div>
`);
//This is just something I tried to do, but it doesnt work.
$('#' + element.attributes[0].value + element.attributes[1].value).css('width', 44 * numOfDays + 'px');
}
});
}
});
})
});
Thanks for help in advance!
Try this fiddle: http://jsfiddle.net/TrrCh/
I think you are trying to run the Javascript before the HTML is loaded. Bind it to the document.ready and it should be working
window.onload=function(){
var elem = document.getElementById('chart');
elem.style.width = 70 + "%";
}
I have a code that puts images on a table(html), and I want to focus on the image that has just appeared.
I know that i have to use $(this) but i don't know how, here is my code
function positioning(year, mon) {
$('#' + year + ' .' + mon).prepend('<img class="black_point" src="./images/circle.png"/>');//that adds the image
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
//here I need the current image I had just add to send to that function
function connect(images) {
var tabBcr = table.getBoundingClientRect();
var imgBcr = image.getBoundingClientRect();
x = imgBcr.left + (imgBcr.width / 2) - tabBcr.left;
y = imgBcr.top + (imgBcr.height / 2) - tabBcr.top;
}
}
I hope I have explained well .
I think it will work, add this where you want to get that img element:
var imgelem=$('#' + year + ' .' + mon).find("img:first");
Please go to: www.designedbychristian.com/template_2
(so far being tested in chrome)
When you click design a bunch of thumbnails appear.
I am trying to use the .each selector to get the src of the image. I want to take that value and apply it to a div that will appear when clicked. (I know how to program that part)
My problem is when I click the thumb nail my alert is giving me the value of all of the thumbnails.
my code is this:
function spawnImages() {
N = 1
for (i = 1; i <= 9; i++) {
var gal = document.getElementById('gallary')
var newDIV = '<img onclick="imageView()" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
$('.gallary').prepend(newDIV)
var min = 3;
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' +N)).css("left", s + "%")
var min = 3;
var max = $(this).height();
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("top", s + "%")
var min = -45;
var max = 45;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("-webkit-transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("-ms-transform", "rotate(" + s + "deg)")
N++
}
}
function imageView() {
$(".thumb-nail").each(function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
})
};
Just use jquery event handlers, get rid of the onclick call in your html and just add this in your javascript.
$(".thumb-nail").on('click', function(){
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
EDIT: didn't think about the images being created dynamically, Popnoodles answer is the right one
pass clicked element reference like this:
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Function:
function imageView(element) {
var imageSrc = $(element).attr('src');
alert($(element).attr('src'));
}
This is exactly how the jQuery API describes the .each() method:
Iterate over a jQuery object, executing a function for each matched element.
When you called $('.thumb-nail') it returned ALL of the elements with the class thumb-nail in a jQuery object. Then when you called .each( function() {} ) on that object, the loop iterated over all of the returned elements.
The easiest way to handle click events in jQuery, is to use the .on() method, as others have pointed out in their answers.
Also, as #Popnoodles mentioned, since these elements are created dynamically, you may need to run your $().on() call explicitly after these elements are created. For that reason, you might wrap it into your spawnImages() function, rather than putting it inside $() as #Popnoodles indicates (i.e. not $( $(element).on('click',function(){}), as $( ) is equivalent to $(document).ready.
The simplest change is this
// send this element to the function
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
function imageView(el) {
var imageSrc = $(el).attr('src');
alert($(el).attr('src'));
};
But it's nice to do things in a more standard fashion...
First get rid of this onclick="imageView()"
var newDIV = '<img src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Since these elements are created dynamically you will need to bind the click event to document or another ancestor that exists, and delegate to each ".thumb-nail".
You also need to run this procedure only when dom is ready ($(function(){...});).
$(function(){
$(document).on('click', ".thumb-nail", function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
});
This question already has answers here:
Clone <div> and change id
(4 answers)
Closed 9 years ago.
I'm trying to clone a div and the input elements inside it. When I clone it, I would like all the ids to increment by one. I've made a fiddle to show you what I'm doing.
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
$(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount);
});
jsFiddle
So far I've cloned the whole div itself and the ids increment but the elements inside remain the same. How would I get all elements inside the div to increment by one?
You have cloned the entire div without modifying it's contents. Try something like:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
$(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount).find('input').each(function (i, e) {
$(e).attr('id', $(e).attr('id').replace(amount, new_amount));
});
});
DEMO
You can recursively replace all id's using find / replace:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount).clone();
cloned_div.insertAfter('#class-' + amount);
cloned_div.find('[id$="-' + amount + '"]').andSelf().each(function(index, child) {
child.id = child.id.replace("-" + amount, "-" + new_amount);
});
});
See jsFiddle
cloned_div.find('[id$="-' + amount + '"]') will search for all child elements having an id attribute ending on "-" + amount, .andSelf() will include the cloned div as you want to change the id there also. Then simply replace the number part in the id of each child (and self).
Try adding this:
$('#class-' + new_amount + ' input:nth-child(1)').attr('id', 'name-class-' + new_amount);
$('#class-' + new_amount + ' input:nth-child(2)').attr('id', 'number-class-' + new_amount);
$('#class-' + new_amount + ' input:nth-child(3)').attr('id', 'book-class-' + new_amount);
just below your $(cloned_div).clone() statement.
See it in action:
http://jsfiddle.net/ZHHcA/1/
These other answers are close, but the problem with their solutions is the original ID prefixes are being lost: number-class-1 is becoming class-1 which is not ideal.
Here is a better option:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
var $cloned = $(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount);
$cloned.children().each(function(){
var $child = $(this);
var oldID = $child.attr('id');
var newID = oldID.replace(/[0-9]+$/, new_amount); // replace just the number, leave the rest of the ID name in tact
$child.attr('id', newID);
})
});
And a working example