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.