Is there a way I can use a selector for a name attribute that has [] at the end? The below code won't work, is there an alternative?
$("[name=some_attribute[]]")
Use ' to wrap the name:
$("[name='text[]']");
Demo
Try before buy
Yes, you can escape with backslashes. So:
$("[name=some_attribute\\[\\]]")
Note that since I'm writing the backslash in a string literal, I have to escape it (with another backslash).
You can also use quotes around the value:
$("[name='some_attribute[]']")
// or
$('[name="some_attribute[]"]')
These are both actually CSS things rather than jQuery things: The value used in an attribute selector must be a CSS identifier or a string.
Working DEMO
Guess this is what you need
$("*[name$='\\[\\]']")
OR
$("[name$='\\[\\]']")
OR
$("[name$='[]']")
Hope this helps, Thank you
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
Is it possible to use a dot in a classname inside Jquery?
$('.B.Avf').toggle();
I need to keep the dot in: B.Avf classname.
Can i somehow escape it?
Is this possible?
UPDATE
I tried to escape it with "\" with no success.
You can always just use the [attr="val"] selector for this.
$('[class*="B.Avf"]')
The *= means "class contains...". Since this is looking at the attribute directly and there could be more than one class, you don't want to use =.
There are two ways to select elements that have special selection characters in their identifiers. As Tushar mentioned in a comment, you can use a double backslash (\\) to escape the special character in query (including both jQuery and document.querySelector), or you can use an attribute selector, as Rocket Hazmat pointed out.
Note that in CSS (that is, an actual stylesheet, not JavaScript), the selector is slightly different. You only need a single backslash to escape the special characters.
Demo below:
// use a double backslash to escape characters in JavaScript query selectors
document.querySelector(".a\\.b").style.backgroundColor = "blue";
//or use an attribute selector!
document.querySelector('[class="a.b"]').style.color = "white";
/* Use a single backslash to escape characters in CSS */
.a\.b{border:1px solid black;}
<div class="a.b">My class name is a.b</div>
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 a function that, when clicked, fills in a field of the parent window. In this case, it's a name (text) field.
The problem I'm having is if the field has a single quote in it (ex. Bill's Chili) the function fails because it reads the single quote as the end of the parameter.
Here is the call:
href="javascript:selectItem('recipe','recipe_name','<recipe_description')"
Again, if the name is Bill's Chili, it causes a syntax error.
Is there a way to automatically convert that single quote to the HTML equivalent so it will read properly?
Thanks
For the single quotes in the field use \' More info on escape characters here.
href="javascript:selectItem('Bill\'s Chilli','recipe_name','<recipe_description')"
The answer I found was completely different than I thought. The page itself is written is ASP (Sorry I forgot to mention that, I didn't think it mattered since the function was javascript and it was called in HTML).
Therefore, I just used this:
<%fixed_name = Replace(recipe_name,"'","") %>
And then used fixed_name instead of recipe_name in the function call.
Thanks for all your help, it set me in the right direction!
try this
href='javascript:selectItem("recipe","recipe_name","<recipe_description")'
You may try to use escaped 'double' quote like that:
href="javascript:selectItem(\"recipe\",\"recipe_name\",\"recipe_description\")"
Please let me know whether it works.
You could use str.replace
Just remplace " by " et ' by ' . :)
But actually, I'm assuming you're getting all of that stuff from a php script (from some sort of storage), in which case you could escape the quotes directly with php, that would be way more safer.
Does javascript regular expressions support backreferences inside character class?
I want to do something like this:
htmlString.replace(/attribute_name=(['"])[^\1]*\1/,'')
But that does not work. This does:
htmlString.replace(/attribute_name=(['"])[^'"]*\1/,'')
Unfortunatelly my attribute_name can contain apostrophes or quotes, so I need to exlude the actual quoting character from the inside of the attribute, but leave the other one.
I can't be sure which one is used. I can safely assume that quotes are in form of entity, but still there can be apostrophes inside:
<div attribute_name="John's car" class="someClass"></div>
<div attribute_name='some "quoted text"' class="someClass"></div>
I am not able to predict which of " or ' will be used around the attribute.
How to get rid of the attribute and leave the class attribute alone (not cut too much)?
context:
I am getting the html by $('templateContainer').innerHTML . I have to modify that html before inserting it into the page again. I have to cut some non-standard attibutes and all the ID attributes.
I agree with the other answers in that I don't think that the attributes are the place to do this type of thing, but I'm also wary of recommending the DOM either. I just feel dirty when I do that, I don't know why.
I usually will try to use a javascript object to store my data in and then reference it using well-formed keys, etc. shrug It's more work, but it's cleaner IMHO. But, it definitely isn't the only way to accomplish the task.
As to your question, you could also use the non-greedy matching in JavaScript and it would look like this:
htmlString.replace(/ ?attribute_name=(['"]).*?\1/, '')
Regular Expressions in JavaScript | evolt.org
You'd be a LOT better off using DOM or some other actual model designed for hierarchical content. That said, if you must use regex, the simplest way would probably be to just use a | (OR) instead.
htmlString.replace(/attribute_name=('[^']*'|"[^"]*")/,'')