admin管理员组

文章数量:1183083

I'm new in javascript. I want to get all input type password on my html page.

I know that there is a way to do this kind off things using Javascript, but I don't know how.

Then, with each one, I want to assign an event on text changed.

How can I do this?

Thanks

I'm new in javascript. I want to get all input type password on my html page.

I know that there is a way to do this kind off things using Javascript, but I don't know how.

Then, with each one, I want to assign an event on text changed.

How can I do this?

Thanks

Share Improve this question edited Feb 19, 2010 at 17:41 Chris 2,9912 gold badges33 silver badges48 bronze badges asked Feb 19, 2010 at 17:24 rpfrpf 3,71210 gold badges40 silver badges48 bronze badges 2
  • What do you mean by “password input types”? – Gumbo Commented Feb 19, 2010 at 17:26
  • 1 <input type="password" name="passwd"> – rpf Commented Feb 19, 2010 at 17:28
Add a comment  | 

5 Answers 5

Reset to default 13

I presume you mean

<input type="password">

If so, you can try a function like this:

function getPwdInputs() {
  var ary = [];
  var inputs = document.getElementsByTagName("input");
  for (var i=0; i<inputs.length; i++) {
    if (inputs[i].type.toLowerCase() === "password") {
      ary.push(inputs[i]);
    }
  }
  return ary;
}

I hope Robusto doesn't mind me extending his solution a bit for a solution that will perform better on the modern browsers. Chrome, Safari, IE8 and Firefox all support querySelectorAll, so it seems more appropriate to use that if it's available.

function getPwdInputs() 
{ 
  // If querySelectorAll is supported, just use that!
  if (document.querySelectorAll)
    return document.querySelectorAll("input[type='password']"); 

  // If not, use Robusto's solution
  var ary = []; 
  var inputs = document.getElementsByTagName("input"); 
  for (var i=0; i<inputs.length; i++) { 
    if (inputs[i].type.toLowerCase() === "password") { 
      ary.push(inputs[i]); 
    } 
  } 
  return ary; 
} 

NB. It shouldn't be a problem but it might be worth noting that querySelectorAll will return a collection, whereas the fallback method will return an array. Still not a big deal, they both have the length property and there members are accessed the same way.

You can do this easily using jQuery:

jQuery("input[type='password']").change( function() {
  // check input ($(this).val()) for validity here
});

jQuery is your friend here. With jQuery, it's as easy as using the selector:

$('input[type=password]');

and then binding a changed listener to each:

$('input[type=password]').change(function ()
{
    // do whatever here
});

This is untested, but something like this should work:

var allElem = document.getElementsByTagName(’input’)

for (i=0; i < allElem.length; i++) {

          if (allElem[i].getAttribute(’type’)==‘password’) {

              allElem[i].onchange = //<your onchange function>
          }    
}

本文标签: javascriptGet all input type passwordStack Overflow