0

For one reason or other ( I'm not going to go into why here) I need to use javascript to get the values of 12 hidden input fields and set a variable for each value.

I am not sure what the best approach for this would be. I'd like to be able to get the values and if they are not created i.e. the input fields are not there then id like to generate an error.

Would using a try / catch be good for this or should I simply be using typeof to check the variables have been created?

would putting them in an array as well so i can loop through to check their existance be a good idea?

thanks

4

3 に答える 3

2

This is the easy way of doing it. try-catch is rather heavy. Also, where would you throw the error to? Instead of unwinding your flow on error, collect your errors into a well structured response. That way if your first one is missing, but the other X are not, then you still get some work done.

if ( typeof( something ) !== "undefined" ) { doStuff(); }

Otherwise, I'd need more information to help you with your question.

于 2012-04-10T20:01:19.227 に答える
0
if(document.getElementById("someID")){
// add the value since the input exists
}
else{
// skip or use default - and inform if need be
}

Example implementation: http://jsfiddle.net/zVz6h/1/

Code:

 function getValueArray(idArray){
var valArray = [];
for(var i=0;i<idArray.length;i++){    
    if(document.getElementById(idArray[i])){
    valArray.push(document.getElementById(idArray[i]).value);       
    }
    else{
    valArray.push("not defined");
    }
}
    return valArray;

}

var txtIDs = ["txt1","txt2","txt3","txt4","txt5","txt6","txt7","txt8"];


alert(getValueArray(txtIDs));
于 2012-04-10T19:58:50.520 に答える
0

Here's simple function that will check to see that exactly 12 input elements are included on the page. Please provide more information if you need th check that individual input elements are present.

  function SaveInputValues() {

    var inps = document.getElementsByTagName('input');
    if (inps.length !== 12) {
      return alert("There must be exactly 12 input elements. You have included " + inps.length + ".");
    }
    var vals = [];
    for (i = 0; i < inps.length; i++) vals.push(inps[i].value);
    inps = null; // provides closure
  }
于 2012-04-10T20:06:49.223 に答える