Hank Hank - 10 days ago 7
jQuery Question

Select specific text within an INPUT text field on change with JQuery Trigger

I have this input text field and I would like to select (highlight really) the first 3 characters, when it changes.

<input class="descriptions" value="temp text"/>


And I have this script monitoring the onChange event...

$(document).on('change','.descriptions',function(event) {
event.target.focus();
event.target.setSelectionRange(0,3);
});


When I manually change the text in this input text field, the script works. However, when I trigger the event using Jquery and a link, it does NOT:

<a onMouseDown="javascript:$('.descriptions').val('test text');
$('.descriptions').trigger('change');">update input</a>


I thought they were virtually the same! I did notice that if I log the
event.target
to the console, the output is not quite exactly the same.

Any thoughts?

Answer

You didn't show all your code together, but this code does what you are after:

$('.descriptions').on('change', function(event){
  event.target.focus();
  event.target.setSelectionRange(0,3);
});

$('#btn').on("click", function(){
  $('.descriptions').trigger("change");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="descriptions">
<input type="button" id="btn" value="Trigger Change">