How to match children innerText with user input using jQuery - javascript

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

Related

Get input value from each row in JavaScript

function shortDescription(a){
var descriptionInput;
var tbl = $(document.getElementById('21.125-mrss-cont-none-content'));
tbl.find('tr').each(function () {
$(this).find("input[name$='6#if']").keypress(function (e) {
if (e.which == 13) {
descriptionInput = $(this).val();
$(this).val(descriptionInput);
$(document.getElementById('__AGIM0:U:1:4:2:1:1::0:14')).val(descriptionInput);
}
console.log(descriptionInput);
});
});
});
}
This code works perfectly but how do I write this in pure JavaScript? I'm mainly interested in this: How do I perform these tasks without jQuery?
for each row, find the input name that ends in 6#if (the column I want)
on enter, get this input value and add to the console it so I know it's there
input id = "grid#21.125#1,6#if" type="text" value"" name="grid#21.125#1,6#if
oninput = shortDescription(this);
It would be great if you could share a piece of HTML on wich we could try some things, but for the moment, here's what your code looks like written in pure JS :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content')
Array.from(tbl.getElementsByTagName('tr')).forEach(function(tr) {
Array.from(tr.querySelectorAll("input[name$='6#if']")).forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
input.value = descriptionInput; // why ??
document.getElementById('__AGIM0:U:1:4:2:1:1::0:14').value = descriptionInput;
}
console.log(descriptionInput);
}
});
});
If you're not OK with the querySelectorAll, you can use getElementsByTagName, it returns a NodeList that you can turn into an array with the Array.from method and the use filter on the name to find the input with a name containing "6#if".
Best practices ...
Since an ID is unique and the methods getElementsByTageName or getElementsByTagName returns a Live HTMLCollection, it's better if you use these elements as unique variables, so you won't ask your browser to fetch them many times.
Since I don't know what your elements means, I will name the variables with trivial names, here's a better version of the code :
var descriptionInput;
var tbl = document.getElementById('21.125-mrss-cont-none-content');
var tr1 = tbl.getElementsByTagName('tr');
var el1 = document.getElementById('__AGIM0:U:1:4:2:1:1::0:14');
var inputsInTr = Array.from(tr1).map(function(tr) {
return Array.from(tr.getElementsByTagName('input'));
}).reduce(function(pv, cv) {
return pv.concat(cv);
});
var myInputs = inputsInTr.filter(function(input) {
return input.name.indexOf('6#if') != 0;
});
myInputs.forEach(function(input) {
input.onkeypress = function(e) {
if (e.keyCode == 13) {
descriptionInput = input.value;
el1.value = descriptionInput;
}
console.log(descriptionInput);
}
});
I didn't try it, hope it's OK.
Hope it helps,
Best regards,

Result not showing in Input text

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

If a specific value is inputed into an input box, display a message using javascript

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

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

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

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

Categories