1

Putting together a very basic query builder using or, not and () operators. I have them appending to an input field though I think it would be beneficial to the user if when the brackets operator button was appended to the input field the cursor would be placed (here) ready for the users query.

So far I have:

   // query builder functions
$(function() {
  var queryinput = $( "#query-builder-modal .search-box input.querybuilder" );

  $('#query-builder-modal ul.operators li.or').click(function(){
    queryinput.val( queryinput.val() + "OR" );
    queryinput.focus();
  });

  $('#query-builder-modal ul.operators li.not').click(function(){
    queryinput.val( queryinput.val() + "-" );
    queryinput.focus();
  });

  $('#query-builder-modal ul.operators li.brackets').click(function(){
    queryinput.val( queryinput.val() + "()" );
    queryinput.focus();
  });
});

Can anyone help me plave the cursor between the brackets in the third click function of this sample code?

Thanks in advance

Gray
  • 115,027
  • 24
  • 293
  • 354
Dave Henderson
  • 151
  • 1
  • 1
  • 10
  • To place cursor see, for example (have you even tried Google??? it only took me 5 seconds): http://stackoverflow.com/questions/5755826/set-cursor-position-in-an-input-text-filed or http://stackoverflow.com/questions/2127221/move-cursor-to-the-beginning-of-the-input-field – Mörre Feb 07 '13 at 18:06
  • People will suggest solutions that replace the input's value. Note that these break undo/redo. Look into execCommand for an undo/redo compatible way of making input changes. (it's not just for contenteditable!) – Alex Feb 07 '13 at 18:07

1 Answers1

1

You can try something like this :

$('#query-builder-modal ul.operators li.brackets').click(function(){
    queryinput.val( queryinput.val() + "()" );
    var pos = queryinput.val().length - 1;
    myInput.focus(); /* Seems mandatory for Firefox/Opera */
    queryinput[0].selectionStart = queryinput[0].selectionEnd = pos;
});

jsfiddle example here

EDIT: It seems that for Firefox and Opera, you must first focus() your input but not on Safari and chrome. I updated the code and the jsfiddle.

koopajah
  • 23,792
  • 9
  • 78
  • 104