[thelist] Javascript bookmarklet to populate fields takes me to new page — why?

Lee Kowalkowski lee.kowalkowski at googlemail.com
Wed Sep 23 15:30:18 CDT 2009


2009/9/23 Barney Carroll <barney at clickwork.net>:
> Hi folks,

Hi Barney,

Looks like Ben's sorted you out already, I just thought I'd volunteer
an explanation.

>javascript:document.getElementById('productDescriptor1').value='this';document.getElementById('productDescriptor2').value='that';
>   1. Only the last command takes effect. For the script above, only
>   productDescriptor2 gets 'that' assigned to it.

I'm not clear how you concluded that, that's not what supposed to
happen, perhaps there's a typo in the ID?  Or perhaps that's just how
it looks when it's not working properly.

>   2. Immediately after the DOM script takes effect, I am given a document
>   whose only content is the last value I assigned. Just a blank page with
>   unformatted 'that', and the page I had been scripting for in my immediate
>   history.

That's what most browsers do when they process JavaScript URIs.  They
evaluate the JavaScript and return the last evaluated statement as the
requested resource.  e.g. javascript:"Hello World!".  You can prevent
this by simply having "undefined" as your last JavaScript statement,
but "void 0" is shortest as far as I know (Internet Explorer had quite
a short URI length limit in bookmarks).  This makes your JavaScript
return nothing, and the browser keeps the current resource loaded.

So you get "that" because the last thing you have is "='that'".  The
assignment operator returns the assigned value, that's why you can do
"a=b=c=0" (a, b & c will be set to zero).

-- 
Lee
www.webdeavour.co.uk



More information about the thelist mailing list