views:

602

answers:

3

I would like a span to update when a value is entered into a text field using jquery. My form field has a text box with the name "userinput" and i have a span with the id "inputval". Any help would be greatly appreciated.

+1  A: 

Try this. Be sure that you understand what is going on here.

// when the DOM is loaded:
$(document).ready(function() {
    // find the input element with name == 'userinput'
    // register an 'keydown' event handler
    $("input[name='userinput']").keydown(function() {
        // find the element with id == 'inputval'
        // fill it with text that matches the input elements value
        $('#inputval').text(this.value);
    }
}
TM
+4  A: 

UPDATE: although you marked this as the correct answer, note that you should use the keyup event rather than the change event or the keydown

$(document).ready(function() {
    $('input[name=userinput]').keyup(function() {
      $('#inputval').text($(this).val());
    });
    });
Marwan Aouida
I guess great minds think alike! Or maybe it was just really trivial?
TM
:) it is not a complex problem
Marwan Aouida
A: 
$(function() {
    $("input[name=userinput]").keydown(
      function() {
        $('#inputval').text(this.value);
      }
     )
})
eKek0
it is the correct answer, he should use the keydown event rather than the change event.but you should not reselect he input element again as TM said
Marwan Aouida
This won't actually work. `text()` will always return an empty string since the input has no inner text, it only has a value. Also, there is no need to find the element again, since you already have a reference to it in the event handler (this)
TM
thank guys, I corrected my answer based on your comments
eKek0