What is the correct jquery syntax for a getElementsByName call?
Here is my javascript code:
var test = document.getElementsByName(tableName)[0];
using this is returning a different value:
var test = $("[name=tableName]");
Thanks in advance
Use quotes around the attribute selector:
$('[name="somenamehere"]');
If you need to use a variable within a selector, you need to use string concatenation to get the value of the variable:
$('[name="' + tableName + '"]');
Typically one should avoid using the [name] attribute in favor of the [id] attribute, because selection would be simpler as:
$('#someidhere');
-or-
$('#' + tableID);
Remove the index from the first statement
These are equal.
var test = document.getElementsByName(tableName);
var test = $("[name=tableName]");
"[name=tableName]" is bad syntax in 2 ways. First, you should put your name in quotes, so it should be "[name='tableName']" and second, in the first case, you're using a variable and in the second, a string, so in reality it shoudl be "[name='" + tableName + "']"
good call also on the fact that you have an index on your getelementsbyname() call, if you select item [0] then it will only return one item.
Interesting to know that jquery is a LOT slower than the native method here.
See the jsPrefs test : http://jsperf.com/getelementsbyname-vs-jquery-selektor/4
if you want to get a element value use this code:
var test1 = $("[name='tableName']").val();
alert(test1);
These are equal to get value of specific index[]:
For same index [0]
var test2 = $("[name='arryname[]']")[0];
alert(test2.value);
var test3 = $("[name='arryname[]']").get([0]);
alert(test3.value);
Related
Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.
The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.
Try \" instead of ' in onClick
$(".container").append("Edit");
You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.
Hi I have an array like this.
var i;
for(i=0;i<10;i++){
$('<input/>').attr('type','text')
.attr('name','TxtBx_[]')
.attr('id','TxtBx_' + i)
.attr("readonly","readonly")
.attr('value',i)
.addClass('txtbx')
.appendTo($div);
}
And I prints the 10 input boxes well.
Later I need to get the number of text boxes I have created. So I'm using
var myarr=document.getElementsByName('TxtBx_');
var numberofElements=myarr.length;
but when I put an alert to check the value of numberofElements it gives me always 0. The length of the array must be 10. Could someone please let me know the mistake I have made.
The elements' names are TextBx[], not TxtBx_.
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Element names are TextBx[] and TxtBx_ is a class name
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Read getElementsByName() documentation for more information
var numberofElements = document.getElementsByName("TextBx[]").length;
Name of textbox is 'name','TxtBx_[]' getting by TxtBx_.
Because no element has name TxtBx_ . It's TextBx[] actually.
Since you are alrady using jQuery, you can find by class like below,
$('.txtbx').length
Few other things, I would like to add here.
attr accepts a object too. So, you can pass all inputs at once. Also, you can pass attributes as second arguement while dynamically creating input. Also, according to jQuery docs, you should specify type in input type while dynamically creating them or it won't work in some IE.
So, try something like this,
var i;
for(i=0;i<10;i++) {
$('<input type="text"/>',{
'name': 'TxtBx_[]',
'id': 'TxtBx_' + i,
'readonly':'readonly'
'value': i,
'class': 'txtbx'
}).appendTo($div);
}
Try it
$("input.txtbx").length;
Just use the class to get them:
var numberofElements = $('.txtbx').length;
I've been working on this all day and just cannot seem to figure out why it won't work. I am grabbing a delimited string from a hidden field. I need to test to see if a string is contained in that original string. The simple example below should work but does not.
var orgStr = "091300159|091409568|092005411";
var newArr = orgStr.split('|');
console.log(orgStr);
console.log(newArr);
console.log("inarray? " + $.inArray(newArr, "092005411"));
It seems to work if I can wrap quotes around each value but all attempts are unsuccessful.
In JQuery's inArray function the value needs to come before the array.
console.log("inarray? " + $.inArray("092005411", newArr));
You could also use the native indexOf operator as such:
console.log("inarray? " + newArr.indexOf("092005411"));
Both should output "inarray? 2" to the console.
Have a look at the $.inArray docs.
The first argument is the value and the second the array. You did the opposite.
$.inArray("092005411", newArr) correctly returns 2.
I've been trying different methods of getting my page to update one input value when I select something from another. When I try it one way using javascript it works fine, another way via jQuery it doesn't and I honestly don't understand why, could someone point out what I'm missing?
This Javascript works fine: -
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
document.getElementById(objID).value = id
}
But this jQuery doesn't: -
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
}
The objects on the being used/references are all loaded in during the page load via AJAX calls etc, is this something to do with what's causing the issue?
Thanks for any pointers, if anyone has any good links to read explaining this stuff better I'd be very appreciative! :)
Also tried this but still no dice...
$(document).ready(function(){
function updateHiddenInput(id, num){
var objID = "any[" + num + "].id";
$("#"+objID).val(id);
}
});
There's a difference between a jQuery selector and document.getElementById. The second does less, so it knows that whatever you give it will be looked at as an id. For example:
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
What will this look for? Let's presume num is 1, say:
$('#any[1].id').val(id);
This looks for an element with the id #any, an attribute 1, and a class id, because the characters []. all have special meanings in a selector. To demonstrate this, run the following line of code in the browser console:
$('<div id="any" class="id" 1="foo"/>').is('#any[1].id') // returns true
The best way to do this selection is to do the selection with document.getElementById, and then wrap it in the jQuery constructor:
$(document.getElementById(objID)).val(id);
It is possible to escape the special characters with \\, but it becomes increasingly unwieldy and hard to (a) write and (b) read.
You have this:
function youPickedThis(id, num){
var objID = "any[" + num + "].id"
$("#"+objID).val(id);
}
This results in objID having some value like any[3].id, so your jQuery looks like this: $("#any[3].id").val(id); jQuery interprets the .id as a class. Escape it like this:
function youPickedThis(id, num){
var objID = "any\\[" + num + "\\]\\.id"
$("#"+objID).val(id);
}
You should escape square brackect and dot
var objID = "any\\[" + num + "\\]\\.id";
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").
REFERENCE
http://forum.jquery.com/topic/jquery-jquery-wont-recognise-attribute-names-containing-square-brackets#14737000000283511
As others have mentioned, there are differences between jQuery selector and document.getElementById. As jQuery selector has to parse the string and some characters like [,] have special meaning while document.getElementById treats all this as part of an id. You could try escaping those special characters as mentioned by others. Here I give another solution.
You could try id attribute selector. It does something similar to document.getElementById
function youPickedThis(id, num){
var objID = "'any[" + num + "].id'"
$("[id="+objID+"]").val(id);
}
DEMO
What I'm trying to ask is that when I take on a .each loop in jQuery using a build of a string by this:
$('.list :checkbox').each(function()
{
var type = $(this).attr('value');
Build += type + ', ';
return Build;
});
But now I need to remove the last "," (without quotes) since it makes a list like this:
Item 1, Item 2, Item 3, Item 4, Item 5,
Then it has to be added to the html() function which works well, but when trying to remove the last "," doesn't work by doing this:
Build.substr(-1);
$('#list-box').html(Build);
But that won't work.
You could simplify your code with something like this:
(updated)
var arr = $(":checkbox").map(function() {
return this.value;
}).get();
$('#list-box').html(arr.join(","));
Try it here: http://jsfiddle.net/andrewwhitaker/rXB2K/ (also updated)
Uses the map() function to translate the jquery results array to an array of checkbox values.
Calls join(), separating each value with a comma.
#YouBook: Try
Build.substr(0, Build.length - 1);
instead.
Have you tried using substring instead of substr? e.g.
Build.substring(Build.length - 1);
Build = Build.slice(0,-1);
works?
Instead this:
return Build;
write this:
return Build.substr(0, Build.length-1);
Don't use initial caps for variables.
Also, Strings are immutable in JS, so it's
build = build.substring(0, b.length-1)
This is a general purpose function called join in most languages, you should break it out as a utility function.
You should take into account the possibility of a zero length list.