tags:

views:

38

answers:

4

Hello,

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!

A: 

One way:

jQuery("#input").change( function(){ 
    jQuery("#box").css("width", jQuery("#input").val()); });

Basically when the input value changes, set the css attribute of #box to use the input width.

Justin Ethier
A: 
$("textbox").blur(function() {
    $("#box").css("width") = $("textbox").val();
});
Dustin Laine
A: 
// 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.

justkt
+1  A: 
$("#txt1").bind("keypress", function(){
    var val = parseInt($(this).val(), 10);
    $("#box").css({'width': val + 'px'});
});
rahul
Curiosity question - why parseInt? Just to ensure type coersion?
justkt
Any way to make this script work as the value is being entered? I have a slider connected to the width input box so when the slider changed value, I want the #box to change at the same time..
Chad Whitaker
@Chat Whitaker - This answer should do that. It is binding to keypress. You can also bind via $("#txt1").keypress(function() {...}); The jQuery docs jave more info http://api.jquery.com/keypress/.
justkt
Note `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).
bobince