ruffy
ruffy

Reputation: 9

An HTML Input Field I Fail to Reset via javascript

I do not use jQuery, unless this will force me.

My apparently simple HTML document has a div with 3 inputs, the 3rd of which, for some reason, I fail to reset. My cleaned-up-for-display code appears below:

<div>
 <label>LIMIT 1
  <select id="limit1"> 
   <option value="1">Choice1</option>
   <option value="2">Choice2</option>
  </select>
 </label>
 <label>LIMIT 2
  <select id="limit2">
   <option value="1">Choice1</option>
   <option value="2">Choice2</option>
  </select>
 </label>

 <label>ENTER A VALUE
  <input type="text" id=“parm2” value="20" size="3" maxlength="4">
 </label>
</div>

Here’s my validation and reset code:

var limit1 = document.getElementById("limit1");
var limit2 = document.getElementById("limit2");
if (limit2.value < limit1.value) {
 alert("ERROR: 1st must be less than 2nd");
 limit1.value = 1; 
 limit2.value = 2;
 return false;
}  // Above resets of select options works!
var uValue = document.getElementById(“parm2”).value;
if (isNaN(uValue)) {
 uValue.value = "20";   // This reset fails!
 return false;
}

Thanks for your help.

Upvotes: 0

Views: 45

Answers (2)

tcigrand
tcigrand

Reputation: 2397

You're accessing .value twice

var parm2 = document.getElementById(“parm2”);
if (isNaN(parm2.value)) {
 parm2.value = "20";   // This reset no longer fails!
 return false;
}

Upvotes: 0

rlemon
rlemon

Reputation: 17667

var uValue = document.getElementById(“parm2”).value;

selects the value of the element, not the element. so "123".value doesn't really make sense, store the element if you want to reset its value.

var uElement = document.getElementById('parm2');
// later on
uElement.value = 20;

Side Note: property access usually isn't expensive, so storing just the element and accessing the value with .value later on is perfectly acceptable instead of using two variables.

Upvotes: 1

Related Questions