Counting the number of input's and textarea's with data - javascript

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);

Related

not receive negative numbers

I have the following code: http://jsfiddle.net/ntywf/1987/
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
}));
});
});
what I want is to remove the "-" sign off when it is inserted. what happens is that the cursor is always the last decimal home. I just want this code not to let the user enter negative numbers. How can I do this? (the problem is to move the cursor within the input, since it is always sent to the last character)
You can use a KeyCode (Link) to verify what key you pressed, and use replace to remove it:
$('input').keyup(function(e) {
var code = e.keyCode || e.which;
if(code == 109 || code == 189) { //Enter keycode
//Do something
var valor = $(this).val();
$(this).val(valor.replace(/[-]/g, ''))
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>
Here what I have tried.
JS
$('input').keyup(function() {
var $th = $(this).val();
$th = $th.replace(/[-]/g, "");
$(this).val($th)
console.log( $(this).val());
});
It will remove - sign from data.
This should solve your problem
What I have done is:
I have used the inbuilt HTML input field method setSelectionRange(), which sets the start and end positions of the current text selection in an element. (From MDN)
MDN Reference : https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
JS Code:
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
} ) );
$('input')[0].setSelectionRange(0, 0); //this method sets the range to zero text starting from 0 index to 0 index
});
});
JSFiddle: http://jsfiddle.net/dreamweiver/ntywf/1998/
Use type = "numeric" and min="0" This way you can prevent your text-field from accepting alphabets as well. min=0 will always make sure that it will never accept -ve value.
<input type="number" min="0"/>
JSFIDDLE DEMO will be helpful to you.

if this input has value doesn't work in IE 9

I am using this simple code to filter through a search form with many text inputs and see if they have a value and then add a class.
Works perfectly in Chrome, safari and Firefox but not in IE9.
$('input[type="text"]').filter(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
Please advice, thanks in advance!
EDIT
Change to each but doesn't solve the issue... Here it is with the event that triggers the function...
$(document).on('event-ajax-form-is-loaded', function() {
$('input[type="text"]').each(function() {
if ($(this).val() !== '') {
$(this).addClass('used');
}
});
});
From the limited information you shared, this is how you should be doing this:
$('input[type="text"]').filter(function() {
return $(this).val() !== '';
}).addClass('used');
.filter() is supposed to reduce a set of matched elements so its filter function should always return a bool instead of manipulating the DOM.
Edit: Based on your updated code snippet and the page link you shared in the comments, if you are using jQuery in WordPress, then its always safer to wrap the code like so:
(function($) {
/* jQuery Code using $ object */
})(jQuery);
enter code hereIn JS you can check the element value by getting their tag name
for (var i = 0; i < document.getElementsByTagName('input').length; i++){
if (document.getElementsByTagName('input')[i].value == "")
{
alert("The value of textbox at " + i + " is empty");
}
}
Working Demo
Or like what other people suggest, use a .each in JQuery
$('input[type="text"]').each(function(i){
if ($(this).val() == "") {
alert("The value of textbox at " + i + " is empty");
}
});
anohter Working Demo
If you insist to use filter and here you go
$('input[type="text"]').filter(function()
{ return $( this ).val() != ""; }).addClass("used");
Last Working Demo
and jquery filter reference

How to match children innerText with user input using jQuery

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;
}
});
//
});

Using jQuery to display input TITLE as VALUE (jsfiddle included)

I am trying to come up with a simple jquery input watermark function. Basically, if the input field has no value, display it's title.
I have come up with the jquery necessary to assign the input's value as it's title, but it does not display on the page as if it was a value that was hand-coded into the form.
How can I get this to display the value when the page loads in the input field for the user to see?
Here's the fiddle: http://jsfiddle.net/mQ3sX/2/
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
value = title;
}
$(".result").text(value);
// You can see I can get something else to display the value, but it does
// not display in the actual input field.
});
});
Instead of writing your own, have you considered using a ready-bake version? It's not exactly what you asked for, but these have additional functionality you might like (for instance, behaving like a normal placeholder that auto-hides the placeholder when you start typing).
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
http://archive.plugins.jquery.com/project/input-placeholder
Use the below line of code. You need to specify the input element, and update its value. Since your input field has a class called '.wmk', I am using the below code. You can use "id" and use "#" instead of ".". Read more about selectors at http://api.jquery.com/category/selectors/
$(".wmk").val(value);
Updated jsfiddle http://jsfiddle.net/bhatlx/mQ3sX/9/
Update: since you are using 'each' on '.wmk', you can use
$(this).val(value)
I think what you want is this:
$(document).ready(function() {
$(".wmk").each(function(){
var value = $(this).val();
var title = $(this).attr("title");
if (value == '') {
$(this).val(title);
}
$(".result").text(value);
});
});
May be you want something like below,
DEMO
$(document).ready(function() {
$(".wmk").each (function () {
if (this.value == '') this.value = this.title;
});
$(".wmk").focus(
function () {
if (this.value == this.title) this.value = '';
}
).blur(
function () {
if (this.value == '') this.value = this.title;
}
);
}); // end doc ready

Why is my jquery .each() function not working properly?

I wrote this function:
jQuery(document).ready(function() {
jQuery('input[type=text]').each( function(i) {
thisval = jQuery(this).val();
jQuery(this).blur( function() {
if (jQuery(this).val() == '') {
jQuery(this).val(thisval);
}
}); // end blur function
jQuery(this).focus( function() {
if (jQuery(this).val() == thisval) {
jQuery(this).val('');
};
});// end focus function
}); //END each function
}); // END document ready function
It's designed to get the value of an input, then if the user clicks away without entering a new value, the old value returns. This works properly with one of the inputs on the page, but not the others. However, when I remove the .blur and .focus functions and just use alert(thisval); it alerts the name of each input, so something is wrong with my function, but I can't figure out what. Any help?
You need var when declaring your variable so it's not a global one being shared, like this:
var thisval = jQuery(this).val();
Also since you're dealing specifically with text inputs you can just use the .value DOM property, like this:
jQuery(function() {
jQuery('input[type=text]').each(function(i) {
var thisval = this.value;
jQuery(this).blur( function() {
if (this.value == '') this.value = thisval;
}).focus( function() {
if (this.value == thisval) this.value = '';
});
});
});
thisval is a global variable so it is replaced with each loop. Make it local [stick var in front of it] and it should work like magic.
You should not just keep creating jQuery(this) over and over again. That is very inefficient. jQuery(this) is expensive. You should store one copy in a variable and use the variable.

Categories