user656925
user656925

Reputation:

How do I optimize this Javascript?

I tried to convert snippet 1 to snippet 2 but this did not work (the text fields did not clear). f3aa and f3bb are each text fields that I need to clear after a sumbit.

Snippet 1

var target=document.getElementById('f3aa');
target.value='';
var target=document.getElementById('f3bb');
target.value='';

Snippet 2

o1('f3aa')=o1('f3bb')='';

Snippet 3

function  o1(a)
  {
  document.getElementById(a);
  }

Upvotes: 0

Views: 99

Answers (4)

Tom
Tom

Reputation: 9167

I think it's illegal to use var to declare a variable more than once in the same scope.

This code is bad:

var test = true;
var test = false;

This code is good:

var test = true;
    test = false; // <-- no "var" keyword here

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 186083

X('f3aa').value = X('f3bb').value = '';

where X is your query-by-ID implementation.

Live demo: http://jsfiddle.net/zmr29/

(I wrote a X function in my demo, but I assume that you either use a library or have some other shorthand for DOM queries.)

Upvotes: 1

Amber
Amber

Reputation: 527378

You forgot to include the attribute names from your first snippet in your second:

document.getElementById('f3aa').value='';
document.getElementById('f3bb').value='';

(Note that this isn't really an "optimization" - there will be no noticeable difference in how quickly the two snippets run. Use whichever is more readable.)

Upvotes: 3

James Allardice
James Allardice

Reputation: 166041

Assuming I've understood your question correctly, you were nearly there:

document.getElementById('f3aa').value = '';
document.getElementById('f3bb').value = '';

In your snippet 2, you are trying to assign an empty string to a DOM element, rather than the value property of that element.

In snippet 1, you assign a DOM element to the target variable, and then assign an empty string to the value property of the target variable. As target contains a DOM element, you assign that string to the value property of that element, which is equivalent to the code I have shown above.

Upvotes: 4

Related Questions