I'm new to jQuery and I want to have a input box from a form called "width" and when you type a value (lets say "300") it will instantly update the div "#box" to a width of 300px.
Thank you!
$("#txt1").bind("keypress", function(){
var val = parseInt($(this).val(), 10);
$("#box").css({'width': val + 'px'});
});
keypress fires before the input's value is changed to include the new key. (And of course there are other ways of editing an input box that don't fire keypress.) You can catch the change event, which will fire for everything but not until the field is blurred, or keyup to at least pick up the value just after the key is pressed. If you want to catch every change immediately, you have to poll the value (at least until HTML5 form input events are widely available).// blur is triggered when the focus is lost
$("#my_input_field_id").blur(function() {
var newWidth = $(this).text();
$("#box").width(newWidth); // the width function assumes pixels
// alternately, use .css('width', newWidth);
});
If you want this to work as the user types (so if they type 500, it updates on 5 to 5, 50 when 0 is added, then 500 on the final 0), then bind to the keypress event.