I have an issue with jquery where elements are not found when the query string has '$' char in them -- is there a known issue? Unfortunately search engines make it so hard to searh for symbols in threads.
I have an html such as this:
<TD id="ctl00$m$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60$ctl00$ctl00_5"
class="MenuItem"
onclick="setSelectedTab('ctl00$m$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60$ctl00$ctl00_5');"
tabsrowid="ctl00$m$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60$ctl00$ctl00_"
nohide="false">...
and my jscript goes something like:
function setSelectedTab(selection) {
var ids = selection.split('/');
for (var i = 0; i<ids.length; i++) {
var item = $("#" + ids[i]);
item.addClass("selected");
$("#" + item.attr("tabsrowid")).show();
}
}
While analyzing in firebug, I see that 'item' is an empty set. If I query $('.MenuItem') for example, it correctly returns a result set with 25 matching items in the page; it appears like $(s) doesn't work when s contains $ chars in it?
What's the solution to it? Sorry if it a dumb question or well known issue -- as I said I tried to google around, but unsuccessfully.
Note: It's not an issue with javascript itself, or duplicate ids, or jquery not loaded, or anything like that. The function does get called onclick, and if I replace $('#' + ids[i]) with document.getElementById(ids[i]), it does return the correct element.
fyi, the string passed to the function setSelectedTab usually contains a hierarchical path to the TD element; though in the example TD above, the ids.length is 1.
Thanks,
Raja.
Perhaps try escaping them with backslashes
<TD id="ctl00\$m\$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60\$ctl00\$ctl00_5"
class="MenuItem"
onclick="setSelectedTab('ctl00\$m\$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60\$ctl00\$ctl00_5');"
tabsrowid="ctl00\$m\$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60\$ctl00\$ctl00_"
nohide="false">...
Related
I get a number value from an array and when I append to the DOM I get a blank space before the value that I need to remove.
The result should look like this. data-filter-class="["4"]"
for (var i=0, len=strArray.length; i<len; i++) {
thepost=String(strArray[i]);
thepost = thepost.split(",");
pid=thepost[9]
pid=String(pid)
pid=pid.replace(/\s+/g, '');
pid='["'+pid+'"]'
console.log(pid) // here I get ["4"]
and then I create a variable like this
html +='<li data-filter-class="'+pid+'" class="test">'
console.log(html) // here I get <li data-filter-class="["4"]" class="test"> as I should
and then I append it to my list.
But when I then look at the code after it is appended I get a blank space before the value?
Then it look like this
<li data-filter-class="[" 4"]" class="test">
So instead of "["4"]" I get "[" 4"]"
So how do I remove the blank space?
Solved
I finally got it working with this. It should be '["4"]', my mistake!
pid='\'["'+pid+'"]\''
data-filter-class='+''+pid+''+'
And it becomes data-filter-class='["4"]'
Try this
str.trim().split(/\s*,\s*/);
or
array = array.map(function (el) {
return el.trim();
});
i am sure your problem isnt with the trim part may be try to create the li element in this way please
let row=document.createElement("li");
row.setAttribute("data-filter-class",pid);
Currently desired <li data-filter-class="["4"]" doesn't look like a good idea. When I see "["4"]" it looks like something wrong, because outer quote marks are the same as inner ones. Are you sure that it will be read like ["4"] in the end of the day?
May be the interpreter sees the "["4"]" and reads it like two separate values "[" and 4"]" and therefore inserts a space?.. Who knows.
I would either try escape inner quote marks to get it "[\"4\"]", or, maybe use different inner quotes altogether: "['4']"
Then your code would be like this:
pid='[\\"'+pid+'\\"]' // for eascaped double quotes inside
or like this:
pid='[\''+pid+'\']' // for single quotes inside
But this has to be check.
I need to take the phrase
It’s that time of year when you clean out your closets, dust off shelves, and spruce up your floors. Once you’ve taken care of the dust and dirt, what about some digital cleaning? Going through all your files and computers may seem like a daunting task, but we found ways to make the process fairly painless.
and upon pressing a button
split it into an array
iterate over that array at each step
Build SPAN elements as you go, along with the attributes
Add the SPAN elements to the original DIV
Add a click handler to the SPAN elements, or to the DIV, which causes the style on the SPAN to change on mouseover.
So far I had
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
print('The original string is: "' + stringToSplit + '"');
print('The separator is: "' + separator + '"');
print("The array has " + arrayOfStrings.length + " elements: ");
for (var i=0; i < arrayOfStrings.length; i++)
print(arrayOfStrings[i] + " / ");
}
var space = " ";
var comma = ",";
splitString(tempestString, space);
splitString(tempestString);
splitString(monthString, comma);
for (var i=0; i < myArray.length; i++)
{
}
var yourSpan = document.createElement('span');
yourSpan.innerHTML = "Hello";
var yourDiv = document.getElementById('divId');
yourDiv.appendChild(yourSpan);
yourSpan.onmouseover = function () {
alert("On MouseOver");
}
and for html I have
The DIV that will serve as your input (and output) is here, with
id="transcriptText":</p>
<div id="transcriptText"> It’s that time of year when you clean out your
closets, dust off shelves, and spruce up your floors. Once you’ve taken
care of the dust and dirt, what about some digital cleaning? Going
through all your files and computers may seem like a daunting task, but
we found ways to make the process fairly painless.</div>
<br>
<div id="divideTranscript" class="button"> Transform the
Transcript! </div>
Any help on how to move one? I have been stuck for quite some time
Well, first off this looks like homework.
That said, I'll try to help without giving you the actual code, since we're not supposed to give actual working solutions to homework. You're splitting the string too many times (once is all that's needed based on the instructions you gave) and you have to actually store the result of the split call somewhere that your other code can use it.
Your instructions say to add attributes to the span, but not which attributes nor what their contents should be.
Your function should follow the instructions:
1) Split the string. Since it doesn't specify on what, I'd assume words. So split it on spaces only and leave the punctuation where it is.
2) with the array of words returned from the split() function, iterate over it like you attempt to, but inside the braces that scope the loop is where you want to concatenate the <span> starting and ending tags around the original word.
3) use the document.createElement() to make that current span into a DOM element. Attach the mouseover and click handlers to it, then appendChild() it to the div.
add the handler to your button to call the above function.
Note that it's possibly more efficient to use the innerHTML() function to insert all the spans at once, but then you have to loop again to add the hover/click handlers.
for reasons i can't go into too much details with here i have an id that could look like this:
1%20
The reason i have this is because im matching a table of alot of data.
1 means the table row 20 is the list it is in (from the database).
Now i have the following javascript code:
function getSplitId(id) {
return id.split('%');
}
Which works fine when i do the following:
selected_row_id = getSplitId($(this).get(0).id)[0];
Now i want to get the HTML id of the row ive clicked and for that i have the following code:
rowHtmlId = $(this).id;
Which also works fine however when i need to start using the rowHtmlId to something like for instance:
newElement = $('#' + rowHtmlId).prev();
I get the following error:
Syntax error, unrecognized expression: #44%24
So my question is how can i go around this?
If you have a look at the jQuery documentation, you see
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[\]^{|}~` ) as a literal part of a name, it must be escaped with with two backslashes: \\.
% is a meta character so you have to escape it first:
newElement = $('#' + rowHtmlId.replace('%', '\\%')).prev();
Or you simply use getElementById:
$(document.getElementById(rowHtmlId)).prev();
Or even better (depending on the context), just keep a reference to the row element itself:
var row = $(this);
// ... later
newElement = row.prev();
There is no need to query for it again if you already have a reference to it.
Just add a backslash to escape the percent sign:
id.split('\%');
in getSplitId() change from:
return id.split('%');
to
return id.split('\%');
Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.
The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.
Try \" instead of ' in onClick
$(".container").append("Edit");
You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.
I'm having problem with the contains in jquery. It seems that it only accepts one word. Not a phrase or two words.
Example:
$('#div:contains('Word')'); --> This is okay
$('#div:contains('Just another word')'); --> This will return empty/this will not match.
Do you have any experience with this kind of problem?
Your reply is greatly appreciated.
What you need, is to use double quotes (instead those single quotes wrapping the whole selector), for example:
$("p:contains('John Resig')");
this will select the correct paragraph, with string 'John Resig' inside
or you can inverse it:
$('p:contains("John Resig")');
or you can use an old good escaping:
$('p:contains(\'John Resig\')');
Try it without the # and avoid using the same quoting within the code:-
$("div:contains('Just another word')");
Assuming you didn't already solve this, from your comment which included:
var selected = $(this).find(':selected').text();
if (selected.toLowerCase() != "all industries") {
if (trim(selected).length > 0) {
$("#contact-list-selectable li .contact-info-industry").parent().css("display", "none");
$("#contact-list-selectable li .contact-info-industry:contains('" + selected + "')").parent().css("display", "block");
alert($("li[style='display: block;']").text());
}
I'll assume you meant to use trim as a method on the string, or if not that you have a trim function defined somewhere else. If this is actually how your code looks and you have no custom trim function, then that's going to be your first problem, it should be: selected.trim().length
One potential issue is that while you check that the trim of selected is > 0, you don't use a trimmed version of selected when checking the contains. If you have any spaces/etc in your selected variable, it will fail for contains.
Here is an example. Note the trailing space in selected = "computer science "; that is intentional to demonstrate what happens in that case.
if you change
$("#contact-list-selectable li .contact-info-industry:contains('" + selected + "')").parent().css("display", "block");
to
$("#contact-list-selectable li .contact-info-industry:contains('" + selected.trim() + "')").parent().css("display", "block");
you can avoid this issue (working example, see here, note the trailing space is still there).
The only other issue I could think of would be if you were incorrectly forming any of your selectors and they did not actually match your DOM structure. Otherwise everything works fine in current jquery.