Home > database >  How do I control input behavior over many input elements with different name attributes?
How do I control input behavior over many input elements with different name attributes?

Time:09-26

My JavaScript skills are a bit green, but I am trying to improve the following:

I am currently using a script to effect a single input element in a form by the input name attribute:

HTML:

<input type="number" class="form-control" 
     id="floatingInputGrid" 
     name="hoursstagingbudget" value="0" >
<label for="floatingInputGrid">Hours Staging Budget</label>

JavaScript:

var nameElement = document.forms.inputform.hoursstagingbudget

  function nameFocus(e) {
    var element = e.target || window.event.srcElement;
    if ( element.value == "0" )
      element.value = "";
  }

  function nameBlur(e) {
    var element = e.target || window.event.srcElement;
    if ( element.value === "" )
      element.value = "0";
  }
  
  if ( nameElement.addEventListener ) {
    nameElement.addEventListener("focus", nameFocus, false);
    nameElement.addEventListener("blur", nameBlur, false);
  } else if ( nameElement.attachEvent ) {
    nameElement.attachEvent("onfocus", nameFocus);
    nameElement.attachEvent("onblur", nameBlur);
  }

I want all the number type inputs to behave this way - I'm using document.form...is there a 'type' method or just the 'name' method to use this?

If not, I was thinking I would use an array of the input names, but I'm not having much luck applying that idea either.

Looking for the smartest way to approach this and expand beyond the one named input in the best DRY approach possible. Thanks in advance.

CodePudding user response:

I would use DOM (Document Object Model) to get all inputs and attach the event listener (using document.forms etc. isn't recommended) :

var inputs = document.getElementById("yourformidhere").getElementsByTagName("input");
for(var i = 0; i < inputs.length; i  ) {
   var currentElement = inputs[i];
   if(currentElement.addEventListener) {...};
   else if (currentElement.attachEvent) {...};
}

Here's a tutorial on how to use DOM if you're interested

CodePudding user response:

The best thing would probably be to use document.querySelectorAll (docs). This will return you a list (not an array) of all the elements that match the css selector you pass in. Assuming all your inputs have the class="form-control" this code should do what you described.

  const inputElements = document.querySelectorAll(".form-control");
  for(let i = 0; i < inputElements.length; i  ){
      if ( nameElement.addEventListener ) {
          inputElements[i].addEventListener("focus", nameFocus, false);
          inputElements[i].addEventListener("blur", nameBlur, false);
      } else if ( nameElement.attachEvent ) {
          inputElements[i].attachEvent("onfocus", nameFocus);
          inputElements[i].attachEvent("onblur", nameBlur);
      }
   }   
  • Related