Search code examples
javascriptonchangelowercasekeyup

javascript lowercase onchange


I hope you can help me with a little problem. I'm not getting anywhere.

If an entry is made in the field post_title, the characters should be copied automatically into the field post_uri. That works.

Now all letters should be lowercase automatically and spaces should be replaced by the - character.

What do I have to do?

  $(function() {
    var $post_title = $('#post_title');
    var $post_uri = $('#post_uri');

    function onChange() {
      $post_uri.val($post_title.val());

    };
    $('#post_title')
      .change(onChange)
      .keyup(onChange);

  }); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form>
  <input type="text" name="post_title" id="post_title">
  <input type="text" name="post_uri" id="post_uri">
</form>


Solution

  • You almost got it. You only need to add toLowerCase and replace function calls on your string.

    $(function() {
        var $post_title = $('#post_title');
        var $post_uri = $('#post_uri');
    
        function onChange() {
          var val = $post_title.val().toLowerCase().replace(/\s/g, "-");     
          $post_uri.val(val);
    
        };
        $('#post_title')
          .change(onChange)
          .keyup(onChange);
    
      });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <form>
      <input type="text" name="post_title" id="post_title">
      <input type="text" name="post_uri" id="post_uri">
    </form>

    EDIT: Just for clarification, this solution does work in any situation where content is modified.

    According to jQuery's Docs:

    .change()

    For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.