开发者

Get all input type password

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 ass开发者_开发知识库ign an event on text changed.

How can I do this?

Thanks


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>
          }    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜