Change button width in jquery

I am trying to change the width of a button so that it matches the width of the text box above it in jquery. I tried to accomplish this 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 use tabs, the width of the text box is not immediately available.

+4
source share
8 answers

The problem is that the text box is hidden (on a tab that is not displayed) and therefore the width cannot be calculated. The work around is cloning an element, adding it, then its width and finally removing it from the DOM.

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

Updated script

Note; the slight difference in widths here is due to differences in padding and / or margin, which I allow you to solve in CSS.

+4
source

Get width before using .tabs :

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

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

+4
source

You can set the width as soon as you click on the tab containing the form. See here: http://jsfiddle.net/4EfAJ/16/

 $('#tabs').tabs(); $("#productTab").on("click",function() { $("#myButton").css("width", $("#textbox").width()); }); 
+2
source

I think this should work

 $("#myButton").css("width", $("#textbox").css("width")); 
0
source

Try changing the width of the button as soon as its tab is visible, and not earlier:

  $('#tabs').tabs({ activate: function(event, ui){ if (ui.newTab.index() == 1){ $("#myButton").css("width", $("#textbox").width() ); } } }); 
0
source

$("#textbox") invisible on the loaded temporary page, so you cannot get its width . Try putting these things on the first tab. or resize width when the second is active.

0
source

try this first:

 <input type="text" id="textbox" **style="width:300px"** /> 

then

 $("#myButton").css({width:$("#textbox").width()+"px"}); 

Hope this leads to some solution

0
source

Be more flexible, just assign a width to the button. Not crazy if he is visible or not.

 #textbox { width: 250px } 

If you can solve the problem with css, always choose this path before running javascript.

0
source

Source: https://habr.com/ru/post/1488496/


All Articles