2014-09-24 73 views
-5

我有几个input字段(有时被禁用)。当用户点击一个按钮时,我怎样才能得到input字段的id,其中文字选中了呢?jquery获得输入选定文本的ID

Text:<input type="text" id="myID" disabled="disabled" value="Hello World"/> 
<input type="text" id="myID2" value="Hello again"/> 
<input type="button" id="myButton" value="Get Selected Id" name="Get Selected Id"/> 

$("#myButton").click(function(){ 
    alert(/*...how do I get 'myID' or 'myID2' here, depending on which has a selection?...*/); 
}); 

通过 “选择” 我的意思是这样的:

enter image description here

这里的fiddle

不幸的是,我需要支持不只是现代的浏览器,而且IE7和IE8。

回答

1

不知道你想达到什么。

在IE浏览器,你可以成功地做到这一点:

var id = document.selection.createRange().parentElement().id 

像这样:

$("#myButton").on("click", function() { 
    var node = document.selection.createRange().parentElement(); 
    if (node && node.id) { 
    window.console && console.log("node_ " + node.id) 
    } 
}); 

在Chrome中这似乎是棘手。

我有一个解决方案,您可能可以使用。这将打破,如果有具有相同值的多个字段

FIDDLE

$(document).on("mouseup", "input", function() { 
    var node = document.selection ? document.selection.createRange().parentElement() : window.getSelection().focusNode.parentNode; 
    if (!node.id) { 
     var sel = window.getSelection().toString(); 
     $("input").each(function() { 
      if (this.value.indexOf(sel) != -1) { 
       node = this; 
       return false; 
      } 
     }); 
    } 
    window.console && console.log("node:" + node.id) 
}); 
+0

这正是我需要的... 我编辑你的小提琴以示区别几个领域的工作:HTTP:/ /jsfiddle.net/s9ms3eea/13/ 正如你所说,它不适用于Chrome,但IE8就足够了! – Franky 2014-09-24 10:06:16

+0

请仅查看我的IE更新 – mplungjan 2014-09-24 12:33:52