1

I just ran into this weird behavior with JQuery:

I've got one of these in my HTML:

<input type="file" name="pdfUrl" id="pdfUrl" />

This didn't work:

$pdfUrl = $('#pdfUrl');

But this did:

$pdfUrl = $('input:file')[0];

How come?

To clarify, I only have one id with pdfUrl in my document. Could it have something to do with the name and id being the same?

Running the chrome console gives this:

$('#pdfUrl')
[<input type=​"file" name=​"pdfUrl" id=​"pdfUrl">​]

So that seems to be working.

Difusio
  • 789
  • 1
  • 8
  • 22

4 Answers4

2

$("#pdfUrl") that contains only one object returns the same type of object as $(".rows") which might contain hundreds of DOM objects. This vastly simplifies jQuery programming because you don't have to do things differently depending upon how many objects come back from the selector query.

When you refer to $('input:file')[0];, you are reaching into the jQuery object's internal array of DOM objects (that was populated on the selector query) and fetching the first DOM object in that array. At that point, you have a normal DOM object, not a jQuery object and you can use normal DOM methods or attributes on it. Occasionally this is required (to fetch the actual DOM object), but usually, it's easier to just use the methods that jQuery provides on the jQuery object. There are lots of advantages to using them such as you can chain multiple requests to most methods and it will iterate over all the DOM objects in it's internal array for you automatically.

Have a look at this

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • even if there are more than 1 element with the given id the id selector has to return the first element with the said id – Arun P Johny Dec 26 '13 at 09:24
  • @ArunPJohny jquery selectors **always** return jquery object – Grundy Dec 26 '13 at 09:53
  • But how come entering the id selector $(pdfUrl) in chrome console gives back the object, but the same code in the script itself doesn't? – Difusio Dec 26 '13 at 11:25
1

yes this is because id is not unique. pdfUrl must be the id of another element also.

Harish Lalwani
  • 754
  • 5
  • 20
0

If id with pdfUrl is unique in your html, then $('#pdfUrl') will be ok.

So check whether there are duplicated id with pdfUrl.

id must be unique.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

try using: $('[id*=pdfile]')

Generally what happens is: an element takes its parent's ID and forms a longer ID as follows:

GrandParentID:PaarentID:ownID..

this leads to confusion for the selector, which can be avoided by using id*=

ipradhansk
  • 352
  • 1
  • 10
  • 36