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
Related
I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;
I'm trying to use the indexOf property in JavaScript/jQuery to detect if there's a comma in a value. This is what I'm trying:
var valueTotalCost = data.TotalCost;
if (valueTotalCost.indexOf('.') > -1)
{ $('table#cartTable tr#' + data.AppItemId + ' td:nth-child(3)').text('£' + data.TotalCost); }
else
{ $('table#cartTable tr#' + data.AppItemId + ' td:nth-child(3)').text('£' + data.TotalCost + '.00'); }
I'm getting an error
valueTotalCost.indexOf is not a function
What might I be doing wrong and how I can fix this? I want to detect if the value already has decimals then don't put tow trailing decimal places, otherwise put two decimal places.
Change the first line from
var valueTotalCost = data.TotalCost;
to
var valueTotalCost = data.TotalCost.toString();
The reason that you're having this problem is most likely because you are trying to use .indexOf() on a number of some kind. .indexOf() is a string method, and so it isn't accessible on numbers.
Usually when you run into a problem like this, I would recommend hopping on Google and searching for the method name. Then you can hit up a Mozilla Resource (generally the easiest to read in my opinion.) like this one:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
Try
var valueTotalCost = String(data.TotalCost);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
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.
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);
I have an issue with jquery where elements are not found when the query string has '$' char in them -- is there a known issue? Unfortunately search engines make it so hard to searh for symbols in threads.
I have an html such as this:
<TD id="ctl00$m$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60$ctl00$ctl00_5"
class="MenuItem"
onclick="setSelectedTab('ctl00$m$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60$ctl00$ctl00_5');"
tabsrowid="ctl00$m$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60$ctl00$ctl00_"
nohide="false">...
and my jscript goes something like:
function setSelectedTab(selection) {
var ids = selection.split('/');
for (var i = 0; i<ids.length; i++) {
var item = $("#" + ids[i]);
item.addClass("selected");
$("#" + item.attr("tabsrowid")).show();
}
}
While analyzing in firebug, I see that 'item' is an empty set. If I query $('.MenuItem') for example, it correctly returns a result set with 25 matching items in the page; it appears like $(s) doesn't work when s contains $ chars in it?
What's the solution to it? Sorry if it a dumb question or well known issue -- as I said I tried to google around, but unsuccessfully.
Note: It's not an issue with javascript itself, or duplicate ids, or jquery not loaded, or anything like that. The function does get called onclick, and if I replace $('#' + ids[i]) with document.getElementById(ids[i]), it does return the correct element.
fyi, the string passed to the function setSelectedTab usually contains a hierarchical path to the TD element; though in the example TD above, the ids.length is 1.
Thanks,
Raja.
Perhaps try escaping them with backslashes
<TD id="ctl00\$m\$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60\$ctl00\$ctl00_5"
class="MenuItem"
onclick="setSelectedTab('ctl00\$m\$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60\$ctl00\$ctl00_5');"
tabsrowid="ctl00\$m\$g_cd3cd7fd_df51_4f95_9057_d98f0c1e1d60\$ctl00\$ctl00_"
nohide="false">...