This should be simple but I can't get it to work so would appreciate any pointers.
I have a function in my webpage that adds a new line into a table with inputs etc. This is a pretty basic POST that looks something like this...
$.post(url, {
newRow : newRow
}, function(data) {
$('#' + tableName + ' > tbody > tr').eq(rowLoc).before(data);
}).done(function() {
reNumberTableIDName($tb)
});
The reNumberTableIDName function is pretty straightforward, it runs through all the objects in the table and changes their id/name so that they are in order relevant to the row they are in the table for other reasons.
Now, one of the elements added in to this table is an auto complete input which looks like so...
<input id="autoLook[9]" class="required yui-ac-input" type="text" title="" value="" name="autoLook[9].id" style="width:500px" autocomplete="off" required="required">
Note that the name and ID are not altered as part of the reNumberTableIDName function.
I tried adding in a line to the "done"portion of the post to then put the focus/carat into that new input but it doesn't work (focus stays on the button previously clicked to add the row).
$("#autoLook[" + (newRow -1) + "]").focus();
I've checked with an alert that "#autoLook[" + (newRow -1) + "]" does indeed come up with the right string so I'm at a loss as to why this doesn't work. What obvious litle gotcha am I missing?
Its also worth noting that I tried to add in a autofocus property to the input being added, but I'm working in grails and this type of auto complete doesn't allow me to do this.
Thanks!
Worth noting that the solution should be to use setTimeout as mentioned below else it will continually put focus back to the object!
The selector #autoLook[9] matches an element with the id autoLook and the attribute 9; which is obviously wrong. Add backslashes around the square brackets to escape them:
$("#autoLook\\[" + (newRow - 1) + "\\]").focus();
Quote from jQuery Documentation: Selectors:
To use any of the meta-characters (such as
!"#$%&'()*+,./:;<=>?#[\]^``{|}~) as a literal part of a name, it
must be escaped with with two backslashes: \\. For example, an
element with id="foo.bar", can use the selector $("#foo\\.bar").
The W3C CSS specification contains the complete set of rules regarding
valid CSS selectors. Also useful is the blog entry by Mathias Bynens
on CSS character escape sequences for identifiers.
Related
I'm using a button to dynamically generate a new table row in my form and the lines include calling functions with parameters. I tried using JQuery on the added lines to trigger the .blur() event, as was successfully done with the hardcoded first table row, but the page completely ignored it. So I'm trying another route of triggering the onblur() event from within the row HTML. I'm getting stuck on the function parameter, as I'm either messing up the escape character order or messing up the translation. I've already spent a few hours on this and tried doing research on Stack Overflow, so I'm hoping a second set of eyes would be able to help.
Here are the relevant pieces of code. The stored html is appended to my table row, which already works.
var strVar = 'myString';
var rowCount = $("#tbodyID td").closest("tr").length;
var rowNum = rowCount + 1;
var line17 = "<td><input type='number' class='form-control' name='named_qty' onblur='function(" + strVar + ")' id='row_R" + rowNum.toString() + "' /></td> ";
There are approximately 25 lines with varying html to be inserted. I was able to get it to work previously, but realized that a value was hardcoded and I needed it to be dynamic. The function it calls is accepting a string.
When inserted into the HTML document, this line should generally read:
<td><input type="number" class="form-control" name="named_qty" onblur="function('myString')" id="row_R2" /></td>
I did some more research and realized that I was using the JQuery blur() method as :
$('#id').blur( function() { }); and trying to call those functions, not realizing that the method only works for HTML elements that had been written to the DOM on page load.
Apparently the solution is to use the JQuery on() method as follows:
$(document).on("blur", '#id', function() { <insert code> });
From W3Schools,
Note: Event handlers attached using the on() method will work for both current and FUTURE elements (like a new element created by a script).
This removes the necessity to include the event function call in the HTML line to be appended to the DOM.
I tried to append divs using jQuery from a function's input values but noticed that I wasn't getting anything but the main div appended to the body:
var the_key = "AAA AA"; //put here as an example
$('body').append('<div class="chart_canvas" id="div_'+ the_key +'" />');
$('#div_' + the_key).append('<div id="d3_canvas'+ the_key +'" />');
It works if the_key = "AAAAA".
My not so good attempt at adding quotation marks wasn't really successful and did end up with an error (unrecognized expression) as the quotation marks end up in the expression:
$('#div_' + "'" + the_key + "'").append('<div id="d3_canvas'+ the_key +'" />');
Is there any way that I can do this? The object that I'm reading these "the_key" values from do all contain spaces.
id values cannot have spaces in them. It's just about the only restriction on id values in HTML (other than that they must be unique).
Separately, CSS ID selectors cannot contain unescaped spaces either (because a space is a descendant combinator). But that doesn't matter because #1. :-)
Use a valid ID, and provided it doesn't have any characters that are allowed in HTML ids but not CSS ID selectors (or you properly escape those characters), concatenation without quotes will work.
A space in ID is a "problem" for jQuery. Try to Escape it:
<script>
// document.getElementById or similar
document.getElementById('AAA AA');
// document.querySelector or similar
$('#AAA\\ AA');
</script>
You could also use the attribute selector like this:
<script>
$("*[id='AAA AA']");
</script>
Spaces are not legal characters of an id attribute value in HTML.
Even though it might "work" in certain situations there is no guarantee that it always will.
console.log('test', document.getElementById('test'));
console.log('te st', document.getElementById('te st'));
console.log('jQuery test', $('#test').length);
console.log('jQuery te st', $('#te st').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">test</div>
<div id="te st">te st</div>
I've the following question, let say we have a div like this:
These are dynamically formatted divs, with the classes 'row', 'element' and 'isotope-item' are always present. Everything in between can vary per div.
What I want is to the following:
As you see the commmas are no longer there and seperate classes between the commas are now one class.
Anyone any idea?
I already have the following to remove the commas:
$('div.element').each(function () {
var _sCurrClasses = jQuery(this).attr('class');
jQuery(this).attr('class', _sCurrClasses.replace(/,/g, ' '));
});
I would advise doing this backend,but in JavaScript you could:
This will not account for the space in the words though.
You would need to pass then trough separately one by one and replace.
or store them in a data-attribute and format when you need them.
<string>
var classesFormat = classes.replace(/,/g, '');
var classesList = classesFormat.split(" ");
for(String c : classesList)
{
$("#id").addClass(c);
}
</string>
So you could create a data-attribute for each one instead.
Go through each one, format and the add to class.
<div data-id="Microsoft Office," class="test test test">
With the script
$(this).attr("data-id") // will return the string "Microsoft Office,"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the Microsoft Office,
And then do your replace after that and addClass.
I don't think classes work like you think they do
the first PICTURE you posted would result in that div having the follwing classes
row
element
Microsoft
Office,
My
SQL,
Page
Rank
isotope-item
Note the , is PART of the class
You want, according to the second PICTURE
row
element
MicrosoftOffice
MySQL
Page
Rank
isotope-item
Removing , is just as you posted ... the problem is, how do you determine which spaces to remove, and which to keep?
(I posted this as an ANSWER, but I KNOW IT IS NOT AN ANSWER)
we have some legacy code where Html element ID's are populated dynamically from database data (I cant change the data here)
ex. <input type="text" id="2314/test/film/code\branch"/>
when I get the ID from click event like below
var src = window.event.srcElement; I get src.id= "2314/test/film/code\\branch";
I want to use the src.id to find the same element in different function like $(_element).find("[id='" + src.id + "']").get();
which is failing to get any ID since I see "\" is replaced with "\\"
Please suggest me how to get around this ?
I don't think jQuery lets you use / in a selector. It is an illegal character in an id name, but still odd that jquery seems to flat out refuse it. Since JS has no problem with that selector You can select it with JS then pass it off to the jquery wrapper.
$(document.getElementById('2314/test/film/code\\branch'));
Maybe it´s works for you
http://codepen.io/luarmr/pen/vOgoLO
$("[id='" + str.replace(/\\/g,'\\\\') + "']").html(str)
The correct regex for backslash is '\\\\'.
I need to add a second unique id to an element.
I use this to generate new ids
var id = 1;
function getNextId()
{
return ++id;
}
Then I am doing this
$('<div id="content '" + getNextId() +"'" class="span6"></div>').appendTo('.new');
But I am getting an Uncaight SyntaxError: Unexpected identifier
How can I add multiple ids where the second is a unique one?
(I am remove the first id on a click, so I'm ok with leaving #content there)
Multiple ids on an element have been discussed in here: Can an html element have multiple ids?
How can I add multiple ids where the second is a unique one?
You can't.
You can't have multiple IDs on one element. You get zero or one ID per element, and that is it. If you want to add additional things to select an element by, you can use classes.
Your syntax error is due to some very confused quotation marks; I suspect you wanted to do this:
$('<div id="content newId' + getNextId() + '" class="span6"></div>')
producing something like <div id="content newId3">, which can't work. You're not giving it two IDs, you're giving it one ID with a space in it, which is an invalid ID:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
There are two problems with your code:
'a'b isn't valid JavaScipt. Try 'a' + b
Whitespace characters aren't allowed in HTML ids. And even if they were, all characters in the id attribute would make up the ID, so you can't assign more than one ID to an element. Use a class instead.
Looks like:
$('<div id="content '+ newId + getNextId() +'" class="span6"></div>').appendTo('.new');
I bet that is more right
Try this instead:
$('<div id="content-' + getNextId() + '" class="span6"></div>').appendTo('.new');
I think a pretty good start would be to add a + there.
'<div id="id-' my_id_var '"></div>'
Just isn't going to work.
"<div id=\"id-" + getNextID() + "\"></div>"
Will work just fine, though.
Second issue, each element gets 1 ID.
The point is that an ID is given to make an element uniquely-identifiable.
Why do you want the element to be uniquely identifiable twice?
There are lots of other ways of doing this.
First, you have class.
If you are working with objects which need similar states ("selected", "news-article", "user-interactive"), use classes.
Then, you have data- attributes.
<div id="player_1"
class="player-character"
data-health="42"
data-x="320"
data-y="240"
data-speed="5"
><img src="..."
></div>
Then in JS, you could do something like:
var player_1 = document.getElementById("player_1");
player_1.dataset.health; // "42"
These values are supported as far back as IE8, I think.
If you want to go further than that, then instead of using .dataset, you use .setAttribute("data-" + field_name, value)
If you're using jQuery, then it handles ALL of that for you, anyway.
So with all of these options, why do you want 2 ids per one element?