title: Control Cursor Location on Focus in Form Field
body: <p>I have a form with 4 fields. I want the first of the four to have the <code>autofocus</code> and be the first the user fills out. But then, either by tab or mouse or whatever, when the user gets to second field, I want the cursor to end up at the end of the string to start. There is a pre-filled string in that field.</p>
  
  <p>I'm using Django so I have a form widget controlling the attributes. I can get the string to show up and even get the cursor to the end, but this always causes <code>autofocus</code> as well on that second field. I haven't managed to get both.</p>
  
  <p>Here is code I'm using so far:</p>
  
  <p><strong>Django</strong></p>
  
  <pre><code>field = forms.URLField(
      widget = forms.URLInput(
          attrs = {
              'placeholder': 'enter field',
               # call to javascript function - this works
              'onfocus': 'add_string("field_id", "string")',
          } 
      )
  )
  </code></pre>
  
  <p><strong>JavaScript:</strong></p>
  
  <pre><code>// add string to element
  function add_string(id, string) {
      var input = document.getElementById(id);
      input.value = string;
  }
  </code></pre>
  
  <p>I've played around with various JS scripts but to no avail. I then found <a href="https://developer.mozilla.org/en-US/docs/Web/API/Input.setSelectionRange" rel="nofollow"><code>setSelectionRange</code></a> and played around with this like so:</p>
  
  <pre><code>input.setSelectionRange(7, 7)
  </code></pre>
  
  <p>Where 7 would be end of the particular "string" in the <code>onfocus</code> JavaScript function call, but I could't get this to work...</p>
  
  <p>Finally, I played around with some jQuery that looked like this:</p>
  
  <pre><code>// focus after string, no highlight
  $(document).ready(function() {
      var $field = $("#field_id");
      var old_val = $field.val();
      $field.focus().val('').val(old_val);
  });
  </code></pre>
  
  <p>But this did the same thing: brought initial focus to second field and brought cursor to the end.</p>
  
  <p>Any idea how I can do this, get both <code>autofocus</code> on field one but get cursor to jump to end of pre-filled string of field two on it's focus? Might be a nice trick if I knew how to do it.</p>