I'm trying to change the width of a button to match the width of the text box above it in jquery. I have tried to accomplish this by using the following line:
$("#myButton").css("width", $("#textbox").width());
In the code below:
JSFiddle
JQuery:
$('#tabs').tabs();
$("#myButton").css("width", $("#textbox").width());
HTML:
<div id="tabs">
<ul>
<li><a href="#tabs-1"> Tab 1</a></li>
<li><a href="#tabs-2" id="productTab">Tab 2</a></li>
</ul>
<div id="tabs-1" class="buttons" class="ui-widget">
</div>
<div id="tabs-2">
<table>
<tr>
<td>
<input type="text" id="textbox" />
</td>
</tr>
<tr>
<td>
<button id="myButton">My Button
</button>
</td>
</tr>
</table>
</div>
</div>
I believe that since I am using tabs, the width of the text box is not immediately available.
The problem is because the textbox is hidden (in the tab which is not being displayed) and therefore it's width cannot be calculated. The work around is to clone the element, append it, then get it's width and finally remove it from the DOM.
$('#tabs').tabs();
var $textboxClone = $('#textbox').clone().appendTo('#tabs');
$("#myButton").css("width", $textboxClone.width());
$textboxClone.remove();
Updated fiddle
Note; the minor difference in widths here is due to padding and/or margin differences which I'll let you solve in CSS.
Get the width before you use .tabs
:
var width = $("#textbox").width();
$('#tabs').tabs();
$("#myButton").css("width", width);
Demo: http://jsfiddle.net/4EfAJ/12/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With