Archive for the ‘ JQuery ’ Category

Border Around Select Elements

*This has been updated here*

IE7 and below don’t support styling of the select element. Here’s a great way round this using JQuery based on this experiment .

function addBordersToSelectElement(selectElement) {
    if ($.browser.msie && $.browser.version < 8 ) {

        /* Create a container that is two pixel smaller.  This will have a 1px border added though CSS. */
        var containerElement = "<span class='left selectElementBorderRemover requiredField'\
         style='position: relative;display:block;overflow:hidden;width:0;height:0'></span>"
        $(selectElement).wrap(containerElement);
        setContainerWidth(selectElement);

        /* move the select element up and left to hide its border */
        $(selectElement).css("position", "absolute");
        $(selectElement).css("top", "-2px");
        $(selectElement).css("left", "-2px");

        //Attach event to capture any resize through text size change
        $(selectElement).resize(function() { setContainerWidth($(this)) });
    }
}

function setContainerWidth(selectElement) {
    var containerWidth = $(selectElement).width();
    containerWidth = containerWidth - 2;
    var containerHeight = $(selectElement).height();
    containerHeight = containerHeight - 2;

    $(selectElement).parent().width(containerWidth);
    $(selectElement).parent().height(containerHeight);
}

You can then apply a border to the container. In this case I used it along side validation with the following.

function checkValueAndUpdateRedBorder(validatedItem) {
    var validatedItemId = $(validatedItem).attr("id");

    if (validatedItem.attr("value") != "") {
        removeRequiredField(validatedItem);
    } else {
        addRequiredField(validatedItem);
    }

    //If validatedItem is a select
    if ($(validatedItem).parent().hasClass("selectElementBorderRemover")) {
        var selectParent = $(validatedItem).parent();

        if ($(validatedItem).hasClass("requiredField")) {
            addRequiredField(selectParent);
        } else {
            removeRequiredField(selectParent);
        }
    }

    function removeRequiredField(element) {
        $(element).removeClass("requiredField");
        $(element).addClass("requiredFieldSatisfied");
    }

    function addRequiredField(element) {
        $(element).addClass("requiredField");
        $(element).removeClass("requiredFieldSatisfied");
    }
}
Advertisements