Replace text from <option> to <input>

Replace text from <option> to <input>

本文关键字:gt lt to input text option from Replace      更新时间:2023-09-26

我想使用"ondblclick"事件和jQuery库将文本从选定替换为另一个。下面是我的简单html代码:

<input id="text_inp" >
<select id="info" ondblclick="PutValue()" >
   <option val="1">1</option>
   <option val="2">2</option>
   <option val="3">3</option>
</select>
jQuery代码:
    function PutValue(){
        var _val = $(this).text();
        $("#text_inp").val(_val);
    }

和控制台错误:

未捕获的TypeError: Cannot call method 'toLowerCase' of undefined

您可以使用.val()

获取选项的值
function PutValue(){
    var _val = $(this).val();
    $("#text_inp").val(_val);
}

顺便说一句,在Safari中,不能双击选择。

使用像ondblclick这样的内联事件处理程序是不好的做法,最好这样做:

$("#info").dblclick(function(){ 
        var _val = $(this).val();
        $("#text_inp").val(_val);
});

Working fiddle: http://jsfiddle.net/m2xRX/1/(on change event)

如果你要使用内联方法你必须传递你点击的元素

<input id="text_inp" >
<select id="info" ondblclick="PutValue(this)" > <!-- put this as a parameter -->
   <option val="1">1</option>
   <option val="2">2</option>
   <option val="3">3</option>
</select>

那么在你的函数中你会得到它

function PutValue(t) { // here t is the element / this
    var _val = $(t).val(); // to get the currently selected value use val
    $("#text_inp").val(_val);
}

因为你使用的是jQuery所以你应该使用jQuery的方式

$('#info').dblclick(function(){
   var _val = $(this).val();
   $("#text_inp").val(_val);
});

你应该明确定义输入的类型:

替换:

<input id="text_inp" >
与这个:

<input id="text_inp" type="text" />