JQuery show / hide button dependents on number of textarea characters - javascript

function countChar(val) {
var len = val.value.length;
if (len == 0 || len == null) {
$('#sending').hide();
} else if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#char_no').text(len + " / 500");
}
};
<textarea id="txt" rows="10" cols="40" onkeyup="countChar(this)"></textarea>
<div id="char_no">0 / 500</div>
<input id="sending" type="submit" value="POST">
Above is my JavaScript and html, it can calculate how many characters are contained in textArea, but I want to hide the submit button if user didn't input anything, or user inputed something but erased them all. any ideas?

You can use toggle to show or hide the button. Also it is recommended to add the event in JavaScript, instead of the markup.
function countChar() {
if (this.value.length > 500) {
this.value = this.value.substring(0, 500);
}
var len = this.value.length;
$('#sending').toggle(!!len); // !! casts a boolean
$('#char_no').text(len + " / 500");
};
$('#txt').on('input', countChar);
Note that this inside the function refers to the element.
DEMO: http://jsfiddle.net/19sLaw7w/1/

<!-- HTML -->
<textarea id = "myinput"></textarea>
<button style = "display: none" id = "mybutton">Submit</button>
Events are neat:
// Pure JS
var myinput = document.getElementById('myinput');
var mybutton = document.getElementById('mybutton');
myinput.onchange = function()
{
var charcount = myinput.value.length;
if(charcount == 0)
{
mybutton.style.display = 'none';
}else{
mybutton.style.display = 'inherit';
}
}
// jQuery
$('#myinput').on('change', function(){
var charcount = $(this).val().length;
if(charcount == 0)
{
$('#mybutton').hide();
}else{
$('#mybutton').show();
}
});

Related

Stop taking input in text-field (tag input)

I am taking some tags name like "study","reading" something like that in the textfield with the help of Bootstrap 4 Tag Input Plugin With jQuery - Tagsinput.js and I have also some predefine tags name contain by buttons. If I click the button then the count of the tag's will increase (count++) and again click this button count will decrease(count--). Same rules for the text-field tags and the total count of the tags in both fields (text and buttons)<=5.
I can count the total tags of the both field but can't stop taking input in text-field when it is greater than 5.
html
<button class="btnr btnr-tags-optional" id="1" onclick="tagSelect(this.id)" >1</button>
<button class="btnr btnr-tags-optional" id="2" onclick="tagSelect(this.id)" >2</button>
<button class="btnr btnr-tags-optional" id="3" onclick="tagSelect(this.id)" >3</button>
My Js
var tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
if (total_tags < 5) {
var tags = document.getElementById(clicked_id);
if (tags.style.borderColor == "rgb(255, 72, 20)") {
tags.style.borderColor = "";
tagsCount--;
} else if (tags.style.borderColor == "") {
tags.style.borderColor = 'rgb(255, 72, 20)';
tagsCount++;
}
total_tags = store + tagsCount;
}
console.log(total_tags);
}
$('#tags_text').on('change', function() {
if (total_tags >= 5) {
$("#tags_text").attr('readonly');
console.log('condition')
} else {
$("#tags_text").removeAttr('readonly');
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
console.log(total_tags);
}
});
Here is the example in jsfiddle
This problem is solved.
I have changed the maxTags value of the plugin with the change of the tags click.
window.tagsCount = 0;
var store = 0;
var total_tags = 0;
function tagSelect(clicked_id) {
var r = ("#" + clicked_id).toString();
if (total_tags < 5) {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
} else {
$(r).addClass("classActiveIssue");
window.tagsCount++;
}
} else {
if ($(r).hasClass("classActiveIssue")) {
$(r).removeClass("classActiveIssue");
window.tagsCount--;
}
}
total_tags = store + tagsCount;
$("#optionsleft").text(total_tags + "/5 selected");
//console.log("total",total_tags);
}
$('#tags_text').on('change', function() {
var items = $("#tags_text").tagsinput('items').length;
store = items;
total_tags = store + tagsCount;
});
and add the line in add:
self.options.maxTags = 5 - window.tagsCount;
Here is the fiddle

javascript disable button conditionally

How come I get the alert's but the button doesn't enable after a negative is changed to a positive after updating the grand total from a select.
Here is the section that is not working:
if ($('.grand_total').val() < 0) {
$('#submit').prop('disabled', true);
alert('negative number found');
} else if ($('.grand_total').val() > 0) {
$('#submit').prop('disabled', false);
alert('positive number found');
}
and here is the complete code:
<script language="javascript">
$(".add_to_total").on('change', function() {
var total = 0;
var grand_total = 0;
$(".dynamic_row").each(function() {
var row = $(this);
var start_hour_am = parseFloat(row.find(".start_hour_am").val()) || 0;
var start_minute_am = parseFloat(row.find(".start_minute_am").val()) || 0;
var end_hour_am = parseFloat(row.find(".end_hour_am").val()) || 0;
var end_minute_am = parseFloat(row.find(".end_minute_am").val()) || 0;
var start_hour_pm = parseFloat(row.find(".start_hour_pm").val()) || 0;
var start_minute_pm = parseFloat(row.find(".start_minute_pm").val()) || 0;
var end_hour_pm = parseFloat(row.find(".end_hour_pm").val()) || 0;
var end_minute_pm = parseFloat(row.find(".end_minute_pm").val()) || 0;
total = ( (Number(end_hour_am) + (Number(end_minute_am))) - (Number(start_hour_am) + Number(start_minute_am)) + (Number(end_hour_pm) + Number(end_minute_pm)) - (Number(start_hour_pm) + Number(start_minute_pm)));
row.find(".total").val(total);
grand_total = Number(grand_total) + Number(total);
});
$("#grand_total").val(grand_total);
if ($('.grand_total').val() < 0) {
$('#submit').prop('disabled', true);
alert('negative number found');
} else if ($('.grand_total').val() > 0) {
$('#submit').prop('disabled', false);
alert('positive number found');
}
});
</script>
Any ideas would be appreciated.
UPDATE
Here is the html for the Grand total:
<input type="text" class="grand_total" name="grand_total" id="grand_total" data-role="none" value="0" size="3" readonly="true">
and here is the button which i'm trying to disable:
<button type="submit" data-theme="e" data-mini="true" data-inline="true" name="submit" id="submit" class="submit" data-icon="check" value="submit-value">Submit</button>
With Nick N's suggestion, still get the same problem with the button disable/enable.
<script language="javascript">
$(".add_to_total").on('change', function() {
var total = 0;
var grand_total = 0;
$(".dynamic_row").each(function() {
var row = $(this);
var start_hour_am = parseFloat(row.find(".start_hour_am").val()) || 0;
var start_minute_am = parseFloat(row.find(".start_minute_am").val()) || 0;
var end_hour_am = parseFloat(row.find(".end_hour_am").val()) || 0;
var end_minute_am = parseFloat(row.find(".end_minute_am").val()) || 0;
var start_hour_pm = parseFloat(row.find(".start_hour_pm").val()) || 0;
var start_minute_pm = parseFloat(row.find(".start_minute_pm").val()) || 0;
var end_hour_pm = parseFloat(row.find(".end_hour_pm").val()) || 0;
var end_minute_pm = parseFloat(row.find(".end_minute_pm").val()) || 0;
total = ( (Number(end_hour_am) + (Number(end_minute_am))) - (Number(start_hour_am) + Number(start_minute_am)) + (Number(end_hour_pm) + Number(end_minute_pm)) - (Number(start_hour_pm) + Number(start_minute_pm)));
row.find(".total").val(total);
grand_total = Number(grand_total) + Number(total);
});
$("#grand_total").val(grand_total);
//if (parseFloat($('.grand_total').val()) < 0) {
// $('#submit').prop('disabled', true);
// alert('negative number found');
//} else if (parseFloat($('.grand_total').val()) > 0) {
// $('#submit').prop('disabled', false);
// alert('positive number found');
//}
var total = parseFloat($('#grand_total').val());
if(total < 0){
$('#submit').prop('disabled', true);
alert('negative number found...');
}
else {
$('#submit').prop('disabled', false);
alert('positive number found...');
}
});
</script>
UPDATE
Ok looks like the issue is because the button is a jquery mobile generated button its not updating the state of the button when a negative value is found, If i refresh the whole form the button state then chnages. I tested this by setting the data-role to none so the submit button becomes a standard form button and the disable/enable functionality works.
Any ideas how i can get around this?
This should work:
var total = parseFloat($('.grand_total').val());
if(total < 0){
$('#submit').attr("disabled", "disabled");
alert('negative number found');
}
else {
$('#submit').removeAttr("disabled");
alert('positive number found');
}
Jquery Mobile: Don't refresh the whole form, but refresh just the button:
$('#submit').button('refresh');
Please note: that I changed '#' to '.'. Dependent on your HTML you could also change this line:
$(".grand_total").val(grand_total);
to:
$("#grand_total").val(grand_total);
you are passing $('.grand_total').val()
instead of $('#grand_total').val()
try this:
var total = parseInt($('.grand_total').val());
if(total < 0){}
else {}

Count textarea characters

I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
$(document).ready(function() {
var tel1 = document.forms["form"].elements.tel1;
var tel2 = document.forms["form"].elements.tel2;
var textarea = document.forms["form"].elements.textarea;
var clock = document.getElementById("clock");
var count = document.getElementById("count");
tel1.addEventListener("keyup", function (e){
checkTel(tel1.value, tel2);
});
tel2.addEventListener("keyup", function (e){
checkTel(tel2.value, tel3);
});
/*$("#textarea").keyup(function(){
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
console.log("Characters left: " + charactersLeft);
});​*/
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});
function checkTel(input, nextField) {
if (input.length == 3) {
nextField.focus();
} else if (input.length > 0) {
clock.style.display = "block";
}
}
function textareaLengthCheck(textarea) {
var length = textarea.length;
var charactersLeft = 500 - length;
count.innerHTML = "Characters left: " + charactersLeft;
}
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks #Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
⚠️ The accepted solution is outdated.
Here are two scenarios where the keyup event will not get fired:
The user drags text into the textarea.
The user copy-paste text in the textarea with a right click (contextual menu).
Use the HTML5 input event instead for a more robust solution:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Here is simple code. Hope it help you
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>
I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.
$(function() {
$("#myTextArea").on("input propertychange", function(event) {
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
$("#counter").html(curlen);
});
});
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />
For those wanting a simple solution without jQuery, here's a way.
textarea and message container to put in your form:
<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>
JavaScript:
<script>
function count_it() {
document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>
The script counts the characters initially and then for every keystroke and puts the number in the counter span.
Martin
They say IE has issues with the input event but other than that, the solution is rather straightforward.
ta = document.querySelector("textarea");
count = document.querySelector("label");
ta.addEventListener("input", function (e) {
count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>
var maxchar = 10;
$('#message').after('<span id="count" class="counter"></span>');
$('#count').html(maxchar+' of '+maxchar);
$('#message').attr('maxlength', maxchar);
$('#message').parent().addClass('wrap-text');
$('#message').on("keydown", function(e){
var len = $('#message').val().length;
if (len >= maxchar && e.keyCode != 8)
e.preventDefault();
else if(len <= maxchar && e.keyCode == 8){
if(len <= maxchar && len != 0)
$('#count').html(maxchar+' of '+(maxchar - len +1));
else if(len == 0)
$('#count').html(maxchar+' of '+(maxchar - len));
}else
$('#count').html(maxchar+' of '+(maxchar - len-1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="message" name="text"></textarea>
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
This solution will respond to keyboard and mouse events, and apply to initial text.
$(document).ready(function () {
$('textarea').bind('input propertychange', function () {
atualizaTextoContador($(this));
});
$('textarea').each(function () {
atualizaTextoContador($(this));
});
});
function atualizaTextoContador(textarea) {
var spanContador = textarea.next('span.contador');
var maxlength = textarea.attr('maxlength');
if (!spanContador || !maxlength)
return;
var numCaracteres = textarea.val().length;
spanContador.html(numCaracteres + ' / ' + maxlength);
}
span.contador {
display: block;
margin-top: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Limit number of lines in textarea and Display line count using jQuery

Using jQuery I would like to:
Limit the number of lines a user can enter in a textarea to a set number
Have a line counter appear that updates number of lines as lines are entered
Return key or \n would count as line
$(document).ready(function(){
$('#countMe').keydown(function(event) {
// If number of lines is > X (specified by me) return false
// Count number of lines/update as user enters them turn red if over limit.
});
});
<form class="lineCount">
<textarea id="countMe" cols="30" rows="5"></textarea><br>
<input type="submit" value="Test Me">
</form>
<div class="theCount">Lines used = X (updates as lines entered)<div>
For this example lets say limit the number of lines allowed to 10.
html:
<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>
js:
$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
$('#countMe').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
});
fiddle:
http://jsfiddle.net/XNCkH/17/
Here is little improved code. In previous example you could paste text with more lines that you want.
HTML
<textarea data-max="10"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span></div>
JS
jQuery('document').on('keyup change', 'textarea', function(e){
var maxLines = jQuery(this).attr('data-max');
newLines = $(this).val().split("\n").length;
console.log($(this).val().split("\n"));
if(newLines >= maxLines) {
lines = $(this).val().split("\n").slice(0, maxLines);
var newValue = lines.join("\n");
$(this).val(newValue);
$("#linesUsed").html(newLines);
return false;
}
});
For React functional component that sets new value into state and forwards it also to props:
const { onTextChanged, numberOfLines, maxLength } = props;
const textAreaOnChange = useCallback((newValue) => {
let text = newValue;
if (maxLength && text.length > maxLength) return
if (numberOfLines) text = text.split('\n').slice(0, numberOfLines ?? undefined)
setTextAreaValue(text); onTextChanged(text)
}, [numberOfLines, maxLength])
A much ugly , but somehow working example
specify rows of textarea
<textarea rows="3"></textarea>
and then
in js
$("textarea").on('keydown keypress keyup',function(e){
if(e.keyCode == 8 || e.keyCode == 46){
return true;
}
var maxRowCount = $(this).attr("rows") || 2;
var lineCount = $(this).val().split('\n').length;
if(e.keyCode == 13){
if(lineCount == maxRowCount){
return false;
}
}
var jsElement = $(this)[0];
if(jsElement.clientHeight < jsElement.scrollHeight){
var text = $(this).val();
text= text.slice(0, -1);
$(this).val(text);
return false;
}
});
For the React fans out there, and possibly inspiration for a vanilla JS event handler:
onChange={({ target: { value } }) => {
const returnChar = /\n/gi
const a = value.match(returnChar)
const b = title.match(returnChar)
if (value.length > 80 || (a && b && a.length > 1 && b.length === 1)) return
dispatch(setState('title', value))
}}
This example limits a textarea to 2 lines or 80 characters total.
It prevents updating the state with a new value, preventing React from adding that value to the textarea.

Categories

Resources