【问题标题】:HTML text input select all content on focus not working in chromeHTML文本输入选择焦点上的所有内容在chrome中不起作用
【发布时间】:2013-04-03 13:25:09
【问题描述】:

我有一堆文本输入,每个都在这样的表格单元格中:

<td class="tdTextInput">
    <input type="text" value="0" name="txt1_9_4_2" id="txt1_9_4_2" class="input-supermini">
</td>

每当用户点击单元格或输入时,它必须自动选择输入内的所有内容(有点像电子表格编辑器)。

所以这是迄今为止仅在可信赖的旧 Firefox 中成功实现它的脚本。

    //focus the textbox on td click
    $('.tdTextInput').mousedown(function ()
    {
        $(this).find('input').first().focus();
    });

    //select all text on focus
    $('.tdTextInput input').focus(function ()
    {
        //the data-selected attribute is used to prevent the 
        // autoselection to happen more than once per cell so that
        // two consecutive  clicks will allow the user to pinpoint the
        // cursor to a specific position
        var isSelected = $(this).attr('data-selected') == 'true';
        if (!isSelected) {
            $('input[data-selected]').removeAttr('data-selected');
            $(this).attr('data-selected', 'true');
            $(this).select();
        }
    });

    //prevent non-numeric values from being added
    $('.tdTextInput input').keydown(function (e)
    {
        CommonTools.IsNumeric(e);
    });

CommonTools.IsNumeric 指的是以下内容:-(可能不相关,因为 keydown 功能不是问题。仅将其添加到问题中以确保完整性)

isNumeric = function (e)
{
    if(!(e.which>=48 && e.which<=57)) //numeric values only
            e.preventDefault();
}

为什么这只在 FF 和 IE 中有效,而在 Chrome 中无效?

更新: 我在这里创建了一个小提琴:http://jsfiddle.net/dDc73/,但是它甚至在小提琴中的 FF 或 IE 中也不起作用。

更多信息: 当我单击单元格时,它会选择所有文本,直到我释放鼠标单击。

【问题讨论】:

    标签: javascript jquery html focus


    【解决方案1】:

    参考: Selecting text on focus using jQuery not working in Safari and Chrome

    $(".tdTextInput input").mouseup(function(e){
        e.preventDefault();
    });
    

    这也可能有帮助:

    Select all text on focus using jQuery

    $(".tdTextInput input").live('mouseup', function () {
            $(this).select();
    });
    

    【讨论】:

    • Ineed,你必须像@Muhammad 所说的那样使用 mouseup。制定了一个例子:alturl.com/giwv5
    【解决方案2】:

    让“名字”输入框在页面加载时自动获得焦点:

    <form action="demo_form.asp">
      First name:<input type="text" name="fname" autofocus><br>
      Last name: <input type="text" name="lname"><br>
      <input type="submit">
    </form> 
    

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 2017-09-26
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 2019-04-27
      • 2013-05-13
      相关资源
      最近更新 更多