Alex_B
Alex_B

Reputation: 1661

Can't set width, height of <textarea> using jQuery

I dblclick a paragraph and call a function to dynamically replace it with a textarea so I can edit the paragraph text. I capture the width and height of the paragraph and pass the text and dimensions.

$('article').on('dblclick','p', function(ev) { 
    var text = $(this).text();              // save the text    
    var dim = $(this).css( ["width", "height"]); 
    $(this)                             // for the p element...
        .empty()                        // wipe the p and it's text 
        .append(newTAInput(this, text, dim));       // append edited text
});

This function creates the textarea, sets it's text and dimensions, and returns the changed text when you click outside the textarea.

function newTAInput(target, text, dim) {
    var input = $('<textarea ></textarea>')
        .val(text)
        .attr(dim)
        .css('font-family', 'Times New Roman')
        .css('font-size', '16.37px')
        .bind('blur', function() {
            var value = $(this).val();
            $(target).html(value);
        });
    return input;
}

It's not happening, even though dim is a plain object with the proper keys and values in the .attr() function.

See the full code in jsfiddle: http://jsfiddle.net/tenrab/dYR4M/

Upvotes: 0

Views: 2081

Answers (3)

dcodesmith
dcodesmith

Reputation: 9614

This...

function newTAInput(target, text, dim) {
        console.log(dim);
        var input = $('<textarea ></textarea>')
            .val(text)
            .css({'font-family': 'Times New Roman',
                  'font-size': '16.37px',
                  'width': dim.width,
                  'height': dim.height
            })
            .bind('blur', function () {
            var value = $(this).val();
            $(target).html(value);
        });
        return input;
    }

Edited: refactored, no need to chain 4 'css' methods onto each other, just pass attributes as an object

Upvotes: 1

Musa
Musa

Reputation: 97672

<textarea>s don't have width and height attributes, use css to set the width and height.

var input = $('<textarea ></textarea>')
    .css(dim)

http://jsfiddle.net/dYR4M/4/

Upvotes: 1

bipen
bipen

Reputation: 36531

use .css()..instead of attr().

function newTAInput(target, text, dim) {
console.log(dim);
var input = $('<textarea ></textarea>')
    .css(dim) //<--here
    .val(text)
    .css('font-family', 'Times New Roman')
    .css('font-size', '16.37px')
    .bind('blur', function () {
    var value = $(this).val();
    $(target).html(value);
});
return input;
}

fiddle

Upvotes: 0

Related Questions