Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the width of a button in jquery

Tags:

jquery

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.

like image 954
Hunter Hodnett Avatar asked Dec 27 '22 01:12

Hunter Hodnett


2 Answers

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.

like image 144
Rory McCrossan Avatar answered Jan 13 '23 22:01

Rory McCrossan


Get the width before you use .tabs:

var width = $("#textbox").width();
$('#tabs').tabs();
$("#myButton").css("width", width);

Demo: http://jsfiddle.net/4EfAJ/12/

like image 30
tymeJV Avatar answered Jan 13 '23 23:01

tymeJV