VladN VladN - 9 months ago 45
Javascript Question

ASP.NET Telerik control styling with jQuery

I have a radTextBox with CssClass="mandatory".
In jQuery I have the next thing:

$(".mandatory").focusout( function () {
if($(this).val() == "") $(this).css("border", "1px solid #ff0000");
});


The problem is that on focusout, my style is "overwritten" by the classes that the control has by default on different events.
I've also tried in jQuery the next thing:

$(".mandatory").focusout( function () {
if($(this).val() == "") $(this).addClass("mandatoryErr");
});


But still nothing, the class is immediately removed after it was added.
So how can I add style to teleriks control using jQuery?

Answer Source

The easiest way to accomplish this would be to hook into the various styling options you have on the client using the Client-side API of the RadTextBox. Here's a snippet that takes essentially your initial code and applies it to the RadTextBox API:

        <script type="text/javascript">
        function ChangeBorder () {
            var textBox = $find("<%= RadTextBox1.ClientID %>");
            if (textBox.get_value() == "") {
                textBox.get_styles().EnabledStyle[0] += "border-color: #ff0000";
                textBox.updateCssClass();
            }
            else {
                //revert back to old CSS
            }
        }
    </script>

    <telerik:RadTextBox ID="RadTextBox1" runat="server" ClientEvents-OnBlur="ChangeBorder">
    </telerik:RadTextBox>

The important items to get out of this is that we are subscribing to a client-side event of the RadTextBox (OnBlur). Then we access the RadTextBox client-side object, check if the value is "" or not and then access the styles of the RadTextBox object. There are several different styles, but it seems as if you're looking for the EnabledStyle. To directly apply some CSS just use the first element of the style array. Alternatively you can apply a CSSClass:

textBox.get_styles().EnabledStyle[1] += " mandatoryErr";

Where you will be accessing the second element in the styles array. Here you can have mandatoryErr be (for example):

    <style>
    .mandatoryErr
    {
        border-color: #ff0000 !important;
    }
</style>

The !important tag is just there to increase the specificity of the CSS rule, otherwise it will not be applied (if you're using the built-in styles).

If you are looking for more information on all of this, the linked documentation articles should help. You can also use the Chrome Dev Tools and FireBug to inspect the textBox variable above and see what the _styles property holds :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download