Click here to Skip to main content
15,891,136 members
Articles / Programming Languages / Javascript
Tip/Trick

Manipulating Controls (Page Elements) in Sharepoint with jQuery

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
3 Jun 2015CPOL4 min read 8.1K  
Simple (once you know how) way to modify controls based on the state of other controls in Sharepoint using jQuery

21st Century Tommys

You can write event handling code in C# to respond to controls being clicked, etc. on Sharepoint pages/Web Parts, but unfortunately the code won't run synchronously - e.g., if you add an "OnChanged" event to a checkbox, checking it or unchecking it on the page as it runs won't cause your event to fire - until you submit the form, at which point you probably don't care any more ("better late than never" is a maxim that doesn't always apply).

So, you need some client-side code that will act immediately, rather than waiting for the browser to poke the server. Cue the fanfare and make way for jQuery, the Crown Prince of King JavaScript.

Once you know how to do it (in my case, it took going down a lot of what ultimately turned out to be "blind leads" - reading this, trying that, etc.*) it's not hard at all.

* I think programmers are often the 21st Century Tommys - we grope about like "deaf, dumb and blind" kids when trying to implement features/get things to work until we seemingly "stumble" into the right solution. But that serendipitous discovery is actually preceded by tons of toil, as is pinball wizardry.

Fortunately, adding jQuery to your Sharepoint page or Web Part is easy as gooseberry pie. Just add code like this to the end of the page's or WebPart's *.ascx (not *.ascx.cs) file:

JavaScript
<script type="text/javascript">
/* When "Employee" checkbox changes state, set up txtbxSSNOrITIN accordingly */
$(document).on("change", '[id$=ckbxEmp]', function () {
    if ($(this).is(":checked")) {
        $('[id$=txtbxSSNOrITIN]').css('background-color', '#ffff00');
        $('[id$=txtbxSSNOrITIN]').css('width', '24');
    } else {
        $('[id$=txtbxSSNOrITIN]').css('background-color', 'green');
        $('[id$=txtbxSSNOrITIN]').css('width', '144');
    }
}); 
</script>

Using the code above as a basis/starting point, you can respond to any control's event, and then respond to that event in whatever way you want.

You can see that the code works by running the "fiddle" here

A "meaner" version of this ("sure codes a mean pinball!") was inspired by Roko C. Buljan in the StackOverflow question/answer here; my "take" on that (shaped more shapily to my needs) is:

JavaScript
$(document).on("change", '[id$=ckbxEmp]', function () {       
    var ckd = this.checked;
    var $input = $('[id$=txtbxSSNOrITIN]');
    if(ckd) $input.data("oldValue", $input.val()); // Remember current value
    
    $input.prop("maxlength", ckd? 4 : 12).css({
        background: ckd? 'yellow' : "lightgreen",
        width: ckd? 40 : 80
    }).val(function(i, v){
        // If checked, slice value to four characters:
        return ckd && v.length>4 ? v.slice(0,4) : $input.data("oldValue");
    });    
    
    $lbl.text(ckd ? "SSN" : "ITIN");
    /* This sets focus to the end of the textbox (multiplication by 2 is because some characters are counted as two) */
    var strLength = $input.val().length * 2;
    $input.focus();
    $input[0].setSelectionRange(strLength, strLength);
}); 

In the second iteration of the code, the change event of an element whose ID ends with "ckbxEmp" is handled. It then, based on whether the checkbox is checked or not, changes the maxlength (allowable number of characters) in the textbox which has a generated ID ending with "txtbxSSNOrITIN", and the background color, and the width. If changing from unchecked to checked, and too many characters (more than 4) have been entered, this is trimmed/truncated/sliced to the four that SSN can be (just the last portion of an SSN, that is). The fanciest code there preserves the previous longer val, so that if the user again returns to "ITIN" from "SSN" that longer value is restored.

As a bonus to you cherished readers (proving I hold no grudges regarding my Choctopilessness, assuming it/they was/were lost in the mail), I have added code at the end to change the label's text, corresponding to the state of the checkbox, and also added code to set focus to the end of the "associated" textbox.

Code Breakdown

So as to avoid your 19th Nervous Breakdown, and to potentially save you enough time so that you can learn to play Foggy Mountain Breakdown on the banjo, here are a couple of tips/explanations about the code:

The reason "[id$=ckbxEmp]" is used instead of "#ckbxEmp" (which I tried, unsuccessfully), is that the actual ID (and name, and "for") of the dynamically created checkbox is not simply "ckbxEmp" (the ID I assigned it in code when dynamically creating it), but the Welshified "ctl00_ctl24_g_1caf4ad1_092d_4224_bd10_28ab028aab50_ctl00_ckbxEmp"

For Pete's sake, somebody's conspiring to drive me crazy (which would be a short lift) with all this super-elongated ID prefixing. If it's not one conspirator, it's another! Who's Next?!?

By using the "id$=" syntax, it finds the element whose ID ends with "ckbxEmp". All the jQuery does is responds to the change event of this checkbox, setting a couple properties of another control (which I gave the ID "txtbxSSNOrITIN") based on whether the state of the checkbox after changing is checked or unchecked. If checked, the textbox's background becomes green and its width is reduced. If unchecked, the textbox's background is greenified and its width is expanded.

Subtle Hint

In spite of relentless nagging and importunities, I still have not become the proud recipient of a Choctypus (chocolate, chocolate-covered, and/or chocolate-filled duckbilled platypus) from any grateful readers. A word to the wiseguys: If this revoltin' development keeps up, the Platypus may evolve wings and commence strafing random slackers with swift slices from its poison toe! If you thought cat scratches were painful, you ain't felt nuthin' yet! If flying Duckbilled Platypi do not strike terror to the innermost depths of your soul, you have either reached nirvana or you are not paying sufficient attention to the extraordinary danger that this cruel and unusual pain and suffering could inflict upon heedless parties of the whatevereth part.

URGENT: Hurry up, because I'm really hungry, and I'm a dyed-in-the-wool Chocolovore (I only eat chocolate - no meat, eggs, fish, fowl, dairy, fruits, vegetables, nuts, grains, or seeds), and I don't want to die in the wool (that I'm wearing).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
-- There are no messages in this forum --