trouble looping through div ids with newest jquery build - javascript

I upgraded my website to the latest jquery build (2.1.4), and I'm trying to debug the many errors that it is throwing.
However, I keep getting the error "unrecognized expression: [id=]" on the following script:
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
and I can't wrap my head around it.
Any help will be appreciated.

At first I was going to write a comment advising to put support requests directly on jQuery, but then I saw the code and thought it merits some discussion.
First of all, the id attribute is a special attribute in HTML. It is supposed to hold a unique value throughout the whole document (in other words, no two elements can have the same id), so I'm finding it strange that code would ever work.
Secondly, I don't see any reason why you would use jQuery to select an element by id when a simple document.getElementById() would have done the trick. Let's say you wanted to have a jQuery element. Fine, even in that case, your jQuery selector is far from perfect. A better alternative would be $('#' + this.id);. That said, the best alternative would be a simple $(this)... no need to worry about the id at all.

Perhaps I misunderstand the new jquery build, but normally you would declare your id within the jquery wrapper with
$('#myId')
Your code is assigning
var ids = $('[id=' + this.id + ']');
which translates to this
ids = $('[id=whateverThisIdIs]');
Can you try this instead?
var ids = $('#' + this.id); // assuming this.id does not contain '#'.
Final
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
var ids = $('#' + this.id);
// or this if you have the '#'
// var ids = $(this.id);
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
One of the comments mentions
You script implies that there are multiple ids on the page: not good.
This is true if you are using the same id, which I do not think you are.

Somewhere in your HTML is an element with one of the classes .cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user, that either has no id attribute or has an empty one.
Change the line
var ids = $('[id=' + this.id + ']');
to
var ids = $('#' + this.id);
and the error will go away.
Or do a check for an empty id:
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
if (!this.id) return;
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
}
...I can't help but wonder what the purpose of the code snippet is though... trying to remove duplicated elements...? Why are they there in the first place?

Related

Create html tags with dynamic tag name in jQuery

I want to create html tags in my function like this:
function createHtmlTag(tagName) {
var newHtmlTag = $(tagName);
return newHtmlTag;
}
But when I call createHtmlTag('div') in my page this function return all my page div tags. I know $(tagName) causes this result, but I need to this method. I can solve this issue by these methods:
function createHtmlTagSecond(tagName) {
var newHtmlTag = $('<' + tagName + '></' + tagName + '>');
return newHtmlTag;
}
Using JavaScript
function createHtmlTagByJavaScript(tagName) {
var newHtmlTag = document.createElement(tagName);
return newHtmlTag;
}
My question
Is there a better way to use jQuery without adding additional marks like ('<')?
Thanks advance.
You can't avoid < or > if you want to use jQuery, but you can trim it down to var newHtmlTag = $('<' + tagName + '>');
Moreover, according to What is the most efficient way to create HTML elements using jQuery? you'd be better off using the vanilla JS approach as far as performance goes.
I found a way that I don't need to add an extra mark (combine createHtmlTagByJavaScript and createHtmlTag).
function creatHtmlTag(tagName) {
var newHtmlTag = $(document.createElement(tagName));
return newHtmlTag;
}

How do I remove variable randomly using jquery?

I'm trying to find a way to remove variable from certain div on the web using jquery. This does not involve using array. If I can do so with using fadeIn() or search() and remove(), that's even better.
var something = '#img' + count;
on the web, images will be added to div as time passes (using setTimeout). Those images have been assigned to variable (something) and I need to find a way to remove it from certain div on the web. It can be hide, remove, whatever, it has to disappear from user's view randomly (both time and which image will disappear).
Thanks for help and your time in advance.
my function code:
var count = 0;
function foo() {
var xPos = xPosition();
var yPos = yPosition();
var someTime;
$("div").append('<img id="Img" ' + count + ' src = "img.png" style="top:' + yPos + 'px; left: ' + xPos + 'px; " />');
var something = "#Img" + count;
someTime = setTimeout('foo()', randInterval());
$(something).hide();
count++;
if (timeRemaining == 0) {
clearTimeout(someTime);
return;
}
Give all the images a class. You can then use $(".class").length() to get the number of images, pick a random number in this range, and delete that element with .eq().
function addImage() {
var xPos = xPosition();
var yPos = yPosition();
$("div").append($("<img>", {
src: "img.png",
"class": "imageclass",
style: {
top: yPos+"px",
left: xPos+"px"
}
}));
setTimeout(addImage, randInterval());
}
setTimeout(addImage, randInterval());
function removeImage() {
var images = $(".imageclass");
if (images.length) {
var rand = Math.floor(Math.random() * images.length);
images.eq(rand).remove();
}
setTimeout(removeImage, randInterval());
}
setTimeout(removeImage, randInterval());
In my code I'm using separate timers for adding and removing images. If you prefer, you could remove the setTimeout from removeImage(), and just call it from addImage so it will always remove an image whenever it's adding a new one.
Please, never ever append a number to an id and piece together numbered names of things. It is unmaintainable and bad. Use class.
Assign a purpose or functionality to an element or elements by adding a class name to them. If you want to add information to an element, that is great, use data- prefix on the attribute name and it is all legal. data-itemid is an example.
You can query for matching elements with var those = $('.that-class-name'), stored for reuse. From there you can access individual elements using those.eq(0) through those.eq(x.length - 1). For example, if you somehow knew that the 3rd one needs to be removed, then those.eq(3).remove();. If you want to pick through them and only select ones that match a condition, use those.filter(callback).remove(), where callback returns true if the element referred to by this should be removed. If you want to filter those with another selector, .filter will accept a selector too.
Is that what you meant?

How can I make this code work better?

I recently asked a question about manipulating the html select box with jQuery and have gotten this really short and sweet code as an answer.
$("#myselect").change(function (event) {
var o = $("#myselect option:selected"),
v=o.text(),
old = $("#myselect option:contains('name')"),
oldv = old.html();
oldv && old.html( oldv.replace('name: ', '') );
o.text('name: ' + v);
});
I have one problem. This code doesn't work on multiple categories and I can't seem to wrap my mind around how it can be done. So, I made the obvious changes to it:
$("select").change(function (event) {
var foo = $("select option:selected"),
bar = foo.text(),
cat = foo.parent().attr("label"),
old = $("select option:contains('" + cat + "')"),
oldbar = old.html();
oldbar && old.html( oldbar.replace(cat + ': ', '') );
foo.text(cat + ': ' + bar);
});
This now works on multiple optgroups/categories but has led to another bug. A more problematic one, at that.
It happens when you click from one category to another. Check it out on jsFiddle.
The problem with the last snippet is it uses the name of the current category to locate the last selected label to flip back. Instead, how about searching for the ":", (this won't work if you have ":" in one of your options), and then replacing that part of the string.
change line 5 to:
, old = $("select option:contains(':')")
and line 8 to:
oldbar && old.html(oldbar.replace(oldbar.substr(0, oldbar.indexOf(':') + 2),''));
Let me know if that's not working for you!
Edit: as an afterthought, you might consider adding this line
$('select').change();
As well, somewhere in the $(document).ready() event, so that when the page first renders the default value gets the prefix like (I think) you want.
I've renamed the variables since it is really a good habit to get into naming your variables and functions with meaningful names so you can juggle in your memory what is going on.
$("select").change(function () {
// We immediately invoke this function we are in which itself returns a function;
// This lets us keep lastCat private (hidden) from the rest of our script,
// while still giving us access to it below (where we need it to remember the
// last category).
var lastCat;
return function (event) {
var selected = $("select option:selected"),
selectedText = selected.text(),
cat = selected.parent().attr("label");
if (lastCat) { // This won't exist the first time we run this
oldSelection = $("select option:contains('" + lastCat + ":')");
oldHTML = oldSelection.html();
oldHTML && oldSelection.html(oldHTML.replace(lastCat + ': ', ''));
}
selected.text(cat + ': ' + selectedText);
lastCat = cat; // Remember it for next time
};
}()); // Be sure to invoke our outer function (the "closure") immediately,
// so it will produce an event function to give to the change handler,
// which still has access to the variable lastCat inside
Here's a shot in the dark. At first blush, it appears you're not saving the previous selection and you're using the selection which triggered the event in your oldbar && old.html( oldbar.replace(cat + ': ', '') ); line. You need to save the category of the previous selection in a separate var.

How do I add an object/this to a string in $$ selector in prototype?

$element = $(element);
console.log($$("#" + element + " > p")[0]); // works
console.log($$($element + $$(" > p"))[0]); // something like this
I think you want "#" + element.id — though it seems a lot more sensible to write $(element).select('p').
Use the select method of the element itself:
$element.select('p')[0]
I'm rusty at Prototype but I think that if you want to find all the <p> elements that are direct children of some element you've already got, you'd do this:
var firstPara = $(element).find(function(e) { return e.tagName.toUpperCase() === 'P'; });

Can this JavaScript be optimized?

This JS will be executed on pages with a lot of fields. Can you see anyway to improve the speed of this code? If so, can you explain what you found?
var _TextInputs = null;
function GetTextInputs()
{
if (_TextInputs == null)
{
_TextInputs = jq('input[type=text]');
}
return _TextInputs;
}
var _Spans = null;
function GetSpans()
{
if (_Spans == null)
{
_Spans = jq('span');
}
return _Spans;
}
function UpdateRate(ratefield, name)
{
GetTextInputs().filter('[' + name + ']').each(function()
{
this.value = FormatCurrencyAsString(FormatCurrencyAsFloat(ratefield.value));
CalculateCharge(name.replace('Rate', ''), jq(this).attr(name));
});
}
function CalculateCharge(name, activity_id)
{
var inputs = GetTextInputs();
var bill_field = inputs.filter('[' + name + 'Bill=' + activity_id + ']');
var rate_field = inputs.filter('[' + name + 'Rate=' + activity_id + ']');
var charge_field = GetSpans().filter('[' + name + 'Charge=' + activity_id + ']');
charge_field.text(FormatCurrencyAsString(FormatCurrencyAsFloat(bill_field.val()) * FormatCurrencyAsFloat(rate_field.val())));
}
You can:
Replace each with while
Replace val() with .value (should be fine as long as those fields are plain text ones)
Access elements by class instead of by name/type
Replace attr() with plain property access; e.g.: this.attr(name) --> this.name
These are all rather unobtrusive changes which should speed things up mainly due to cutting down on function calls.
Don't query elements on every function call if those elements are static (i.e. are not modified during your app life-cycle). Instead, store them outside the loop.
I can see that you're using attribute filters everywhere, e.g.:
_TextInputs = jq('input[type=text]');
inputs.filter('[' + name + 'Bill=' + activity_id + ']');
Attribute filters are useful, but not especially 'snappy' when compared to more direct class or ID selectors. I can't see any markup so the best I can do is suggest that you use more IDs and classes, e.g.:
jq('input.textInput');
instead of:
jq('input[type=text]');
A little off-topic, but I use and recommend Javascript Rocks. This books contains a TON of awesome JS optimisation advice by the creator of Scriptaculous. Also comes with a tool called DOM Monster which helps track down performance bottlenecks - it's an awesome compliment to Firebug as it actually tracks through the DOM looking for inefficiencies based on heuristics and DOM complexity.

Categories

Resources