Trigger the counter function on page load - javascript

I am using keyup function to calculate the number of words and characters. The function is working fine but when the page loads, initially it does not calculate the default values within the textarea and when any key is pressed then it works fine. I need to trigger the function on page load and calculate the default string This is default text. Here is my code below:
<p> Words <span id="count1">0</span></p>
<p>Characters <span id="count2">0</span></p>
<textarea rows="5" id="mycounter">This is default text</textarea>
<script>
$(document).ready(function () {
$("#mycounter").on("keyup", function () {
var wcounts = 0;
var ccounts = 0;
if ((this.value.match(/\S+/g)) != null) {
wcounts = this.value.match(/\S+/g).length;
}
if ((this.value.match(/\S+/g)) != null) {
ccounts = this.value.length;
}
$('#count1').text(wcounts);
$('#count2').text(ccounts);
});
});
Thanks in advance.

You can use trigger to do it
$(document).ready(function () {
$("#mycounter").on("keyup", function () {
var wcounts = 0;
var ccounts = 0;
if ((this.value.match(/\S+/g)) != null) {
wcounts = this.value.match(/\S+/g).length;
}
if ((this.value.match(/\S+/g)) != null) {
ccounts = this.value.length;
}
$('#count1').text(wcounts);
$('#count2').text(ccounts);
});
$("#mycounter").trigger('keyup');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> Words <span id="count1">0</span></p>
<p>Characters <span id="count2">0</span></p>
<textarea rows="5" id="mycounter">This is default text</textarea>

Related

Error with <input> triggerWord and Javascript

I want to load the page http://example.com by typing trigger in the <input> text box. I made some modifications over time, and at some point it seemed to work but now it doesn't.
How can I make this work? What are some errors that I am missing?
window.onload = function() {
var input = document.getElementById("idname").focus();
}
$(function() {
var triggerWords = ['trigger'];
$('#indexinput').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>
You are registering on keyup two times, following code will work. Dont need to register it with javascript if you are mentioning it inline HTML.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>
<script>
window.onload = function() {
var input = document.getElementById("idname").focus();
}
function myFunction(event) {
var triggerWords = ['trigger'];
for (let i = 0; i < triggerWords.length; i++) {
if (event.target.value == triggerWords[i]) {
window.open("http://example.com/", "_self");
break;
}
}
}
</script>
You have the wrong id in the query selector. It says
$('#indexinput') but must be $('#idname').
Consider using the following snippet:
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
console.log('open new page');
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>
Note that the window.open doesn't work in code-snippets, therefore I added the console.log part.
I also removed this unnecessary part:
window.onload = function() {
var input = document.getElementById("idname").focus();
}
There is no need of myFunction and id was incorrect
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() === triggerWords[i]) {
window.open("https://google.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>

Need to limit the comma(,) entered in textbox

I need to place a limit for the number of commas entered in the text area
I tried these links but it dint help
Limit the number of commas in a TextBox
The comma in the textBox
Iam using php. Is it possible to implement php or javascript here.
You should wait for DOMContentLoaded event, and afterwards bind the textarea with a callback for the "input" event:
const MAX_COMMAS = 3;
document.addEventListener("DOMContentLoaded", function(event) {
let textarea = document.getElementById('textbox');
textarea.addEventListener("input", function(event) {
let matchCommas = this.value.match(/,/g);
if (Array.isArray(matchCommas) && matchCommas.length > MAX_COMMAS) {
this.value = this.value.substring(0, this.value.length - 1); // remove the last comma
alert("MAX COMMAS EXCEEDED!");
}
});
});
<textarea id="textbox" cols="40" rows="4"></textarea>
HTML:
<textarea id="textarea" rows="20"></textarea>
JavaScript:
var textarea = document.getElementById('textarea');
var maxCommas = 5;
var filterCommas = function(event) {
var textCommas = this.value.match(/[,]/g);
if(textCommas.length >= maxCommas && event.key === ',') {
event.preventDefault();
return false;
}
}
textarea.onkeydown = filterCommas;
textarea.onkeypress = filterCommas;
textarea.onchange = filterCommas;`
https://jsfiddle.net/xL04qb8c/2/

jQuery Counter Not Working

JavaScript/jQuery newbie here!
I have the following form here (using bootstrap's disabled class, heads up):
EDIT: the class 'disabled' is a thing in bootstrap, and does properly disable and enable the button if it is there or not.
<form action="" method="post">
<input type="text" id="bio">
<p class="bio-counter"></p>
<input type="text" id="username">
<p class="user-counter"></p>
<input type="submit" class="btn">
</form>
And the following script (I have included jQuery in my head tag correctly):
var main = function() {
$('.bio-counter').text('500');
$('.user-counter').text('0');
var postLengthUser = $('#username').val().length;
var postLengthBio = $('#bio').val().length;
$('#username').keyup(function() {
$('.user-counter').text(postLengthUser);
});
$('#bio').keyup(function() {
var charactersLeftBio = 500 - postLengthBio;
$('.bio-counter').text(charactersLeftBio);
});
if(postLengthUser > 6 && postLengthUser < 21) {
if(postLengthBio >= 0 && postLengthBio < 501) {
$('.btn').removeClass('disabled');
} else {
$('.btn').addClass('disabled');
}
} else {
$('.btn').addClass('disabled');
}
}
$(document).ready(main);
I am running into the following problems:
The 'btn' is not losing it's disabled state, even when I type enough information in the inputs.
The counters are not updating.
What am I doing wrong?
<script>
var main = function () {
var postLengthUser = 0;
var postLengthBio = 0;
$('.bio-counter').text(500);
$('.user-counter').text(0);
var validate = function () {
if (postLengthUser > 6 && postLengthUser < 21) {
if (postLengthBio >= 0 && postLengthBio < 501) {
$('.btn').removeClass('disabled');
} else {
$('.btn').addClass('disabled');
}
} else {
$('.btn').addClass('disabled');
}
}
$('#username').keyup(function () {
postLengthUser = $('#username').val().length;
$('.user-counter').text(postLengthUser);
validate();
});
$('#bio').keyup(function () {
postLengthBio = $('#bio').val().length;
var charactersLeftBio = 500 - postLengthBio;
$('.bio-counter').text(charactersLeftBio);
validate();
});
validate();
}
$(document).ready(main);
</script>
You're validating the disabled condition only at page load, it should be run at each keyup event - i moved it to validate function.
postLengthUser and postLengthBio were updated only at page load too. They should be updated on each key up event too.
Try using:
$('.btn').prop('disabled', true);
and
$('.btn').prop('disabled', false);
instead.

I want to disable the button if specific text has been found in any label

I want to disable the button if specific text has been found in any label.
The following code doesn't run because aTags[i].innerText is not equal to searchText all the time which is wrong because the label has inner text = "a" and the searchText variable have "a" as text - I need it to run in IE
<html>
<script language="javascript">
$(document).ready(function () {
var aTags = document.getElementsByTagName("label");
var searchText = "a";
var found;
for (var i = 0; i < aTags.length; i++) {
if (aTags[i].innerText == searchText) {
document.getElementById('choose').disabled=true;
break;
}
else
{
alert("failed")
}
}
});
</script>
<label> a </label> <br/>
<label> b </label> <br/>
<label> c </label> <br/>
<input type='button' value='choose' id='choose' />
</html>
Seems like there should be easier ways to do that with jQuery
$(function () {
var searchText = "a";
$('#choose').prop('disabled', function() {
return $('label').filter(function(_,el) {
return $.trim( $(el).text() ) === searchText;
}).length > 0;
});
});
FIDDLE
The issue is that your label contains " a " (with the spaces), but you're comparing with "a" (no spaces).
If you want to ignore the spaces, you can use jQuery's $.trim(...) to trim the text off the innerText.
But as you're using jQuery, you can dramatically reduce that code:
$(document).ready(function() {
var searchText = "a";
var found = false;
$("label").each(function() {
found = $.trim($(this).text()) === searchText;
if (found) {
return false; // No need to keep looking
}
});
$("#choose").prop("disabled", true);
});
Since you're already using jQuery, you can do what you like with much less complexity.
This will work:
(function ($) {
var searchText = "a";
$('label').each(function(){
if ($.trim($(this).text()) === searchText) {
$('#choose').prop('disabled', true);
}
});
})(jQuery);
You have to trim label's text. Try with:
if (aTags[i].innerText.trim() == searchText)
or without trim method:
if (aTags[i].innerText.replace(/^\s+|\s+$/g, '') == searchText)
If you want to match if a substring exists you can try with
aTags[i].innerText.indexOf(searchText) > -1
instead of
aTags[i].innerText == searchText

Find empty input elements inside a collection - jQuery

I am trying to find the empty input types like textbox, select and li elements inside a jQuery resultset.
My resultset is (requiredfields) -
$requiredFields = $(".f-form-required.f-form-field").filter(function(){
if($(':input:not([type="hidden"])'))
return $(this);
});
And on that resultset I want to query for empty inputs like textbox, select and li elements. But it seems I am doing something wrong. Can someone suggest me how to do that.
Currently I am doing this to get empty textboxes but not working -
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.val == "") {
emptyInputs = emptyInputs + 1;
}
});
});
I am trying to do same for finding out empty dropdown/select elements and list / li elements over $requiredFields collection.
There is no val property. Try using .val() instead or this.value:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (jQuery(this).val() == "") {
emptyInputs = emptyInputs + 1;
}
});
});
or:
var emptyInputs = 0;
$requiredFields.filter(function(){
$('input[type=text]').each(function(){
if (this.value == "") {
emptyInputs = emptyInputs + 1;
}
});
});
I think you arn't using .filter() quite as it is expected to be used. Consider something like this:
<html>
<body>
<div>
<input type="text" id="text1" class="f-form-required f-form-field" />
<input type="text" id="text2" class="f-form-required f-form-field" value="test" />
<input type="text" id="text3" class="f-form-required f-form-field" />
</div>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function test(){
var $requiredFields = $('.f-form-required.f-form-field');
var $errorFields = $requiredFields.filter(function () {
var $this = $(this);
return $this.is('input') && $this.val() === '';
});
var errorCount = $errorFields.length;
console.log('errors:' + errorCount);
}
$(document).ready(function(){
test();
}
</script>

Categories

Resources