Add multiple unique ids to an element - javascript

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?

Related

Jquery doesn't find div to append to when the variable in $('#div'+variable) contains spaces

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>

spaces in ID and putting variable in ID jquery

I want to put spaces in id and also i want to select an id using variable.
The id i want to achieve is something like this
<span id="printroofG.I. Sheet" class="underline"></span>
Lets say i have this variable.
var id = G.I. Sheet;
and this is my selector
$('span[id=printroof'+value.material+']').text(value.material);
I get unrecognized expression: span[id=printroofG.I. Sheet].
What is the proper way to have spaces in ID and use variable as selector.
As I said earlier, do not use an ID for this purpose. You'd be better of using data-* as below.
var id = "G.I. Sheet";
$('span[data-id="printroof' + id + '"]').text("Some text");
//OR
$('span[data-id="printroof' + value.material + '"]').text(value.material);
A Demo
HTML:
<span data-id="printroofG.I. Sheet" class="underline"></span>
If you absolutely have to do this use double quotes:
$('span[id="printroof'+value.material+'"]').text(value.material);
But don't do it. As lshettyl suggested perhaps it is better to use the jquery data api for this.

How to select element with id containing \ in jquery or javascript

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 '\\\\'.

Autofocusing on a newly added element via javascript

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.

How to dynamically add attributes to mulitple div with same class name using jquery?

I have a "div" written in my html code like this
<div class="mydata">
</div>
and this is created dynamically when page renders so how many div with this same class name is going to be created is not fixed but using my code i can get the total no of div presented at a time after page load.
i stored that value in a variable "counter".
so for example at some time if their are 5 div with "mydata" class name then counter have 5 value
but now i want to add id attribute(Start from 1 upto counter value) to each div.
ex: first div is look like this <div class="mydata" id="1"></div>
second one is like this <div class="mydata" id="2"></div> and so on.
so please tell me how can add this id attr to my div(as discribed other )using jquery ?
-Thanks
No need for the counter.
However you can't use only a number for the id attribute. It must start with a letter.
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 (".").
ID and NAME tokens
Here is the jQuery code:
$('.mydata').each(function(i){
$(this).attr('id', 'id_'+(i+1));
});
The IDs will be:
<div class="mydata" id="id_1"></div>
<div class="mydata" id="id_2"></div>
...
$('.mydata').each(function(index, element) {
$(element).attr('id', 'id_' + (index + 1));
});
var i = 1 ;
$('.mydata').each(function(){
$(this).attr('id',i);
i++;
});
Also,
$('.mydata').attr('id', function (i, oldValue) {
return 'id_' + i;
});
Nice and simple :)

Categories

Resources