HTML
<div id="code1" data-code="123;12"></div>
<div id="code2" data-code="231"></div>
Jquery/Javascript
alert($("#code1").data("code").split(";")[0]);
alert($("#code2").data("code").split(";")[0]);
alert('test');
Since code2 does not have a ";", the code stops working all together. The last alert will not work nor will any code after the non-splitable code. How can I split code by ";" even when it may not have the ";" character?
data() will typecast a value to number if it is numeric
Try:
$("#code2").data("code").toString().split(';')
More about typecasting in the html 5 attributes section of data() docs
Use the following:
alert($("#code1").attr("data-code").split(";")[0]);
alert($("#code2").attr("data-code").split(";")[0]);
alert('test');
The reason that the second line fails is because the value is implicitly typecasted to a number by jQuery when using $.data. It has nothing to do with the implementation of String.prototype.split, since that returns an array with the 0th element being the full string if the delimiter does not exist.
In order to fix the problem, use $.attr instead of $.data to ensure that jQuery does not internally typecast the value to another type if it looks like another type.
Test on JSFiddle.
Related
I'm trying to use classList.replace() with regular expression. My goal is replacing an expression like badge-something with an other value like badge-success.
I've tried this:
element.classList.replace(/badge-*/i, 'badge-success')
But it returns false and doesn't change nothing. What am I missing?
Element.classList is a DOMTokenList (not a string).
DOMTokenList.replace takes two strings, not a regex. The first argument is the exact class name you want to replace. Patterns are not supported.
If you want to use regexes, you need a string:
element.className = element.className.replace(/(^|\s)badge-\S+/g, '$1badge-success');
classList.replace took string as an argument, so i think that is why it is not working.
But you can achieve your goal by twisting your code little bit,
repeat these steps
first took all className of that element(using element.className)
split those classes in array (using split function--- classname.split(' '))
apply forEach loop on array and by using str.search('badge-') > -1, replace that className using element.classList.replace..........Simple little long but code will work definitly
.
Thank you
I found a bug in a program I had written, but the behavior of the error is inexplicable to me:
If I have:
<input type="text" name="cust_id" value="666" />
<input type="text" name="phone[]" value="666" />
And then use this selector:
var test = $("input[name=phone[]]:eq(0)");
test.css("color", "red");
I see this:
What I'm surprised by is the fact that the eq(0) selects the first input even though I explicitly tell it to find only ones with name=phone[]
Here is a fiddle: https://jsfiddle.net/1xdnv1t8/
Is this expected behavior? Does the eq selector ignore attribute selectors?
You need to quote name attribute:
var test = $("input[name='phone[]']:eq(0)");
because phone[] is not valid name without quotes. So jQuery parser (or DOM) simply ignores everything invalid and treats selector as if it was simply input[name='phone']:eq(0). Also worth noting, that looks like this behaviour is fixed in more up to date versions of jQuery. You use pretty old 1.6.4 in your demo, but if you check it with 1.8.x and above it will work properly throwing error.
For example, if you try
try {
document.querySelector("input[name=phone[]]")
}
catch(e) {
alert(e.message)
}
it will even throw an error
Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'input[name=phone[]]' is not a valid selector.
But jQuery is more forgiving and it just selects whatever it can.
Use
var test = $("input[name='phone[]']:eq(0)");
JSFiddle
In the selector especification states
jQuery( "[attribute='value']" )
attribute: An attribute name.
value: An attribute value. Can be either an unquoted single word or a quoted string.
You are missing quotes around the attribute value. Try this -
var test = $('input[name="phone[]"]:eq(0)');
The square brackets in your selector confuse the attribute selection part as it is not quoted. Notice if you change the name of the second input to phone then it works as expected:
$("input[name=phone]:eq(0)")
Alternatively, wrap the attribute selector in quotes:
$("input[name='phone']:eq(0)")
While quoting the name attribute's value isn't strictly required (jQuery for the most part will work fine without them), as you noticed you can run into unusual situations when there are non-alphanumeric characters involved and jQuery interprets them as CSS notation.
The solution is to always properly escape any of these characters (:, ., [, ], etc.) as jQuery recommends, with two backslashes:
In order to tell jQuery to treat these characters literally rather
than as CSS notation, they must be "escaped" by placing two
backslashes in front of them.
So according to the jQuery documentation, you should be using var test = $("input[name='phone\\[\\]']:eq(0)"); as the selector (although simply properly quoting the string in your case will also work fine).
jsFiddle example
Ref: How do I select an element by an ID that has characters used in CSS notation?
I have the below code in my JSP. UI displays every character correctly other than "&".
<c:out value="<script>var escapedData=unescape('${column}');
$('div').html(escapedData);</script>" escapeXml="false" /> </div>
E.g. 1) working case
input = ni!er#
Value in my escapedData variable is ni%21er%40. Now when I put it in my div using
$('div').html(escapedData); then o/p on html is as expected
E.g. 2) Issue case
input = nice&
Value in my escapedData variable is nice%26. Now when I put it in my div using
$('div').html(escapedData); then also it displays below
$('#test20').html('nice%26');
However, when output is displayed in JSP, it just prints "nice". It truncates everything after &.
Any suggestions?
It looks like you have some misunderstandings what unescape(val)/escape(val) do and where you need them. And what you need to take attention of when you use .html().
HTML and URI have certain character that have special meanings. The most important ones are:
HTML: <, >, &
URI: /,?,%,&
If you want to use one of those characters in HTML or URI you need to escape them.
The escaping for URI and for HTML are different.
The functions unescape/escape (deprecated) and decodeURI/endcodeURI are for URI. But was you want is to escape your data into the HTML format.
There is no build-in function in_JS_ that does this but you could e.g. use the code of the answer to this question Can I escape html special chars in javascript?.
But as it seems that you use jQuery you could think of just using .text instead of .html as this will do the escaping for you.
An additional note:
I'm pretty sure that the var escapedData=unescape('${column}'); does not do anything. I assume that ${column} already is ni!er#/nice&.
So please check your source code. If var escapedData=unescape('${column}'); will look like var escapedData=unescape('ni!er#'); then you should remove the unescape otherwise you would not get the expected result if the ${column} contains something like e.g. %23.
Following my code:
<div onclick="this.innerHTML='<div onclick=\"<img src=/*how to do here?*//>\">abc</div>'">a</div>
I would like to do everything on one line, can I specify the address of the image with the current example code or not?
Use " to represent a " character in an HTML attribute value delimited with " characters.
(Use & to represent a & character in an HTML attribute value, so if you want to nest insanely then: ")
But don't do this.
Writing everything on a single line in not a virtue.
Writing JS in an onclick attribute instead of a .js file is not a good thing.
Use addEventListener and friends.
I've read a lot of the HTML encoding post for the last day to solve this. I just managed to locate it.
Basicly I have set an attribute on an embed tag with jQuery. It all works fine in the browser.
No I want to read the HTML itself to add the result as a value for an input field to let the user copy & past it.
The PROBLEM is that the .html() function (also plain JS .innerHTML) converts the '&' char into '& amp;' (without the space). Using differen html encoder functions doesnt make a difference. I need the '&' char in the embed code.
Here is the code:
HTML:
<div id="preview_small">
<object><embed src="main.swf?XY=xyz&YXX=xyzz"></embed>
</object></div>
jQuery:
$("#preview_small object").clone().html();
returns
... src=main.swf?XY=xyz&YXX=xyzz ...
When I use:
$("#preview_small object").clone().children("embed").attr("src");
returns
main.swf?XY=xyz&YXX=xyzz
Any ideas how I can get the '&' char direct, without using regex after I got the string with .html()
I need the & char in the embed code.
No you don't. This:
<embed src="xyz&YXX=xyz"></embed>
is invalid HTML. It'll work in browsers since they try to fix up mistakes like this, but only as long as the string YXX doesn't happen to match an HTML entity name. You don't want to rely on that.
This:
<embed src="xyz&YXX=xyz"></embed>
is correct, works everywhere, and is the version you should be telling your users to copy and paste.
attr("src") returns xyz&YXX=xyz
Yes, that's the underlying value of that attribute. Attribute values and text content can contain almost any character directly. It's only the HTML serialisation of them where they have to be encoded:
<div title="a<b"&c>d">
$('div').attr('title') -> a<b"&c>d
I want to read the HTML itself to add the result as a value for an input field
<textarea id="foo"></textarea>
$('#foo').val($('#preview_small object').html());
However note that the serialised output of innerHTML/html() is not in any particular fixed dialect of HTML, and in particular IE may give you code that, though generally understandable by browsers, is also not technically valid:
$('#somediv').html('<div title="a/b"></div>');
$('#somediv').html() -> '<DIV title=a/b></DIV>' - missing quotes
So if you know the particular format of HTML you want to present to the user, you may be better off generating it yourself:
function encodeHTML(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
}
var src= 'XY=xyz&YXX=xyzz';
$('#foo').val('<embed src="'+encodeHTML(src)+'"><\/embed>');
(The \/ in the close tag is just so that doesn't get mistaken as the end of a <script> block, in case you're in one.)