Search code examples
javascriptjqueryvariablesinputkeyup

jQuery - How to retrieve input values when Typing?


When a user fills out my form, I would like to create a special code.

The code would be the first two letters of each input (input#one, input#two, input#three).

While typing, the "code" would be stored in a variable and set as a value for input#four.

This is my HTML:

<form id="gravity">
    <li>
        <input type="text" id="one"/>
    </li>
    <li>
        <input type="text" id="two" />
    </li>
    <li>
        <input type="email" id="three" />
    </li>
    <li>
        <label>Code:</lable>
        <input type="text" id="four" />
    </li>

</form>

And this is my jQuery:

$(function() {

 $( "input#one" ).keyup(function() {
    var el1 = $( this ).val().substr(0,2);
}).keyup();

 $( "input#two" ).keyup(function() {
    var el2 = $( this ).val().substr(0,2);
}).keyup();

 $( "input#three" ).keyup(function() {
    var el3 = $( this ).val().substr(0,2);
}).keyup();

var el4 = el1 + el2 + el3;
$("input#four").attr('value', el4);


});

So if a user were to enter first name (input#one): William, last name (input#two): Tell and Email (input#three): williamtell@gmail.com -> the code would be: witewi

Where am I going wrong with my jQuery?

Your input is much appreciated! Fiddle


Solution

  • When you declare var the variable only exists in the container it is declared, so el1 etc will cease to exist after the function is finished.

    Also, this bit of code is only ever run after the page has loaded...

    var el4 = el1 + el2 + el3;
    $("input#four").attr('value', el4);
    

    What you need to do is rebuild it each time by putting it in a function and calling the function...

    $(function() {
      var el1 = "", el2 = "", el3 = "";
    
      $( "input#one" ).keyup(function() {
        el1 = $( this ).val().substr(0,2);
        buildel4();
      });
     
      $( "input#two" ).keyup(function() {
        el2 = $( this ).val().substr(0,2);
        buildel4();
      });
    
      $( "input#three" ).keyup(function() {
        el3 = $( this ).val().substr(0,2);
        buildel4();
      });
      
      function buildel4() {
        var el4 = el1 + el2 + el3;
        $("input#four").attr('value', el4);
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <form id="gravity">
        <li>
            <input type="text" id="one"/>
        </li>
        <li>
            <input type="text" id="two" />
        </li>
        <li>
            <input type="email" id="three" />
        </li>
        <li>
            <label>Code:</lable>
            <input type="text" id="four" />
        </li>
    
    </form>

    Here is a Live Demo using jsfiddle

    (Also, you don't need the 2nd call to .keyup(); on each one)