.length incrementation and decrementation - javascript

Here's my code in javascript:
function length(inputLength){
this.inputLength = inputLength;
document.getElementById('view').innerHTML = inputLength.length;
}
Normally, when I press a key, a counter is incremented and when I delete a char with the backspace key, the counter is decremented.
The problem is when I delete a char, the count is incremented by 1 too then is decremented normally.
Try this code by using the "onkeydown" event.
Can you help me?

Why not simplify it and just do this :
​function calcLength(elem) {
document.getElementById('output').innerHTML = elem.value.length;
}
Where elem is the input. Using elem.value.length will get the length of the content within the input.
An example of the HTML would be this
​<input id="testing" value="" onkeyup="calcLength(this)" />
Length = <span id="output"></span>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Working example here

Related

For every textarea i create, i want it to have its 'personal word count' on it.

The code below is to appear additional 2 textbox and 1 textarea everytime i click a button.
var x=1;
var count=0;
$('body').on('click','#add',function()
{
if(count < 6)
{
$('#div').append("<div class='line'><input type='text' name = 'txta"+x+ "' id='txta"+ x +"'><span class =wordtab></span> <textarea rows='9' onkeyup='countChar2(this)' cols='50' name = 'txtc"+x+ "' id='txtc"+ x +"'></textarea> <span class =wordtab></span><input style = 'width:50px' type='text' name = 'txtb"+x+"' id='txtb"+ x +"'><span class =wordtab></span><button class='delete' value ='Delete Row'>Delete Row</button></div><div style='margin-left: 750px' id='charNum" + x + "'></div>");
count++;
x++;
}
else
alert("Maximum 6 Skills");
});
$('body').on('click','.delete',function()
{
$(this).closest('.line').remove();
count--;
});
The below function is the code that i currently have (which i know its wrong) to put in a counter for every textarea that i added in.
function countChar2(val)
{
var len = val.value.length;
if (len >= 200)
{
val.value = val.value.substring(0, 500);
}
else
{
var id = "charNum" + x;
$(id).text((200 - len)+" words left");
}
};
So my goal is that everytime i click on the add row and start typing on the textarea, it will show the word count for that particular texarea just right below the textarea box.
To get a unique counter added to each textarea, you could append another div to the textarea with a specific class e.g.
Set the HTML structure to something such as:
<textarea></textarea><div class='text-count-area'>Word Count: 0</div>
Add the following JS at the point where each textarea is added e.g. just before 'count++' in your original code (note: this is not the most efficient way of doing this, but this will work easily with your current code):
// Bind the text area to the keyup event
$("textarea").on('keyup', function(val) {
// Simple word count
var words = this.value.match(/\S+/g).length;
// Write the word count to the immediate text-count-area div afterwards
$(this).next(".text-count-area").text("Text count" + words);
});
The word count is kept simple here for readability, but the logic from other answers (highlighted in the comments) could be implemented at this stage.
A JS Fiddle demo of this working is here.
Let see your example:
You add each div by .append method, it's correct
You count input symbols by onkeyup event, it's correct too
All you need is update your countChar2 function because this function has wrong body in that lines:
var id = "charNum" + x;
$(id).text((200 - len)+" words left");
First of all: try to debug your code via developer tools in your favorite browser with breaks in that lines. This step can give your much more and quickly info than posting question in stackoverflow :)
For onkeyup event you should use link to this object instead of id inside your function:
$(val).parent().find('.words-left').val((200 - len));
This line uses val as a link to textarea object in just appended line. .parent() gives you access to wrapper and find() finds input for words left field. (I've added '.words-left' class to your input, see my fiddler bellow). And this code works in stage of your just added line.
Your code of $('body').click() should be executed, when document is fully loaded and DOM ready. But all your ids that you will create in future doesn't appends that DOM. That's why your delete function works properly - that function uses class selector instead of id.
Proposed by me code doesn't uses id selector because it is not needed. All that needs to me - link to current object in new line, val - what I need for that operation.
BTW: When you implement function that works with objects, such as onkeyup='countChar2(this)', better way to use object as passed variable - var countChar = function(obj) {. Because val is using for scalar values in common way.
You can check my code here https://jsfiddle.net/jo0cd3yr/1/

Javascript onclick increment a number as text

I have a problem with Javascript: I'm trying to increment a number which is a string, so I need to parse it, increment the value, and assign that number to the value in the field. But I don't understand why this code doesn't work properly:
<button type="button" onclick="dec()" name="less" style="background-color: orange;border:none;">-</button>
<script>
function dec() {
var x = parseInt(document.getElementById("num").value, 10);
x--;
document.getElementById("num").value = x;
}
While the number is in a div like this:
<div id="num" style="display:inline;">0</div>
Where is the error?
For one hand, if you want to increment the value you need to do x++ instead of x--. And after that, I think you will fix it with:
document.getElementById("num").innerHTML= x;
Because a div does not have a value property.
Just use
document.getElementById("num").innerHTML
instead

Increment and Decrement Javascript not working

i made a JavaScript function to increment and decrement a number in the like button, here is the function
var val = 0;
var negative = false;
$('.i-t').click(function(){
val = val + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});
This function works great on the first click but clicking the second time it doesn't remove the value, is something wrong with the function? here is the button
<button id="myvals" class="myvals">
<i class="myvals" id="i-t"></i>
<span class="myvals" id="voteScore">123</span></button>
i want to change the 123 to 124 if liked and 122 if disliked and it doesn't works, i'm sorry i had to prepare the question better from the beginning
From your comments and update, what you want to do is to increase/decrease the vote count based on whether you have already clicked or not.
In that case, instead of using a variable, you can store the state using a class to support multiple vote button if you need like
$('button.vote').click(function () {
var $btn = $(this).toggleClass('voted');
$(this).find("span.score").text(function (i, val) {
return +val + ($btn.hasClass('voted') ? 1 : -1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="myvals vote"> <i class="myvals" id="i-t">here</i><span class="myvals score">123</span></button>
You need two buttons, one for up and one for down, or you could use one button and a checkbox for up or down, but I think two buttons is simpler.
When reading values from DOM elements, they're generally strings so if numbers are required, particularly for addition, don't forget to convert the value to a number before doing arithmetic.
So the buttons and code can be something like:
function vote(n) {
// Get the element to update
var el = document.getElementById('votes');
// Convert the text content to Number, then add value
el.textContent = Number(el.textContent) + n;
}
Votes: <span id="votes">123</span>
<button onclick="vote(1)">up vote</button>
<button onclick="vote(-1)">down vote</button>
Of course this is just a demo, adapt it however you wish.
Try this:
var val = 0;
var negative = false;
$('.i-t').click(function() {
val = parseInt($("#voteScore").val()) + ((negative) ? -1 : 1);
negative = (negative) ? false : true;
$("#myval").text(val);
});

How to add values from two buttons to single inputbox?

Assume that I have two buttons with the values 'abc' and 'efg' respectively, and an inputbox.
This is what I want to achieve :
When I click the button with the value 'abc' a single time, the value 'a' gets appended to the inputbox. If I press it two times immediately the value suddenly changes to 'b' instead of 'a', and when I do it three times it changes to 'c' instead of 'b'.
I should be able to type double 'a''s (or any of 'a', 'b', 'c') by waiting some time between button clicks on button 'abc'. For instance : I first click button 'abc', then 'a' gets into the inputbox, I wait for a short time and clicks one more time to get another 'a'.
I want the same functionality with all the buttons ('abc' and 'efg').
I have linked sample expected output image.
View this jsfiddle Code
<div ng-controller="MyCtrl">
<input type="text" ng-model="btnTxt[btnarr]">
<button ng-modle="btnarr" ng-Click="change()">abc</button>
</div>
Expected output:
Can anyone help me with this ?
I have tried one without using built-in timer functions, and checking it manually.
Solution at Pastebin : pastebin.com/vHF517FN
See if it's good enough for you. Btw, I didn't really refactor much, will do it if you are satisfied with this (I'm also new to js -_-).
EDIT
Refactored anyway.
Refactored Solution at Pastebin : pastebin.com/EnHz2EHK
EDIT 2
Added it to JSFiddle. However, I had to add everything to HTML part to make it work there, moving script to script part isn't working for me (wonder why).
Solution at JSFiddle
<script>
var prevClick = '!';
var prevClickTime;
var clicks = 0;
function buttonClick(letters) {
var input = document.getElementById("put");
var backLetterIndex = (clicks == 0) ? letters.length-1 : clicks - 1;
if(letters[backLetterIndex] == prevClick) {
var now = (new Date()).getTime();
if(now - prevClickTime < 500) {
var val = input.value;
input.value = val.slice(0, val.length - 1);
}
else
clicks = 0;
}
else
clicks = 0;
prevClickTime = (new Date()).getTime();
prevClick = letters[clicks];
clicks = (clicks + 1) % letters.length;
input.value = input.value + prevClick;
}
</script>
<input id="put" type="text"></input>
<button onClick="buttonClick('abc');">abc</button>
<button onClick="buttonClick('defg');">defg</button>
I get it, you want to do phone keyboard.
I am not sure what exactly is your question so here I wrote complete example
http://jsfiddle.net/daybda4h/5/
Bacically, I wrote click event listener with timer if click comes within 200ms after another click I count up.
clicks++;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
updateInput(clicks, evt.target);
clicks = 0;
}, timeout);
Then, when no more clicks are comming, I take the final number of clicks, take data attribute of a button that says what letters does it control, and take the letter number according to num of clicks.
to add value to input, you simply take input value and add the same value + some custom string.
function updateInput(cl, btn) {
var input = document.getElementById("test");
var letters = btn.getAttribute("data-letters").split("");
input.value = input.value + letters[cl-1];
}
Hope this resolves your problem :)

Counting occurrences of a string in textarea using jQuery/Javascript not updating on new button-press

I have a button that puts the string:
<dt></dt><dd></dd>
on to the end of the text in a textarea with the id #upcoming_text.
I'm using JavaScript to count the number of occurrences of </dd> each time that the button is pressed. If the count of <dt> is greater than 20 then I have an if-statement that prevents any more of the above string being added.
The count works on first page refresh however it does not seem to count the new number of occurrences of </dd> with each subsequent button-press. (I tested this by alerting out the variable numlines, and it remains at the number when the page was refreshed.)
Am I missing some code?
$("#new_act").click(function(){
var text = $('#upcoming_text').text();
var eachLine = text.split('/dd');
var numlines = eachLine.length;
if(numlines > 20){
alert("You've reached the maximum number of acts");
}
else{
if (!$("#upcoming_text").val()){
$("#upcoming_text").val($("#upcoming_text").val()+"<dt></dt>\n<dd></dd>");
}
else{
("#upcoming_text").val($("#upcoming_text").val()+"\n<dt></dt>\n<dd></dd>");
}
}
});
The text method will return the inner text of the element, which is the orignal vale from the HTML code. You should use the val method instead, which returns the current text.

Categories

Resources