jquery get id of input selected text

Not sure what you are trying to achieve.

In IE you can successfully do this:

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

Like this:

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

in Chrome it seems to be trickier.

I have a solution which you may be able to use. It will break if there are more than one field with the same value

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)
});

Leave a Comment