0

I have a collection of textareas I am getting using a selector. I am then iterating through and trying to set the max width for each based on its current width(they are not all the same, that is why I am doing it this way). However, I can not access the .css property of the elements in the array, I guess because they are HTMLTextAreaElements? Is there a way to make this work or a better way to approach this?

I can not set the max width statically because this is a generic control that is used in a variety of pages and with a variety of different sizes.

$(function () {
var a = $('.myTextAreaCssClass');
for(var i = 0;i < a.length; i++) {
var w = a[i].css(width);
a[i].css('max-width',w);
}
});
Brendan
  • 1,853
  • 11
  • 18
jas
  • 537
  • 1
  • 7
  • 12

3 Answers3

2

I think you should use $.each. Try this,

$(function () {
   var a = $('.myTextAreaCssClass');
   a.each (function () {
      $(this).css('max-width', $(this).css('width'));
   });
});

or you can make use of css function argument as given below,

$(function () {
   var a = $('.myTextAreaCssClass');
   a.css ('max-width', function () {
      return $(this).css('width');
   });
});

Edit: I just realized this is really just setting the max width to the width I designated in my css file, what I need is the width in pixels – jas

Try this,

$(function () {
   var a = $('.myTextAreaCssClass');
   a.css ('max-width', function () {
      return $(this).width(); //returns computed width
   });
});

Note: there are different version of width() function so use accordingly. See: https://stackoverflow.com/a/10018686/297641

Community
  • 1
  • 1
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • `.each()` is a much better option in this case. – Ashley Strout May 16 '12 at 19:42
  • thanks, I guess it was an issue because I used the javascript way instead of jquery? Just out of curiosity, is it normal for the width() property in this case to be 0? – jas May 16 '12 at 19:52
  • I just realized this is really just setting the max width to the width I designated in my css file, what I need is the width in pixels – jas May 16 '12 at 19:54
  • @jas Try using `.width()` function. Something like `a.css ('max-width', function () { return $(this).width(); });` – Selvakumar Arumugam May 16 '12 at 19:55
  • I did that, but it returns 0? That's what I was trying to say in my comment above. – jas May 16 '12 at 20:01
  • I can give it a shot, there's a lot going on but I'll try to isolate it down to a minimum viable example – jas May 16 '12 at 20:16
0
var a = $('.myTextAreaCssClass');

a.each(function() {
  w = $(this).width();
  $(this).css('max-width',w + 'px');
});
The System Restart
  • 2,873
  • 19
  • 28
0

try this:

$('.myTextAreaCssClass').each(function(){
    $(this).css("max-width", $(this).css("width"))
})
Ram
  • 143,282
  • 16
  • 168
  • 197