在HTML表单中更改两个文本输入之间的光标位置

时间:2015-11-15 07:57:34

标签: html forms input cursor caret

我有一个包含2个文本输入字段的简单搜索表单。这是代码;

<div id="mini-search-wrapper">
  <form role="search" action="/" method="get">
     <input type="search" id="s" name="s" class="s-input" required/>
     <input type="hidden" name="post_type" value="artist"/>
     <input type="submit" class="s-submit" value="Şarkıcı Ara"/>
  </form>
  <form role="search" action="/" method="get">
      <input type="search" id="s" name="s" class="s-input" required />
      <input type="hidden" name="post_type" value="lyrics" />
      <input type="submit" class="s-submit pos-center" value="Şarkı Ara"/>
  </form>
</div>

看起来像那样;

Form Image

我的问题是;

打开此表单时,光标的位置从第二个输入框开始。我想更改光标(插入符号)位置,以便当用户单击此表单时,光标的位置将位于第一个输入框中,而不是第二个。

如果HTML表单中有许多inpux文本框,如何选择光标的起始位置?

感谢。

3 个答案:

答案 0 :(得分:0)

尝试将autofocus属性添加到输入中,如下所示:

    <div id="mini-search-wrapper">
  <form role="search" action="/" method="get">
     <input type="search" id="s" name="s" class="s-input" required/>
     <input type="hidden" name="post_type" value="artist"/>
     <input type="submit" class="s-submit" value="Şarkıcı Ara"/>
  </form>
  <form role="search" action="/" method="get">
      <input type="search" id="s" name="s" class="s-input" required autofocus="true"/>
      <input type="hidden" name="post_type" value="lyrics" />
      <input type="submit" class="s-submit pos-center" value="Şarkı Ara"/>
  </form>
</div>

答案 1 :(得分:0)

为您的输入提供唯一ID,并将焦点设置为JQuery's .focus

<div id="mini-search-wrapper">
    <form role="search" action="/" method="get">
        <input type="search" id="s" name="s" class="s-input" required/>
        <input type="hidden" name="post_type" value="artist"/>
        <input type="submit" class="s-submit" value="Şarkıcı Ara"/>
    </form>
    <form role="search" action="/" method="get">
        <input type="search" id="s2" name="s" class="s-input" required autofocus="true"/>
        <input type="hidden" name="post_type" value="lyrics" />
        <input type="submit" class="s-submit pos-center" value="Şarkı Ara"/>
    </form>
</div>

JS:

$('input').click(function(){
    $('#s').focus();
});

答案 2 :(得分:0)

专注于onload:

window.onload=function() {
  document.getElementsByName("s")[0].focus(); // focus first of this name
}

如果您有相同名称的字段,则替代:

  <form role="search" action="/" method="get">
     <input type="search" id="s" name="s" class="s-input" required/>
     <input type="hidden" name="post_type" value="artist"/>
     <input type="submit" class="s-submit" value="Şarkıcı Ara" 
      onclick="this.form.post_type.value='artist'"/>
     <input type="submit" class="s-submit pos-center" value="Şarkı Ara" 
      onclick="this.form.post_type.value='lyrics'"/>
  </form>

但为什么有两种形式?

function find(obj, param, pos) {
   var out = [];
   for (var p in obj) {
     if (obj[p][pos] === param) out.push(p);
   }
   return out;
}

find(colors, '#999999', 0); // ['second']
find(colors, '#999999', 1); // ['first']