homepage Welcome to WebmasterWorld Guest from 54.242.126.126
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
javascript tips and code cutting
tips on how to extract fat out of the code
copongcopong

10+ Year Member



 
Msg#: 1989 posted 1:50 am on Jun 29, 2004 (gmt 0)

Hi everyone,
lately i was hand-coding javascript and every function that i created, i need to access and do ...

document.formname.fieldname.value=...
document.formname.fieldname.disabled=...
getElementById('id').style.background= ...
etc ...
is there any tips you could give to so that I could simply make the "fieldname" part into a variable so that I could just do ...

var arr = new Array(fieldname1, fieldname2, etc ... );
for(i=0; i<arr.length; i++)
{
document.formname.arr[i].value='';
}

it does not need to be the above code for i know it does not work, but anything like that could help. =)

 

Purple Martin

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 1989 posted 4:38 am on Jun 29, 2004 (gmt 0)

Making the "fieldname" part into a variable is as simple as declaring it:
var myFieldName = document.formname.fieldname;
You've now got a variable which is a reference to the field object, so you can use your variable to get/set properties for the object, eg:
myFieldName.disabled=...

Here is another hint: if you have a function called when a form is submitted to do some validation, you can use the "this" keyword to pass a reference to the form directly to the function:
<form onSubmit="return validate(this);">
<script type="text/javascript">
function validate(form) {
form.fieldname.disabled=...
return true;
}
</script>
The cool thing about doing it "this" way is that you can call the same function from several forms, and it will automatically know which form called it.

copongcopong

10+ Year Member



 
Msg#: 1989 posted 7:59 am on Jun 29, 2004 (gmt 0)

but what if i have a lot of fieldname, for example 10? thanks

dcrombie

10+ Year Member



 
Msg#: 1989 posted 9:31 am on Jun 29, 2004 (gmt 0)

Have a look at the with statement.

eg. with(document.formname) { // do stuff }

That 'localises' the form elements so you don't need to use "document.formname." when you reference them.

;)

Bernard Marx

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 1989 posted 10:07 am on Jun 29, 2004 (gmt 0)

There's no actual reason to hard-code the names/ids of your elements into the script.

..but if you need to, do this, after load:

var elms = document.forms["_formName_"].elements
myFields =
[
elements["_name_"],
elements["_name_"],
........
elements["_name_"]// no comma
]

This is only needed, if your want to be really specific. You can rely on the form's collections instead. Collections behave like arrays, but your can also access their members by other means. The form will have collections:

// all input elms. Access by index, name (id on modern browsers too)
theForm.elements
// Specific tags. Access by index, id
theForm.getElementsByTagName("input")

You could loop through these by index, picking out only the ones that match a certain property.
This can be done after load to put into an array, or in specific functions later.

var inputs = document.forms["_formName_"].getElementsByTagName("input")
for(var k=0;k<inputs.length;k++)
if(inputs[k].type == "checkbox") // *
inputs[k].someProperty = someValue

* For 100% safety use a RegExp (no case sensitivity):
if(/checkbox/i.test(inputs[k]))

-----------------------------------------------------

dcrombie Re: with

I've recently read reports from Javascript "leading lights" that with should not be used. I always have difficulty with it, and find it easier to shorten the chain to one local variable, and leave it at that. Whether there's actually 'wrong' or unreliable with with I don't know.

Can I back this up? Probably not.

Douglas Crockford [crockford.com ] simply says (to save you the trouble): The with statement should not be used.
..not much help! I have seen better, but can't find it now.

Here is something more browser-specific:

[home.hiwaay.net ]

dcrombie

10+ Year Member



 
Msg#: 1989 posted 10:20 am on Jun 29, 2004 (gmt 0)

I think with is probably ok in simple situations - it sounds like there might be problems if the object changes while you're inside a with (if that makes any sense).

It seemed like the simplest solution to the question above - though I'd tend towards something more like you describe.

copongcopong

10+ Year Member



 
Msg#: 1989 posted 12:30 am on Jun 30, 2004 (gmt 0)

yup i also read a book from orielly about using "with" is not always recommended. An out of the box solution i did is to have php do the recursive type/echo 'formname.fieldname.etc ...' thanks for your help. Any other great tips to cut the fat out? =)

Bernard Marx

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 1989 posted 11:09 am on Jun 30, 2004 (gmt 0)

er..yes..

Don't use that recursive typing thingy! The best way (if not using with) is to put the reference chain into a single local var, which very nearly amounts to the same thing as with, but without the possible confusions.

There'll be less code, less of an eye-full, and it's faster (which only makes a difference if the form is long).

Another tip is to use the keyword, this, if you are using event handlers in the form. Each input element has a property, .form, that refers to the form, so can go on from there inside the function without having to reference global or document properties (efficiency). It also means that, as there are no specifics in the handler, you can cut'n'paste it straight into another form (that means less PHP-ing for you).

<input type="text" onchange = "doSomething(this)">

function doSomething(element)
{
// element var refers to the input
var form = element.form
}

For pages with many, many event handlers (eg long tables with reactive inputs in every cell), you might consider scrapping all local event handlers, and catch all events as they bubble to whatever ancestor element you see fit (form, table). This can mean a mild increase on the script side to process the event for it's source element and/or the event type. A small touch of cross-browser tweaking is needed, but that can be achieved with a couple of global functions.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved