jquery escape square brackets to select element - javascript

Consider a input element
<input id="meta[152][value]" type="text" />
Here the input field is dynamically generated. I need to select that field. So I used,
alert($('#meta[152][value]').val());
But this seems to be invalid. After searching I found, that the "square brackets" need to be escaped like #meta\\[152\\]\\[value\\]
So how to do that ?
I currently use this code,
var id = "#meta[152][value]" // (I get this value by another method) I need the escaping to be done here. So that i can use as
/** I need the value of id to be escaped using regex,replace or any other method
to get #meta\[152\]\[value\]
and not manually **/
alert($(id).val());
Your suggestions will be helpful !

The following should work:
alert($('#meta\[152\]\[value\]').val());
or
var id = "#meta\[152\]\[value\]";
alert($(id).val());
Working Example
Conversion Function:
function ConvertValue(id)
{
var test = id.replace(/[[]/g,'\\\\[');
return "#" + test.replace(/]/g,'\\\\]');
}
Conversion Example

If you feel more comfortable without escaping you also use the attributes selector and search for the element with that id like this: $("[id='meta[152][value]']")

The simplest way is just to use the regular getElementById, which requires no escaping:
document.getElementById("meta[152][value]").value;

this shoudl work for you, you almost had it:
$(document).ready(function() {
var id = "#meta\\[152\\]\\[value\\]";
alert($(id).val());
});

Um, just put the escaped value right in your string.
var id = "#meta\\[152\\]\\[value\\]";
See it working here

You can use the _.escapeRegExp method from the Lodash library.
console.log($('#' + _.escapeRegExp('meta[152][value]')).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<input id="meta[152][value]" type="text" value='Test' />

Related

Jquery get element by id, multidimensional array

I'm trying to get the value of a specific html input that is named like:
<input type="hidden" value="." id="grid[0][0]">
where [0][0] could be any value within a foreach loop.
using Jquery:
var currVal = $('#grid['+x+']['+y+']').html();
I'm getting an undefined value. Not sure whether it's a syntax problem. I haven't found a similar example so I'd appreciate any help on this. Thanks!
It actually is a syntax problem. jQuery interprets "#grid[...]" as an HTML element with the ID "grid" and some attribute (or other meta stuff) just like CSS would.
To solve simply escape the [ and ], like this:
$('#grid\\[' + x + '\\]\\[' + y + '\\]').val()
That should do it :)
Edit: As noted by Josh Crozier, the html() method is supposed to be used in normal tags (like div). For input, select or textarea you should use val() -- Docs on that: http://api.jquery.com/val/
You can also do :
var currVal = $('input[id="grid['+x+']['+y+']"]').val();

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

How to get the value from a string using javascript

I have a string like follows in javascript
var str='<img class="avatar avatar-small 012345" src="/img/staff_avatar_profile.jpg" /> olah blah';
I need to get every time the number like for this example 012345. Which will be ofcourse be different in different scenario and I also need to get the text olah blah which will be also different in different scenario.
I have the above string in a variable. ;)
How can i perform this in a efficient manner in java-script
The best way to parse HTML in a browser is to let the browser do it for you:
var div = document.createElement('div');
div.innerHTML = str;
var numbers = div.getElementsByTagName('img')[0].className.match(/ (\d+)/)[1];
Here's the fiddle: http://jsfiddle.net/CGuLC/1/
You could use jQuery if it works there to get an only numeric class name. Take a look at jQuery - selectors on a html string to get a clue.
Use the data attribute instead of class.
<img class="avatar avatar-small" data-id="012345" src="/img/staff_avatar_profile.jpg" />
Then use jQuery to get the data attribute.
jQuery('.avatar').data('id');
Sources:
http://html5doctor.com/html5-custom-data-attributes/
http://api.jquery.com/data/
If you need to store data for an element, one good way to achieve that is to use the data-key attribute with jQuery:
$('.avatar').data('number', '012345'); // set value
var number = $('.avatar').data('number'); // get value
The rendered markup will look like this:
<img class="avatar avatar-small" data-number="012345" src="/img/staff_avatar_profile.jpg" />

How to read the contents of text area by jQuery?

<textarea id="metaSourceText" name='key' style="width:100%" class="text ui-widget-content ui-corner-all" rows="1"></textarea>
I tried
$metaSourceValue = $('metaSourceText').val();
alert($metaSourceValue);
But it shows "undefined"
Your code just needs to be tweaked, to something like this:
var metaSourceValue = $('#metaSourceText').val();
alert(metaSourceValue);
you were missing the hash before metaSourceText, signaling an ID to jQuery. And you typically don't want to start variables with $
You missed the # character in $('#metaSourceText')
.text() method will also give you value of textarea. In ready() state you can either get object of textarea using class selector or id selector.
$(document).ready(function () {
$("#submitbtn").click(function () {
var textAreaValue = $("#txtMessage").text();
alert(textAreaValue);
});
});
Check sample here: http://www.codegateway.com/2012/03/get-textarea-value-in-jquery.html
Please define the selector with '#' prefix as it is an ID you are referring.
In your case, it refers a DOM element of type metaSourceText which really does not exists..
To get a value of this text area:
you can use .text() or val();
$(function(){
var textareaContent = $('#metaSourceText').text();
alert(textareaContent);
​}​);​
fiddle link:http://jsfiddle.net/Ds4HC/1/
Javascript variables don't start with $. EDIT: They can, but usually do not. See
Why would a JavaScript variable start with a dollar sign?)
You want to try:
var metaSourceValue = $('#metaSourceText').val();
alert(metaSourceValue);
The $(...) used by jQuery is a shortcut to the jQuery function.
Also, as others mentioned, you need $('#metaSourceText') if you're trying to reference the textarea by id - you were missing the #.

Categories

Resources