I have the following JQuery code I am working on. When I test it, the expected values are shown in the span but not in the input text box.
JQ
$(function() {
$("#textbox").each(function() {
var input = '#' + this.id;
counter(input);
$(this).keyup(function() {
counter(input);
});
});
});
function counter(field) {
var number = 0;
var text = $(field).val();
var word = $(field).val().split(/[ \n\r]/);
words = word.filter(function(word) {
return word.length > 0 && word.match(/^[A-Za-z0-9]/);
}).length;
$('.wordCount').text(words);
$('#sentencecount').text(words);
}
Please see Fiddle. Please let me know where I have gone wrong. Still new to JS.
Thanks
Change this:
$('#sentencecount').text(words);
to this:
$('#sentencecount').val(words);
The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method. To get the value of a script element, use the .html() method. -> http://api.jquery.com/text/
Trying using val() instead This should fix it up.
http://jsfiddle.net/josephs8/6B9Ga/8/
You can not set text to an input you must use value
try this.
$('#sentencecount').text(words);
//has to be
$('#sentencecount').val(words);
and i have also updated your Jsfiddle
$(function() {
$("#textbox").each(function() {
var input = '#' + this.id;
counter(input);
$(this).keyup(function() {
counter(input);
});
});
});
function counter(field) {
var number = 0;
var text = $(field).val();
var word = $(field).val().split(/[ \n\r]/);
words = word.filter(function(word) {
return word.length > 0 && word.match(/^[A-Za-z0-9]/);
}).length;
$('.wordCount').text(words);
$('#sentencecount').val(words);
}
Related
I am new to jQuery and I can't see where my code is wrong. I am trying to get an element with the id of custom-logo-video to change its innerHTML with an if statement (if it is "" or blank etc). However it is not working. What am I doing wrong?
$(document).ready(function(){
var a = $("#custom-logo-video");
if (!a.trim()) {
// is empty or whitespace
a.innerHTML("easy");
} else {
a.innerHTML("hard");
}
});
you can try:
$(document).ready(function () {
var a = $('#custom-logo-video').html();
if (!$.trim(a)) {
// is empty or whitespace
$('#custom-logo-video').html("easy");
} else {
$('#custom-logo-video').html("hard");
}
});
A few issues with the code
var a = $(#custom-logo-video);
selection requires quotes around it
var a = $('#custom-logo-video');
When you use jquery to select, you have a jQuery object so innerHTML won't work, you want to use either .html() or .text() to get the inner text. Here is how I fixed it.
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.html()) {
// is empty or whitespace
a.html("easy");
}else{
a.html("hard");
}
});
You can read more here: https://learn.jquery.com/using-jquery-core/selecting-elements/
You're using innerHTML which isn't necessary since you're using jQuery. .html() will suffice.
Try this:
$(document).ready(function(){
var a = $("#custom-logo-video");
if ( !a.html().trim() ) {
// is empty or whitespace
a.html('easy');
}
else {
a.html('hard');
}
});
EDIT: fixed typos and logic in code.
Try this as well,
$(document).ready(function () {
var a = $('#custom-logo-video').html();
(a !== null && a.trim().length > 0) ? a.html('hard') : a.html('easy');
});
Try this:
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.trim()) {
// is empty or whitespace
a.text("easy");
} else {
a.text("hard");
}
});
Try this code:
$(document).ready(function(){
var a = $("#custom-logo-video");
// To check if the node is empty or not I am
// calling jQuery api is(':empty')
if (a.is(':empty')) {
// is empty or whitespace
// To replace the innerHTML of a node you call a .html() jQuery api
a.html("easy");
} else {
a.html("hard");
}
});
Working Example
Total number of words will display in the top of Textarea., when i enter or paste some words.
Actually, I gotta total number of words, when i used the element <textarea id="text"></text>.
But i can not get the total number of word using <div id="text"></div>
Is it possible to count all the words within a element <div id="text"></div>?
JS for counting words.
counter = function() {
var value = $('#text').val();
if (value.length == 0) {
$('#wordCount').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
$('#wordCount').html(wordCount);
};
$(document).ready(function() {
$('#text').change(counter);
$('#text').keydown(counter);
$('#text').keypress(counter);
$('#text').keyup(counter);
$('#text').blur(counter);
$('#text').focus(counter);
});
Could someone help me to solve this?
The issue is because val() will retrieve the value of a textarea without a problem, however a div does not have a value property.
For this to work with div elements, you should change val() to text():
var value = $('#text').text();
I guess you need this:
counter = function() {
var value = $('#text').text(); //<----change .val() to .text()
if (value.length == 0) {
$('#wordCount').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
$('#wordCount').html(wordCount);
};
$(document).ready(function() {
counter(); //<---call the function here.
});
You need to call the function on dom ready because all the events you bound on the div needs some event to be happend by the user.
Use text instead of val:
var value = $.trim($('#text').text());
val will give you the value attribute value. Whereas text will give you the innerText of the element(div).
Optimization
var counter = function () {
var value = $.trim($(this).text()); // Trim spaces
if (value.length === 0) {
$('#wordCount').text(0);
return;
}
var wordCount = value.replace(/\s+/g, ' ').split(' ').length;
$('#wordCount').text(wordCount);
};
$(document).ready(function () {
$('#text').on('change keydown keypress keyup blur focus', counter);
});
I'm can't figure out a way of displaying a message if a specific word is inputed into an input box. I'm basically trying to get javascript to display a message if a date, such as '01/07/2013', is inputed into the input box.
Here is my html
<p>Arrival Date</p> <input type="text" id="datepicker" id="food" name="arrival_date" >
I'm using a query data picker to select the date.
You can insert code in attribute onchange
onchange="if(this.value == 'someValue') alert('...');"
Or create new function
function change(element){
if(element.value == 'someValue'){
alert('...');
}
}
And add attribute
onchange="change(this);"
Or add event
var el = document.getElementById('input-id');
el.onchange = function(){
change(el); // if 'el' doesn't work, use 'this' instead
}
I'm not sure if it works, but it should :)
Use .val() to get the value of the input and compare it with a string
var str = $('#datapicker').val(), // jQuery
// str = document.getDocumentByI('datapicker').value ( vanilla js)
strToCompare = '01/07/2013';
if( str === strToCompare) {
// do something
}
And encase this in either change or any keyup event to invoke it..
$('#datepicker').change(function() {
// code goes here
});
Update
Try the code below.
$(function () {
var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.on('change', function () {
var str = $datepicker.val(),
strToCompare = '07/19/2013';
if (str === strToCompare) {
console.log('Strings match')
}
else {
console.log('boom !!')
}
});
});
Check Fiddle
Your input has 2 ids. You need to remove id="food". Then the following should work with IE >= 9:
document.getElementById('datepicker').addEventListener(
'input',
function(event) {
if (event.target.value.match(/^\d+\/\d+\/\d+$/))
console.log("Hello");
}, false);
I have the following structure:
<div id="campaignTags">
<div class="tags">Tag 1</div>
<div class="tags">Tag 2</div>
<div class="tags">Tag 3</div>
</div>
And I'm trying to match user input against the innerText of each children of #campaignTags
This is my latest attempt to match the nodes with user input jQuery code:
var value = "Tag 1";
$('#campaignTags').children().each(function(){
var $this = $(this);
if(value == $(this).context.innerText){
return;
}
The variable value is for demonstration purposes only.
A little bit more of context:
Each div.tags is added dynamically to div#campaignTags but I want to avoid duplicate values. In other words, if a user attempts to insert "Tag 1" once again, the function will exit.
Any help pointing to the right direction will be greatly appreciated!
EDIT
Here's a fiddle that I just created:
http://jsfiddle.net/TBzKf/2/
The lines related to this question are 153 - 155
I tried all the solutions, but the tag is still inserted, I guess it is because the return statement is just returning the latest function and the wrapper function.
Is there any way to work around this?
How about this:
var $taggedChild = $('#campaignTags').children().filter(function() {
return $(this).text() === value;
});
Here's a little demo, illustrating this approach in action:
But perhaps I'd use here an alternative approach, storing the tags within JS itself, and updating this hash when necessary. Something like this:
var $container = $('#campaignTags'),
$template = $('<div class="tags">'),
tagsUsed = {};
$.each($container.children(), function(_, el) {
tagsUsed[el.innerText || el.textContent] = true;
});
$('#tag').keyup(function(e) {
if (e.which === 13) {
var tag = $.trim(this.value);
if (! tagsUsed[tag]) {
$template.clone().text(tag).appendTo($container);
tagsUsed[tag] = true;
}
}
});
I used $.trim here for preprocessing the value, to prevent adding such tags as 'Tag 3 ', ' Tag 3' etc. With direct comparison ( === ) they would pass.
Demo.
I'd suggest:
$('#addTag').keyup(function (e) {
if (e.which === 13) {
var v = this.value,
exists = $('#campaignTags').children().filter(function () {
return $(this).text() === v;
}).length;
if (!exists) {
$('<div />', {
'class': 'tags',
'text': v
}).appendTo('#campaignTags');
}
}
});
JS Fiddle demo.
This is based on a number of assumptions, obviously:
You want to add unique new tags,
You want the user to enter the new tag in an input, and add on pressing enter
References:
appendTo().
filter().
keyup().
var value = "Tag 1";
$('#campaignTags').find('div.tags').each(function(){
if(value == $(this).text()){
alert('Please type something else');
}
});
you can user either .innerHTML or .text()
if(value === this.innerHTML){ // Pure JS
return;
}
OR
if(value === $this.text()){ // jQuery
return;
}
Not sure if it was a typo, but you were missing a close } and ). Use the jquery .text() method instead of innerText perhaps?
var value = "Tag 1";
$('#campaignTags').find(".tags").each(function(){
var content = $(this).text();
if(value === content){
return;
}
})
Here you go try this: Demo http://jsfiddle.net/3haLP/
Since most of the post above comes out with something here is another take on the solution :)
Also from my old answer: jquery - get text for element without children text
Hope it fits the need ':)' and add that justext function in your main customised Jquery lib
Code
jQuery.fn.justtext = function () {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
$(document).ready(function () {
var value = "Tag 1";
$('#campaignTags').children().each(function () {
var $this = $(this);
if (value == $(this).justtext()) {
alert('Yep yo, return');)
return;
}
});
//
});
I have a script that only works in jquery 1.7.2. I'm also getting a lot of conflicts with this script.
Is there an alternative to this approach? I'm trying to count the number of input's and textarea's that have data typed inside them. I just need a number.
Here is my current script:
$('#form_register').on('keyup', function() {
var number = $('#form_register').find('input, textarea')
// filter out every empty input/textarea
.filter(function() {
return $(this).val() != '';
}).length;
$('.inputCount').val('There are ' + number + ' empty input fields');
console.log('test');
});
I'd use the change handler too, to prevent someone paste the text inside a field.
EDIT :
To count upwards as you asked in your comment:
jsBin demo
$('#form_register').on('keyup change', function() {
var number = 0;
$(this).find('input, textarea').each(function(){
if( this.value !== ''){
$('.input_count').val(number++);
}
});
});
To redo to count downwards (DEMO) just use === and exclude the print from the each function:
if( this.value === ''){
number++;
}
$('.input_count').val(number);
If you have more issues, try to wrap the code into:
(function($){ // remap '$' to jQuery
// CODE HERE
})(jQuery);