Question

I currently have:

jquery

$(document).ready(function () { 
    $('.span-fix').each(function(){ /* Do this for each extended input */
        var wide = $(this).width(), /* create a variable that holds the width of the form */
            label = $(this).prev('.add-on').width(); /* create another variable that holds the width of the previous label */
        $(this).width( wide - label ); /* subtract the label width from the input width and apply it in px */
    });
});

html

<div class="input-prepend">
    <span class="add-on">Location</span>
    <input name="ctl00$ContentPlaceHolder1$tbLocation" type="text" id="tbLocation" class="span12 span-fix" placeholder="Location" style="width: 97.04668304668304%; ">
</div>

Fiddle that shows the problem: http://jsfiddle.net/SuguM/

However, this applies the new width in px, and I'm using a fluid layout and need this to be a percent again.

Is there a way to convert the px applied to a %?

Was it helpful?

Solution

In fact you omit the padding in your calcul. I think this code help you.

EDIT :

This is the code for firefox :

$(document).ready(function () {
    $('.span-fix').each(function(){ /* Do this for each extended input */
        var label = $(this).prev('.add-on').outerWidth();
        /* create another variable that holds the width of the previous label */
        $(this).width( (1-(label + $(this).outerWidth() - $(this).width())/$(this).parent().width()) *100 + "%" );
    });
});

And this is the code for chrome :

$(document).ready(function () {
    $('.span-fix').each(function(){ /* Do this for each extended input */
        var label = $(this).prev('.add-on').outerWidth(); 
        /* create another variable that holds the width of the previous label */
        $(this).css("width", (1-(label)/$(this).parent().width()) *100 + "%" );
    });
});​

For chrome you must set the property css if you use the width method when you check the width css property, the property value is not equel to the value calculated.

There is an example on jsFiddle here.

Here there is a jsFiddle with the two implementation. Now you just need to detect the browser.

OTHER TIPS

This takes the parent's width and just calculates the percentage.

$(this).width((wide - label)/$(this).parent().width()*100+'%');

Based on an earlier post by me.

var getPercent = function(elem) {
    var elemName = elem.attr("id"),
        width = elem.width(),
        parentWidth = elem.offsetParent().width(),
        percent = Math.round(100 * width / parentWidth);
    return percent;
};

This calculates the percentage with the entire document:

$(this).width((wide - label) * 100 / $(document).width()+'%');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top