Friday, February 24, 2017

Setting and Getting Checkbox Values using SPServices and JQuery

I was given a requirement for a project where a user was presented with two questions, each with a checkbox related.  The two questions were:

1. I have read and understood this document
2. This document does not apply to me

The user is only allowed to select one of these choices.  How do I support this requirement using a form with checkboxes and JQuery?  The following code meets these requirements, see comments for line by line explanations.

<script src="../SiteAssets/jquery-1.11.3.js" type="text/javascript"></script>
<script src="../SiteAssets/jquery.SPServices-2014.02.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

  $(document).ready(function () {
   alert('JQUERY LOADED');  //A test to ensure JQuery paths correct.  Comment out for prod
   $("input[type='checkbox']").click(function() {  // detect checkbox check
    var checkboxName = ($(this).attr('name'));  // get the name of the checkbox that was just clicked
    if (checkboxName == 'Checkbox1') {  // if the first checkbox is checked
     $('input[name=Checkbox2]').attr('checked', false);  // uncheck the second one
    if (checkboxName == 'Checkbox2') {  // if the second checkbox is checked
     $('input[name=Checkbox1]').attr('checked', false);  // uncheck the first one



<input name="Checkbox1" type="checkbox" />I have read and understood this document.<br/>
<input name="Checkbox2" type="checkbox" />This document does not apply to me.<br/>

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from JQuery Training in Chennai . or learn thru JQuery Training . or learn thru ES6 Online Training. Nowadays JavaScript has tons of job opportunities on various vertical industry.