I'm attempting to grab a data-* with jQuery. My problem is that jQuery reads my string of numbers as a number and as such drops the leading zero.
HTML
<tr data-string-number="0123456789">... (website layout, jk) ...</tr>
jQuery 1.7.2
var string_number = $('#selector').data('string-number');
// string_number == 123456789
// string_number != '0123456789'
Seems simple enough however this always drops the leading zero.
data-string-number is always going to be a number and may or may not have a leading zero. Currently it has a standard length but I can't say at this point if that will stay true.
Current only thought is to prefix it with a non-numeric and remove it straight away. This feels hacky and makes me sad.
Any thought appreciated.
Thanks.
Use this:
$('#selector').attr('data-string-number')
The .data() method does data conversion by design. The .attr() method simply returns the attribute as is (as a string). Note that when using .attr() you need to supply the full name of the attribute including the "data-" prefix.
I know this is old but I have 2 alternative to using the .attr() for accessing the data as a string.
<!-- Force a String by breaking the parser Remove Quotes later
or Use Object Below -->
<li data-tmp='"0123456789"'>Data as a String: </li>
<li data-tmp='{"num":123456789,"str":"0123456789"}'>Data as a Object: </li>
Now you can access them with the jQuery .data() method.
See this fiddle to illustrate http://jsfiddle.net/KUrJ2/.
Get the attribute with the standard attr() accessor.
jQuery tries to guess the type and convert it when using data() on data-* attributes. As we know leading 0's are insignificant in a Number but not a String.
use the jquery attr()
http://jsfiddle.net/duerq/
Related
I would like to use jQuery's .text() method to get my text contents of div element. Which is fine & works fine, however, I am trying to come up with a method to allow ONLY to get .text(); of first 10 text characters, is this possible?
Overriding jquery's .text() will show reflection everywhere.
So the best option would be create a function for doing this,
function myText($elem,len=10){
return $elem.text().substr(0,len)
}
and call it like myText($("#textWithElement")). Also you can alter your returning text's length by passing the second parameter myText($("#textWithElement"), 5).
And due to the confusion happened in comment section, I would like to add some details about the usage of substr and substring at this context.
"string".substr(0,2) //where 0 is the start and 2 is the length
"string".substring(0,2) //where 0 is the start and 2 is the to (not inclusive)
So here in your context, both would yield the same result. But it is good to know about the difference between the both.
el.text().substring(0,10);
where el is a jquery element
This doesn't work
var name= "#443.selected:first";
selectedEntity = $(name).attr('entityId');
This works
var name= "li.selected:first";
selectedEntity = $(name).attr('entityId');
selectedEntity is undefined but an element does exist with id="443" class="selected".
Why doesn't the first example work?
You can use the attribute selector:
$('[id="443"].selected:first')
See this jsFiddle demo
Though in HTML other than HTML5 IDs which start with a number are not allowed, your selector should work (working Demo). You must have an error elsewhere in your code and/or markup.
There are several issues you should address:
IDs must be unique otherwise your HTML is invalid
overqualifying the ID-Selector is bad for performance and due to 1) even not necessary
ID-Selectors only return the first element so using :first is useless (and also affected by point 1)
Don't use custom attributes like entityId. Instead use the data- prefix. Then you can use jQuerys data method to get/set those attributes. (Beware however that you cannot use camelCase).
What I'm attempting to do can be accomplished by the following...
elementContent = document.getElementById('docElement').innerHTML;
elementContent = parseFloat(elementContent);
or even by...
elementContent = parseFloat( document.getElementById('docElement').innerHTML );
but I can't help to wonder if there's a more elegant way to retrieve and assign DOM content as a float that I may be unaware of. Any insight?
There is the unary plus operator which tries to convert a string (or another type's toString()) to a number. It would be used like:
elementContent = +document.getElementById('docElement').innerHTML;
As others have mentioned you can use jQuery as essentially syntactic sugar for .innerHTML here, also.
That's a fine way to go about doing things. The only thing I could suggest would be that if you can avoid working with the HTML markup entirely, by storing the "clean" number as an attribute of the element, that would be preferable, as it would get around problems that might be introduced if the HTML gets fancier than you expect it to be. (For example, sometimes designers want negative numbers formatted with the Unicode "minus" glyph instead of the plain hyphen, because it looks better.)
Thus if you could generate your elements like this:
<span id='docElement' data-value='29.20221'>29.20221</span>
then instead of accessing the value as ".innerHTML" you'd use ".getAttribute()":
var value = document.getElementById('docElement').getAttribute('data-value');
value = parseFloat(value);
Use JQuery:
var html = parseFloat($('#docElement').html());
$('#docElement').html(html);
If you use a library such as jQuery the code for this would be more elegant, like so:
var el = parseFloat( $('#docElement').text() );
Don't forget you might run into an issue where you need to trim() the string as well.
html
<div contentEditable="true">testing....</div>
jQuery
$(document).ready(function(){
$('[contenteditable]').removeAttr('contenteditable');
});
above codes is fine and working. you can feel it here.
Now, try this
$('[contentEditable]').removeAttr('contentEditable');
// notice the CamelCase of the string contentEditable
in FF 3.6, it gives an error on the console
An invalid or illegal string was
specified" code: "12 elem[ name ]
= value;
and the div is still editable.
I suspected it was the jQuery selector, but is not. By further inspection, it was the argument passed on the .removeAttr('contentEditable');. It works when all small letters. So, I thought it should be all small letters. I'm curious so I tried adding CLass as an attribute and do .removeAttr('CLass');. But then it works without error.
So, how come contentEditable is giving me that error?
update
from Kobi, it seems that it actually accept any case except, contentEditable (I did try too).
CamelCase
This isn't about small letters, but about the exact casing. Any other casing than contentEditable works, for example: removeAttr('ConTentEditable');.
I can't find the exact source of the problem, I guess it's a Firefox restriction.
It seems jQuery sets the attribute to an empty string before removing it, which is what's causing the error. This seems to work better:
$('[contentEditable]').attr('contentEditable', false);
You could call it a bug, but really the framework is designed this way. removeAttr, along with other attr functions, points to jQuery.attr() to set the attribute's value. After setting the attribute to "", it then attempts to remove it. The code for attr() specifically checks to see if the given string is a property name on the object first using the in operator:
// If applicable, access the attribute via the DOM 0 way
if ( name in elem && notxml && !special ) {
(from jQuery 1.4, line 1452-1453)
Since you're supplying the camelCase property name, it uses that instead of elem.setAttribute(), which is specifically the cause of the problem. For any other case, name in elem would return false (because property names are case sensitive), which is why it's successful then. jQuery does this mostly to work around cross browser issues with setAttribute().
It looks like Firefox has a problem with setting the property to an empty string, unless you have the same problem in other browsers. You could try and file a bug either on the jQuery site or MDC.
contentEditable seams to be a special attribute:
http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#contenteditable
The contentEditable property (not attribute, since that isn't what attr() and friends usually deal with) expects a string value, one of "true", "false" and "inherit". I wouldn't use jQuery to turn off contentEditable, but I imagine the following would work:
$('[contenteditable]').attr("contentEditable", "false");
Or you could bypass jQuery for setting the actual contentEditable property:
$('[contenteditable]').each(function() {
this.contentEditable = "false";
});
I have the following being extracted from an XML and being put into a jQuery variable.
links.append($("<a href='"+alink+"'></a> ").html(desc));
...however the does not output onto the page. I need this to separate the hrefs on output
I have also tried
links.append($("<a href='"+alink+"'></a>").html(desc));
links.append($(" "));
Many thanks!
$("<a href='"+alink+"'></a> ")
Yeah, that's actually only creating the <a> element, and discarding the nbsp. When you pass a string into the $() function that looks like(*) HTML, jQuery creates the stretch of markup between the first < in the string and the last >. If you've got any leading or trailing content outside those, it gets thrown away(**). You could fool jQuery by saying:
$("<a href='"+alink+"'></a> <!-- don't ignore me! -->")
This doesn't seem to be documented anywhere, makes no sense whatsoever, and might be considered a bug, but it has been jQuery's normal behaviour for some time so it's probably not going away.
When you pass an HTML string to the append function (and other manipulation methods) directly instead of via the $ function, this behaviour does not occur. So:
links.append("<a href='"+alink+"'></a> ");
actually does keep the space. But a better way forward is to stop throwing HTML strings about, so you don't have to worry about alink containing ', < or & characters either, and work in a more DOM style:
var link= $('<a/>');
link.attr('href', alink);
link.html(desc);
links.append(link);
links.append('\xA0');
Or, more concisely, using jQuery 1.4's props argument shortcut:
links.append($('<a/>', {href: alink, html: desc}));
links.append('\xA0');
assuming that desc is really something that should contain HTML markup; if not, use text instead.
(I used \xA0, the JavaScript string literal way to include a character U+00A0 NON-BREAKING SPACE as it is a whole two characters shorter than the HTML entity reference. Woohoo!)
(*: how does it tell that a string is HTML? Why, by checking to see if there's a < and > character in it, in that order, of course. Meaning it'll get fooled if you try to use a selector that has those characters in. Brilliant, jQuery, brilliant.(***))
(**: why? see line 125 of jQuery 1.4.2. It builds the HTML fragment from match[1]—the group from the first < to the last > in quickExpr—and not the original string or match[0].)
(***: I'm being sarcastic. The insane over-overloading of the $ function is one of jQuery's worst features.)
You better style with css, something like :
links.append($("<a class='link' href='"+alink+"'></a>").html(desc));
in css :
a.link {
padding-left : 5px ;
padding-right : 5px ;
}
you could try