Search code examples
javascripthtmltextbox

How to update the textbox value based on other textbox using JavaScript?


I have three input text boxes in my form.

First one is teacher, second one is grade. Now I've the third input text box, where i need to update the value dynamically from these two values as "(teacher)'s (X) class" using JavaScript.

Can anyone help me in writing the code? Thanks in advance.

here is the jquery code:

<script type="text/javascript">
  $(document).ready(function(){
    $('#both').value($('#teacher').val() + "'s " + $('#grade').val());
});

  </script>

and my input tags are:

<input type="text" name="teacher_name" id="teacher" value="" style="background:#f7f6f2 url(../images/input_02.png) repeat left top;border: 0px;width: 250px;height: 10px;padding: 10px;display: block;">
<input type="text" name="teacher_name" id="grade" value="" style="background:#f7f6f2 url(../images/input_02.png) repeat left top;border: 0px;width: 250px;height: 10px;padding: 10px;display: block;">
<input type="text" name="teacher_name" id="both" value="" style="background:#f7f6f2 url(../images/input_02.png) repeat left top;border: 0px;width: 250px;height: 10px;padding: 10px;display: block;">

what are the things i need to add to make my third input field to get updated.


Solution

  • Use the onChange event that is triggered when an input content changes or the onBlur event that is triggered when an input lost the focus:

    function UpdateInfo()
    {
      var teacher = document.getElementById('teacher').val();
      var grade = document.getElementById('grade').val();
      var info = teacher + '\'s '+ grade + ' class';
      document.getElementById('info').value = info;
    }
    
    /* Solution 1 (onChange) */
    <input id="teacher" type="text" onChange="UpdateInfo();" />
    <input id="grade" type="text" onChange="UpdateInfo();" />
    <input id="info" type="text" />
    
    /* Solution 2 (onBlur) */
    <input id="teacher" type="text" onBlur="UpdateInfo();" />
    <input id="grade" type="text" onBlur="UpdateInfo();" />
    <input id="info" type="text" />
    

    Or using jQuery, you can bind the event at document.ready event:

    $(document).ready(function()
    {
        /*
        * binding onChange event here
        * you can replace .change with .blur
        */
        $('#teacher').change(UpdateInfo);
        $('#grade').change(UpdateInfo);
    });
    
       function UpdateInfo()
       {
         var teacher = $('#teacher').val();
         var grade = $('#grade').val();
         var info = teacher + '\'s '+ grade + ' class';
         $('#info').val(info);
       }
    
    <input id="teacher" type="text" />
    <input id="grade" type="text" />
    <input id="info" type="text" />
    

    DEMO