count char of TextArea (retrieved from database) - javascript

I am dynamically creating combination of textarea and label, each combination having different ids. e.g: text-1, text-2 .... for textarea and lab-1, lab-2, .... for labels.
Each label displays the number of characters in each textarea. I am doing this by using following piece of code.
function updateCount(textAreaId, labelId) {
var cs = $('#'+textAreaId).val().length;
$('#'+ labelId').text(cs);
}
Calling above function onkeyUp and onKeyDown on textarea and its working fine.
In some of the textareas I am filling the data from the users last submission from database, In that case it shows default length as 0 till some key in not pressed in the textarea.
I want that as soon as page loads.

You can manually trigger keyup
$('textarea[id^="text-"]').keyup();
Make sure to place this line after binding the keyup events to all textareas

On page load, get the value of the textareas where the value has been added. Get the length of the value, and subtract the length from the maximum length.
$(window).load(function(){
var length = $('textarea').val().length;
Maxmlength = maxmlength - length;
$('span').text(Maxmlength); //element to display the remaiing character.
});
Hope this will help.

<script>
$( document ).ready(function() {
var textAreaId="textArea1";
$('#'+textAreaId).keyup(function() {
updateCount(textAreaId, labelId);
});
});
</script>

Related

Dividing a column of <td> by a an input value

I'm stumped by this current project I'm trying to solve. I'm able to print out the exact results that I want in the console, however I can't figure out how to insert those back into their respective tds within the table.
var calc = $('.calc'),
odds = $('.weight');
$(document).on('keyup keydown', '.calc', function(e){
var curVal = calc.val();
$(document).find('.weight').each(function(){
var oddsVal = ($(this).text() / curVal);
console.log(oddsVal);
});
});
I'm trying to divide the text in each cell of the weight column by the input.calc while a user is entering data into the input so that it updates live.
You can see a Fiddle of it here, with the results printing to the console. How can I make it so each cell in the weight column updates?
Thanks in advance for your help!
The problem is that the cells are getting updated before a value is in the input, which results in 'Infinity' being created 4 times. You can even see it in your console log.
Instead, make sure there is a value in calc before executing the function.
Furthermore, if you repeatedly change the calc field, it will do a new calculation based on the newly replaced values, which does not seem like the correct behavior. So, instead, capture the original values on page load and use those in the calculation:
var originalWeights = getOriginalWeights();
function getOriginalWeights() {
var weights = [];
$('.weight').each(function(index) {
weights[index] = $(this).text();
});
return weights;
}
$(document).on('keyup keydown', '.calc', function(e){
if (!calc.val()) return;
var curVal = calc.val();
$(document).find('.weight').each(function(index){
var oddsVal = (originalWeights[index] / curVal);
$(this).text(oddsVal);
});
});
Fiddle
To solve this you have to edit both HTML and JS code. You should store the original value in a data attribute, and then print it inside the loop using the value parameter of the jquery each function. Here is your fiddle edited, hope it helps!
http://jsfiddle.net/ch1qui/LoLrotkn/3/
You should remove the keydown event from the event delegation as the value on the input box would not be available during keydown. Also having keyup and keydown would trigger the events simultaneously, triggering each block twice. Also you don't need to declare the var calc = $('.calc'), globally since the element would be available during the event target on the document.
$(document).on('keyup', '.calc', function(e){
var curVal = $(this).val();
$('table td.weight').each(function(){
var oddsVal = $(this).text() / curVal;
alert(oddsVal);
});
});
Example : http://jsfiddle.net/LoLrotkn/4/

Jquery each loop showing first value as zero or NaN

I am using jquery to gather data from a dynamically created table via Jquery. I am able to get the data, but now I want to sum up the fields and put the result inside a text field or label etc dynamically when I press enter. I am using the following code:
$("#iq").keypress(function(e)
{
if(e.which==13)
{
var tot=0;
$('#tab .itemtotal').each(function()
{
tot = tot + parseInt($(this).html());
});
$("#totalamount").val(tot);
}
});
My problem is that the value showing in the textfield is zero or NaN for the first time and after that its calculating correctly. I used the same code and associating it with a button and checking its click event and its working properly and showing first item also.
Any suggestions? If need some more clarification let me know. Thanks in advance.

jQuery: Put dynamically generated input values to span/div

I'm trying to create form for printing with dynamically generated inputs.
Contents of the fields is shown later in PreviewDiv.
It works fine as long as I specify where they should be, for example:
$('#Prw_CapacityA_1').text($('#CapacityA_1').val());
$('#Prw_CapacityB_1').text($('#CapacityB_1').val());
$('#Prw_CapacityC_1').text($('#CapacityC_1').val());
But if the user creates 100 fields this would be a lot of code to write.
There must be other methods to fix this dynamically, for example:
$('#Prw_CapacityA_'+ counter).text($('#CapacityA_'+ counter).val());
Here's the js fiddle
You could try using attribute starts with selector to select the elements starting with the specific id's and then loop through them using the each() function.
There is no need to have html within your preview table. You can generate it when the user clicks on preview. Modified fiddle
$('#PreviewButton').click(function(){
var capB = $('td input[id^=CapacityB_]');
var capC = $('td input[id^=CapacityC_]');
var table = $("#AddFieldsToPreviewDiv");
table.empty(); //build table everytime user previews so that previously appended values are removed
table.append('<tr><td>ID</td><td>Text 1</td><td>Text 2</td><td>Text 3</td></tr>');
$('td input[id^=CapacityA_]').each(function(i){
table.append('<tr><td>#'+(i + 1)
+'</td><td>'+$(this).val()
+'</td><td>'+$(capB[i]).val()
+'</td><td>'+$(capC[i]).val()
+'</td></tr>');
});
// Show PreviewDiv and hide FormDiv if PreviewButton clicked
$('#PreviewDiv').show();
$('#FormDiv').hide();
});
You could try giving them a unique class (Normally I'd suggest ID but you're using one) say a class of "getinfo"
You could then try the .each() function
https://api.jquery.com/each/
$( ".getinfo" ).each(function( index ) {
var text = $(this).val();
alert(text);
});
This will make an alert box for every element it finds with the class 'getinfo' and then retrieve the value and display it, I hope this gives you a better idea.
If the amount of inputs can change from one page load to the next then you need to use a loop, rather than pulling all the values by 'hand', More code will help better understand what you're trying to achieve and from what.

Javascript: How to remove the last character from a div or a string?

I have a div with a string of content in it. The content is not stored in a variable and I would like to remove the last character of the text in this div. Any help please?
More info:
I have a text field, and upon entering text into the text field, the text appears in a div in large writing. When the user hits the back-space key, I want the last character in the div to be deleted. I am mainly using jQuery to achieve this. Here is my code:
$(document).ready(function(){
$("#theInput").focus(); //theInput is the text field
$('#theInput').on('keypress', printKeyPress);
function printKeyPress(event)
{
//#mainn is the div to hold the text
$('#mainn').append(String.fromCharCode(event.keyCode));
if(event.keyCode ==8) //if backspace key, do below
{
$('#mainn').empty(); //my issue is located here...I think
}
}
});
I have attempted $('#mainn').text.slice(0,-1);
I have also tried storing the value of #theInput in a variable and then printing it, but that didn't work. Any ideas ?
$('#mainn').text(function (_,txt) {
return txt.slice(0, -1);
});
demo --> http://jsfiddle.net/d72ML/8/
Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html.
On keyup
$("#div").html($("#input").val());
var string = "Hello";
var str = string.substring(0, string.length-1);
alert(str);
http://jsfiddle.net/d72ML/

Populating div in real time with form input data

I have a form (just one field) which I am populating with some data. I would like to get me Div container populated with the data I put there in a real time. So no refresh, after I type in some text in the form field, I get it in the div as well. Does anybody know how to do it? JQuery, AJAX?Any advice appreciated.
var div = $('div')[0];
$('input').bind('keyup change', function() {
div.innerHTML = this.value;
});
Try it out: http://jsfiddle.net/H6P2z/
Of course you should make the selectors specific to your actual elements.
With jQuery you can do this very easily:
$('#textFieldId').bind('change', function (event, previousText) {
$('#divId').html($(this).val());
});
You could bind an onkeyup event to the input field. When the event fires, you can grab the contents of the field and do what you want with it.
This might look like this:
$(selector).keyup(function(e) {
// find the value of the field
var text = $(this).val();
// do something with it
$(yourDivSelector).html(text);
});

Categories

Resources