创建后选择文本字段

时间:2015-04-11 17:58:08

标签: javascript html

我有一个JavaScript代码,通过单击按钮向页面添加新的文本字段。问题是,每次添加新文本字段时都不会自动选中,因此我可以立即点击+键入(而不是单击,然后单击文本字段,然后键入,然后再次单击按钮添加新文本字段)。

这是添加元素的.js:

var counter = 1;
var limit = 65;
var divcounter = 1;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('tr');
          newdiv.className = "spaceUnder";
          newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}

我已经完成了一些谷歌搜索,但由于英语不是我的母语,因此我很难弄清楚应该用什么谷歌来解决这个问题。

3 个答案:

答案 0 :(得分:2)

您可以使用focus()来关注元素。在else中的addInput()末尾添加:

var inputs = document.getElementsByName('namefield');
inputs[inputs.length-1].focus();

jsfiddle example

答案 1 :(得分:1)

虽然您已经接受了答案,但我建议您对初始JavaScript进行一些更改,不过下面的演示会对您的HTML结构做出一些猜测;希望JavaScript仍然适用。

因此,假设以下HTML大致相似(虽然当变量包含newdiv元素时,为什么变量为<tr>有点令人困惑):

<div>
  <button id="demo">Add a new row</button>
  <table id="container">
    <tbody>
      <tr>
        <td>Nimi 1</td>
        <td>
          <input type="text" name="namefield" class="field" />
        </td>
      </tr>
    </tbody>
  </table>
</div>

user3760780's answer所述,您可以在最后focus()元素上使用<input>方法:

var counter = 1;
var limit = 65;
var divcounter = 1;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('tr');
          newdiv.className = "spaceUnder";
          newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
    // querySelector('input') finds the first element matching
    // the CSS selector passed to the method (here: 'input')
    // contained within the node to which the method is chained
    // (here the 'newdiv' node); in this instance there is only
    // one <input> so it's the right one (and from a UI perspective
    // it's probably the first <input> in the <tr> you'd want to
    // focus):
    newdiv.querySelector('input').focus();
     }
}

var counter = 1;
var limit = 5; // lowered for demo purposes
var divcounter = 1;

function addInput(divName) {
  if (counter == limit) {
    alert("You have reached the limit of adding " + counter + " inputs");
  } else {
    var newdiv = document.createElement('tr');
    newdiv.className = "spaceUnder";
    newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";
    document.getElementById(divName).appendChild(newdiv);
    counter++;
    newdiv.querySelector('input').focus();
  }
}

document.getElementById('demo').addEventListener('click', function(e) {
  addInput(this.nextElementSibling.id);
});
<div>
  <button id="demo">Add a new row</button>
  <table id="container">
    <tbody>
      <tr>
        <td>Nimi 1</td>
        <td>
          <input type="text" name="namefield" class="field" />
        </td>
      </tr>
    </tbody>
  </table>
</div>

尽管如此,虽然上述方法有效,但我建议进行一些修改:

function addInput(event) {
  // cancels the default action of the clicked element
  // to prevent form submission (if it's a <button> within a
  // <form>, or navigating to a new page (if it's an <a> element:
  event.preventDefault();

  // this approach finds the next element-sibling of the
  // clicked <button>, in this case the <table>:
  var self = this.nextElementSibling,
    // initialises the counter variable by finding
    // the number of <tr> elements held in the 'rows'
    // property of the <table>:
    counter = self.rows.length,
    // initialises the limit by looking at the custom
    // data-maxrows attribute of the <table> itself
    // (these approaches reduce the reliance on potentially
    // global variables) and uses parseInt() to convert
    // that string into a number:
    limit = parseInt(self.dataset.maxrows, 10);

  if (counter == limit) {
    alert("You have reached the limit of adding " + counter + " inputs");
  } else {
    var newdiv = document.createElement('tr');
    newdiv.className = "spaceUnder";
    newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";

    // appending the newly-created <tr> to the <table>:
    self.appendChild(newdiv);

    // finding the <input> elment within the created <tr>
    // and focusing it:
    newdiv.querySelector('input').focus();
  }
}

// binds the addInput function (note the lack of parentheses) as
// the click event-handler for the element with the id of 'demo':
document.getElementById('demo').addEventListener('click', addInput);

function addInput(event) {
  event.preventDefault();

  var self = this.nextElementSibling,
    counter = self.rows.length,
    limit = parseInt(self.dataset.maxrows, 10);

  if (counter == limit) {
    alert("You have reached the limit of adding " + counter + " inputs");
  } else {
    var newdiv = document.createElement('tr');
    newdiv.className = "spaceUnder";
    newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";

    self.appendChild(newdiv);
    newdiv.querySelector('input').focus();
  }
}

document.getElementById('demo').addEventListener('click', addInput);
<div>
  <button id="demo">Add a new row</button>
  <table id="container" data-maxrows="5">
    <tbody>
      <tr>
        <td>Nimi 1</td>
        <td>
          <input type="text" name="namefield" class="field" />
        </td>
      </tr>
    </tbody>
  </table>
</div>

并显示一种方法 - 与上述类似 - 可以找到与<table>在同一父级中保留的<button>

function addInput(event) {
  event.preventDefault();

  // this is the only change, moving from the <button> to
  // its parentNode, to find the (first) element matching
  // the CSS selector:
  var self = this.parentNode.querySelector('table'),
    counter = self.rows.length,
    limit = parseInt(self.dataset.maxrows, 10);

  if (counter == limit) {
    alert("You have reached the limit of adding " + counter + " inputs");
  } else {
    var newdiv = document.createElement('tr');
    newdiv.className = "spaceUnder";
    newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";

    self.appendChild(newdiv);
    newdiv.querySelector('input').focus();
  }
}

document.getElementById('demo').addEventListener('click', addInput);

function addInput(event) {
  event.preventDefault();

  var self = this.parentNode.querySelector('table'),
    counter = self.rows.length,
    limit = parseInt(self.dataset.maxrows, 10);

  if (counter == limit) {
    alert("You have reached the limit of adding " + counter + " inputs");
  } else {
    var newdiv = document.createElement('tr');
    newdiv.className = "spaceUnder";
    newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";

    self.appendChild(newdiv);
    newdiv.querySelector('input').focus();
  }
}

document.getElementById('demo').addEventListener('click', addInput);
button {
  display: block;
}

code {
  background-color: #eee;
  padding: 0 0.4em;
}
<div>
  <button id="demo">Add a new row</button>
  <em>An arbitrary number of elements can exist here</em>
  <p>This is because here, the JavaScript looks to the <code>parentNode</code> of the <code>&lt;button&gt;</code> to find the <code>&lt;table&gt;</code> element</p>
  <table id="container" data-maxrows="5">
    <tbody>
      <tr>
        <td>Nimi 1</td>
        <td>
          <input type="text" name="namefield" class="field" />
        </td>
      </tr>
    </tbody>
  </table>
</div>

最后,一种方法 - 再次 - 与上述类似,并在data-*元素上使用另一个自定义data-tableid属性(此处为<button>):

  <button id="demo" data-tableid="container">Add a new row</button>

给予JavaScript:

function addInput(event) {
  event.preventDefault();

  // finding the element in the document whose id is equal
  // to the string held within the 'data-tableid' attribute:
  var self = document.getElementById(this.dataset.tableid),
    counter = self.rows.length,
    limit = parseInt(self.dataset.maxrows, 10);

  if (counter == limit) {
    alert("You have reached the limit of adding " + counter + " inputs");
  } else {
    var newdiv = document.createElement('tr');
    newdiv.className = "spaceUnder";
    newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";

    self.appendChild(newdiv);
    newdiv.querySelector('input').focus();
  }
}

document.getElementById('demo').addEventListener('click', addInput);

function addInput(event) {
  event.preventDefault();

  var self = document.getElementById(this.dataset.tableid),
    counter = self.rows.length,
    limit = parseInt(self.dataset.maxrows, 10);

  if (counter == limit) {
    alert("You have reached the limit of adding " + counter + " inputs");
  } else {
    var newdiv = document.createElement('tr');
    newdiv.className = "spaceUnder";
    newdiv.innerHTML = "<td>Nimi " + (counter + 1) + "</td> <td><input type='text' name='namefield' class='field'> </td>";

    self.appendChild(newdiv);
    newdiv.querySelector('input').focus();
  }
}

document.getElementById('demo').addEventListener('click', addInput);
button {
  display: block;
}
div {
  border: 2px solid #000;
  margin: 0 auto 1em auto;
}
<div>
  <button id="demo" data-tableid="container">Add a new row</button>
</div>
<div>
  <table id="container" data-maxrows="5">
    <tbody>
      <tr>
        <td>Nimi 1</td>
        <td>
          <input type="text" name="namefield" class="field" />
        </td>
      </tr>
    </tbody>
  </table>
</div>

参考文献:

答案 2 :(得分:0)

您可以在计数器中输入您的输入ID,然后按照以下方式解决:

document.getElementById("input1").focus();