Search code examples
javascriptformscakephp

Change input value based on another input's value


I want to have a form which will have a couple of inputs, for example: name and url.

When the user enters their name, I'd like the url input to automatically have as a default their name with an underscore between words. So if they type in as their name pedro kinkybottom then automatically set as the default in the url input would be pedro_kinkybottom.

I'm using cakephp if anyone happens to know a particularly cakey way to do this that'd be cool but otherwise any help at all would be most welcome.


Solution

  • You'd probably want to do this in JavaScript and not in PHP. Even though you may be more familiar with the latter, the user experience would be better with the former and the overall design simpler (since the page wouldn't need to refresh).

    You essentially need to do two things:

    1. Set the value of an input in response to an event on another input.
    2. Replace space characters with underscore characters.

    For the second part, take a look at JavaScript's replace function. It's pretty robust and lets you do a lot of string manipulation. Definitely worth trying it out yourself.

    For the first part, here's an example with jQuery:

    $('#inputName').change(function() {
      $('#inputURL').val($('#inputName').val());
    });
    

    This would set the value of inputURL to the value of inputName any time the value of inputName changes. For the string replacement, you'd modify it similar to this:

    $('#inputName').change(function() {
      $('#inputURL').val($('#inputName').val().replace(' ', '_'));
    });
    

    Note that the change event will be fired when the control loses focus. If you want to to happen as-you-type then try the keyup event. There are other events as well.