abby
abby

Reputation: 678

generate and show password

i have a form with a html table. my table is :

<table>
<tr>
  <td>
    <input type="text" name="password[]"/>
  </td>
  <td>
    <input type="radio" value="1" onchange="generatePassword()"/>Short<br />
    <input type="radio" value="2" onchange="generatePassword()"/>Medium<br />
    <input type="radio" value="3" onchange="generatePassword()" />Long
</td>
<tr>
</table>

In my code, there is a button at the bottom and when it is clicked, it clones the table row. So, i dont know number of rows or number of password fields in my table. Because of clonning the row, i could not give id to my password field. So, I couldnt decide how to reach a text box without id. But i need to show my generated password in password field.

Upvotes: 0

Views: 142

Answers (3)

Zword
Zword

Reputation: 6793

Use .getElementsByName instead of id:

document.getElementsByName('password[]')[0].value="anyvalue";

Fiddle1

OR

Use .getElementsByTagName

document.getElementsByTagName('input')[0].value="anyvalue";

Fiddle2


New fiddle in response to comment

Upvotes: 1

alexP
alexP

Reputation: 3765

You could use Classes instead of an ID.

HTML

<input type="text" class="myPassword" value="test" name="password[]" />
<input type="text" class="myPassword" value="test" name="password[]" />
<input type="text" class="myPassword" value="test" name="password[]" />

JS

var passwords = document.getElementsByClassName('myPassword') || document.querySelectorAll('myPassword'); //querySelectorAll for IE <= 8

 for (var i = 0; i < passwords.length; i++) {
    console.log(passwords[i].value);
 }

Upvotes: 1

dfsq
dfsq

Reputation: 193271

What you can do. You can find an input field from generatePassword like this:

function generatePassword(inp) {
    var textbox = inp.parentNode.parentNode.cells[0].getElementsByTagName('input')[0];
    textbox.value = 'password ' + inp.value;
}

You would also change markup a little. Add name attribute to radio buttons and reference current input with this:

<input type="radio" name="generate" onchange="generatePassword(this)" value="1" />

Demo: http://jsfiddle.net/BHb3N/

Upvotes: 1

Related Questions