comparing variable in javascript - javascript

I am in a predicament. I have been trying to compare two variables in javascript and then assign a class to parent element if matched. But i am having no success in this. I have searched through all possible codes and tried them but not able to get it working. The code i have written so far is as below:
$('div#encased a').click(function(){
$('ul#filter .current').removeClass('current');
var class_name = ($(this).parent().attr('class').replace('-',' '));
var className = class_name.toString();
alert(className);
$('ul#filter li').each(function(){
/*1st version
var filterValue = $(this).text().toLowerCase();
var filterValstr = filterValue.toString();
alert(filterValstr);
if(filterValstr==className)
{
alert("match!")
$(this).parent().addClass('current');
}*/
/*2nd version*/
if($(this).text().toLowerCase() == class_name)
{
$(this).parent().addClass('current');
}
/*this works which according to me means it is not entering the if clause
else{
$(this).parent().fadeOut('slow').addClass('hidden');
}*/
});
});
As per my knowledge the value is not going inside the if command at all as i tried using else function and that works. I am sure theres some silly error i am doing. I have tried 2 methods here and i have commented one but presented both of them here to know if any of them should be correct.
Basically on click of an image in my div#encased element the class name of the image is taken and then compared with the text in the filter menu above. If it matches the matched filter text should be assigned the class of current. Hope you are getting what i am trying to explain. Please help. thanks

Your code isn't clear, and kind of a spaghetti one, but maybe your problem is with white spaces, try trim them
var filterValue = $.trim($(this).text().toLowerCase());
And you should know that string.toString() return the string...
Example:
var str = "bla bla bla";
alert(str.toString === str); // true!

Related

Detect Once a Certain Word Has Just Been Entered in a Textarea

Considering features like EditArea's and CodeMirror's autocomplete, I was wondering if, like Dreamweaver, there is a way to detect if the last word you entered is in a certain list then provide the same kind of suggestion box but with the function's arguments. I imagine you would use a regular expression on the entire field or possibly split() the whole thing (or the current line) then use the length attribute of the array to find the last bit of text, then do something involving an indexOf-like operation; however, this seems like it would get a bit resource-intensive. It almost looks like I've answered my own question, but it always helps to fully explain one's quandary, especially publicly. There's gotta be a better solution than mine. I appreciate any input. Thank you.
Put the list of words to match in an object, have the text or options to display as the value. Then on keyup or keypress you can get the last word of the text area using a function like:
function showLastWord(id){
var el = document.getElementById(id);
var lastWord = el.value.match(/\w+$/);
return lastWord? lastWord[0] : '';
}
Then check if the word is in the list and do stuff appropriately.
Edit
A small example is:
<textarea onkeyup="showHelp(this);"></textarea>
<script>
var getLastWord = (function() {
re = /\w+$/;
return function (s){
var lastWord = s.match(re);
return lastWord? lastWord[0] : '';
}
}());
var keyWords = {foo:'foo was typed',bar:'bar was typed'};
function showHelp(el) {
var lastWord = getLastWord(el.value);
// Check for matching own property of keyWords
if (keyWords.hasOwnProperty(lastWord)) {
// Do stuff
console.log(keyWords[lastWord]);
}
}

Trying to .replace() Without Success

I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,
item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});
this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/
Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle
also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));

Extracting specific text from select option boxes

It's possible I'm just misusing .filter() here, but I've been trying to extract a particular piece of text from javascript option boxes without much success.
In short, each of my option boxes has a bunch of info, then, in brackets, ([x] items left in stock).
I'd like to extract that [x], but I can't seem to get any sort of regular expression filtering working in jQuery - or, perhaps, I'm doing it wrong.
In short, if anyone could complete the below, I'd be very appreciative:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
[ your code here]
});
Any help very appreciated.
Something along these lines:
$('.productSelect').change(function() {
selectedItem = $(this + 'option:selected').text();
# Now grab the integer "x" inside the ([x] items left in stock) part of the text
var n = selectedItem.match(/(\()(\d+)(\))/)[2];
});
Of course, this expression depends on the fact that your data is formatted as (number) string
This should get you what you need.
var pattern=/\[(\d+)\] items left in stock/;
var qty = pattern.exec(selectedItem)[1];
So you should use the JavaScript string.match function
var s = "[100] items left in stock";
var p = s.match(regexp);

How do I get element's className inside loop of elements?

I am trying to create a function that given a divid, and a list of classes, will then do some text replacing inside them.
Having learned of how Firefox Dom is handling text nodes differently, I read that I had to use javascript to loop through the elements, sibling to nextSibling.
The last obstacle I had in my script, of which you see a small portion of, is getting the classname. I need the class name so that I can filter down what content get's text replaced.
Having looked all the answers, and with the help of a co-worker named Ryan at work, we have redone this in jquery.
$(divid).find(".status_bar").each( function() {
var value = $.trim($(this).text());
// if value is not defined thru browser bugs do not replace
if (typeof(value) != 'undefined') {
// it is a text node. do magic.
for (var x = en_count; x > 0; x--) {
// get current english phrase
var from = en_lang[x];
// get current other language phrase
var to = other_lang[x];
if (value == from) {
console.log('Current Value ['+value+'] English ['+from+'] Translation ['+to+']');
value = to;
$(this).attr('value', to);
}
}
}
});
This currently works in all areas, except in the replacing of text.
The reason I had originally with doing this in jQuery, had to be not sure I could loop thru elements, and avoid the problem with firefox and text nodes.
I am doing a loop of all elements inside a div, and I now need to get the classname of the element that I am looping by.
Then i can check if the current element's class is one, I need to do something with...
// var children = parent.childNodes, child;
var parentNode = divid;
// start loop thru child nodes
for(var node=parentNode.firstChild;node!=null;node=node.nextSibling){
var myclass = (node.className ? node.className.baseVal : node.getAttribute('class'));
}
But this code for getting the classname only get's null values.
Any suggestions?
For those of you who are trying to figure out what the whole point is, read this JavaScript NextSibling Firefox Bug Fix I have code that does my language translation that works in Google Chrome and IE. But when I use it in Firefox, and try to translate div content after ajax has loaded it, it fails because of the whitespace issue.
I really don't have a preference of jQuery or Pure Javascript, I just want a working solution.
Thank you all for being patient. I personally thought I was extremely clear in my description, I apologize if it wasn't. I wasn't trying to be obscure or make it difficult to get help. But please don't insult me, by implying I am trying to make it unclear.
Thanks.
Hm... You have jQuery but don't use it?
$(divid).children(".yourSpecialClassName").each( function() {
doSomethingWith(this);
});
To get the CSS class attribute value, this will do:
$(divid).children().each( function() {
alert(this.className);
});
Based on the function you posted now, you want this:
$(divid).find(".status_bar").each( function() {
$(this).text( function(i, text) {
var x = $.inArray(en_lang, $.trim(text));
if (x > -1) {
console.log('Current Value ['+text+'] English ['+en_lang[x]+'] Translation ['+other_lang[x]+']');
return other_lang[x];
}
return text;
});
});
And please, don't ever use "do magic" as a comment again. This is incredibly lame.
EDIT. This can be made much more efficient (superfluous console.log() removed):
$(divid).find(".status_bar").each( function() {
// prepare dictionary en_lang => other_lang
var dict = {};
$.each(en_lang, function(x, word) { dict[word] = other_lang[x]; });
$(this).text( function(i, text) {
var t = $.trim(text);
return (t in dict) ? dict[t] : text;
});
});
if you are using jquery you can do this:
$("#myDiv").find("*").each(
function(){
var myclass = $(this).attr("class");
}
);
Your sample code doesn't make sense.
$(this).attr('value', to);
'value' is an attribute of the tag, not the text content.
Did you really mean to do this instead?
$(this).text(to);
Also, you've re-edited your question, but you're still trying to loop through the child nodes using non-jQuery methods. You said "The last obstacle I had in my script, of which you see a small portion of, is getting the classname. I need the class name so that I can filter down what content get's text replaced."
If you are using jQuery it is completely unnecessary to loop through anything to get a class name. You simply have to use a proper selector in the first place.
$(divid).find(".status_bar.replaceme").each( function() {
// .replaceme is whatever class you're using for the stuff you want to change
// .status_bar.replaceme matches all elements with BOTH status_bar and replaceme classes
var value = $.trim($(this).text());
// if value is not defined thru browser bugs do not replace
if (typeof(value) != 'undefined') {
// it is a text node. do magic.
// NOTE: The following is inefficient but I won't fix it.
// You're better off using an associative array
for (var x = en_count; x > 0; x--) {
// get current english phrase
var from = en_lang[x];
// get current other language phrase
var to = other_lang[x];
if (value == from) {
console.log('Current Value ['+value+'] English ['+from+'] Translation ['+to+']');
// value = to; <-- useless, get rid of it.
$(this).text(to);
// or $(this).html(to);
}
}
}
});

Formfill in Javascript not working?

var tagMatch;
if (tagMatch = window.location.href.match(/\/questions\/ask\?tags=([^&]+)/)) {
$(function() {
if (!$('#tagnames').val().length) {
$('#tagnames').val(unescape(match[1].replace(/\+/g, ' '));
}
});
}
Hi all, this JS code is supposed to match the latter-part of a URL of the form /questions/ask?tags=some-tag, and then plug the text contained in the part of the URL after tags= into a textbox with the id #tagnames. What am I doing wrong? How can I fix this?
I'm still learning so if you would want to show me how to fix my regex or anything else, please do!
I think the error is with this line
if (!$('#tagnames').val().length)
length will return a number and check that against number.
Something like
if ($('#tagnames').val().length > 0)
I don't think there is a need to place document ready inside the if statement. Isn't this better.
$(function() {
var tagMatch;
if (tagMatch = window.location.href.match(/\/questions\/ask\?tags=([^&]+)/))
{
if ($('#tagnames').val().length > 0)
{
$('#tagnames').val(unescape(match[1].replace(/\+/g, ' '));
}
}
});
Without looking too much into how the string matching works...
You seem to be defining and setting a variable called tagMatch, but then you're using a variable called match to set the value.
Is that the problem?
Update: Apologies - your regex is correct - I misread the intention :)

Categories