0

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!

4 Answers 4

1
$("#txt1").bind("keypress", function(){
    var val = parseInt($(this).val(), 10);
    $("#box").css({'width': val + 'px'});
});
Sign up to request clarification or add additional context in comments.

4 Comments

Curiosity question - why parseInt? Just to ensure type coersion?
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..
@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 api.jquery.com/keypress.
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).
0

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.

Comments

0
$("textbox").blur(function() {
    $("#box").css("width") = $("textbox").val();
});

Comments

0
// 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.