Jquery get element by id, multidimensional array - javascript

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();

Related

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

jQuery trying to build up and then append HTML

I've put a much simplified example on jsFiddle.
Basically, I'm trying to build up my HTML and then append the whole thing once I'm done. The JS looks like this:
var label = 'My label',
var checkbox = $('<input type="checkbox">').prop({
id: 'checkboxId',
name: 'checkboxId',
checked: visible
});
listItem = ('<li class="customise_option"><label>'+checkbox+' '+label+'</label></li>');
$('#mylist').append(checkbox);
$('#myotherlist').append(listItem);
Appending just checkbox is fine, but if I try to include checkbox within my listItem variable then I just get:
[object Object] My label
So, on it's own jQuery is fine with appending my checkbox as a string, but when I try to do anything with that it treats it as an object.
Having looked around there are some similar questions, but as I'm creating everything in JavaScript (rather than manipulating something that already exists in the DOM) it seems there must be a way to do what I want. Problem is I can't figure it out.
EDIT
I simplified my original example too much, not understanding the problem fully. I have updated the jsFiddle to show that on my checkbox I need to be able to add a bunch of properties. So, the checked property will be reliant on something else. As such, I need $ so I can access jQuery's prop function (I think).
var label = 'My label',
checkbox = '<input type="checkbox">';
listItem = '<li class="customise_option"><label>'+checkbox+' '+label+'</label></li>';
$('#mylist').append(checkbox);
$('#myotherlist').append(listItem);
Here's the jsfiddle. If you're adding HTML markup, all you need are strings; you weren't far away.
checkbox is a jquery object, when you say string + checkbox you're casting checkbox to a string (which gives [object Object]) and then appending it. you need to use append() there as well.
Its because checkbox = $('<input type="checkbox">') returns a jquery object.
Either stick to jquery objects and use methods like text() etc, or stick to appending string representations of HTML. Just dont mix it.
This happens because the checkbox is an object.
With this code, works
var label = 'My label',
checkbox = '',
listItem = ''+checkbox+' '+label+'';
$('#mylist').append(checkbox);
$('#myotherlist').append(listItem);

How to get an element by name and set its value

There should be a simple solution for this. I need to get an input element by name and set its value.
The following Javascript does not work:
x = document.getElementsByName($('#questions').val());
x.value=this.value;
Is there a simple solution using JQuery?
Description
You are mixing normal javascript and jQuery.
Use the attribute selector.
Check out my sample and this jsFiddle Demonstration
Sample
Html
<input type="text" name="nameOfTheInputElement"/>
jQuery
$(function() {
$("input[name='nameOfTheInputElement']").val("your value");
});
​
Edit
If you want, for some reason, change a element which name is a value in another element
then do this. jsFiddle Demonstration
Html
<input type="text" id="questions" value="nameOfTheInputElement"/>
<input type="text" name="nameOfTheInputElement"/>
​jQuery
$(function() {
var name = $("#questions").val();
$("input[name='"+name +"']").val("your value");
});​
More Information
jQuery - Attribute Equals Selector [name="value"]
jsFiddle Demonstration (first sample)
jsFiddle Demonstration (second sample)
A simple, pure JavaScript (and therefore faster) solution:
var x = document.getElementsByName(document.getElementById('questions').value)[0].value = this.value;
I know jQuery's tagline is 'Write less, do more', and in many cases it is true... many cases !== always, though ;-)
getElementsByName() returns a node-list, so you need to get the first one getElementsByName(...)[0]
But you are already using jQuery, so use it. Read some tutorials about the jQuery selectors
Try this
var q = $("#question").val();
var x = $("input[name='" + q + "']").val();
on the 2nd line, variable q, the name provided in input with id 'question', will be enclosed with ' and could contain any supported characters, like space, :, -, etc
If you need the value of a component regardless of its tag, you can do this:
var x = $("[name='" + q + "']").val();
Consider that this approach $("[name='" + q + "']") can return more than one element, but .val() will return only the value of the first element.
If I'm understanding your question correctly, you want to get an element by name, and the name of the element you're selecting will be specified by some dropdown or text area.
Here's my take on it:
Html
<input type="text" id="enteredName">
<button id="doTheStuff">Do the work</button>
<input name="one" value="One">
<input name="two" value="Two">
jQuery
$('#doTheStuff').click(function(){
var objectOfInterest = $('[name=\'' + $('#enteredName').val() + '\']');
alert(objectOfInterest.val());
});
Working example
Here's another working example using a dropdown to specify the selection name.
$('#form-id input[name="name-input"]').val('your value');

jquery escape square brackets to select element

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' />

jQuery: Using Selectors on HTML from an Attribute

I have some HTML that is stored as an attribute on a tag. I can access it in jQuery using
$("input[id$='_myField_hiddenSpanData']").attr("value")
This looks like this:
"<span id='spantest\user' tabindex='-1' contentEditable='false' class='ms-entity-resolved' title='test\user'><div style='display:none;' id='divEntityData' key='test\user' displaytext='Test User' isresolved='True' description='test\user'><div data=''></div></div><span id='content' tabindex='-1' contenteditable onMouseDown='onMouseDownRw();' onContextMenu='onContextMenuSpnRw();' >Test User</span></span>"
I would need the value of the key attribute (test\user). Can I somehow tell jQuery to parse a block of HTML and apply selectors to it? I found I can wrap it into a new jQuery object by wrapping it into another $(): $($("input[id$='_myField_hiddenSpanData']").attr("value")) but I still did not manage to apply a selector on it.
Any hints? And no, sadly I do not control the markup that generates the hidden field.
Wrap your crappy markup with a jQuery object, and then use the find function to apply a selector to it...
var crappyHtml = $("input[id$='_myField_hiddenSpanData']").attr("value");
var key = $(crappyHtml).find("div[key]").attr("key");
alert(key);
Try this:
var html = $("input[id$='_myField_hiddenSpanData']").attr("value");
var user = $(html).find("#divEntityData").attr("key");
alert("user=" + user);
You should be able to pass it as a context. Does this work?:
$('#divEntityData', $($("input[id$='_myField_hiddenSpanData']").attr("value"))).attr('key');

Categories

Resources