CPK_2011 CPK_2011 - 2 months ago 25
ASP.NET (C#) Question

RadioButtonList not firing SelectedIndexChanged everytime

I have a RadioButtonList with "Leave" and "Available" options.


  1. I am throwing confirm message box on click of "Leave" in RadioButtonList from Server side as below

    protected void rdlUser_SelectedIndexChanged(object sender, EventArgs e)
    {
    radWindowManager.RadConfirm("Are you sure you want to take leave?", "confirmLeave" + this.ClientID, 300, 100, null, "");
    }

  2. If user clicks "Cancel", then it will automatically selects "Available" with below code.



The following is the javascript code to "Ok" or "Cancel" leave.

function confirmLeave<%=this.ClientID%>(arg) {
if (arg == true) {
alert("User has selected Leave.")
}
else {
var rdlUser = docment.getElementById("<%= rdlUser.ClientID %>");
var radioButtons = rdlUser.getElementsByTagName('input');
radioButtons[1].checked = true;
}
}


If the user clicks "Leave" for the 2nd time, the SelectedIndexChanged does not fire at all.

I am flexible to move Server Side code to Client side also.

Answer

Since you're open to the idéa of moving the code to the client instead. Remove the OnSelectedIndexChange on your radiobutton to skip the postback. You should be able to do something like this instead:

// Put this in a script-tag.
$(document).ready(function(){
    $('#<%=this.ClientID%>').change(function(){
        var radioBtnId = this.id;
        radconfirm('Are you sure you want to take leave?', function(arg){
            if (arg == true) {
                alert("User has selected Leave.")
            }    
            else {
                var rdlUser = docment.getElementById(radioBtnId);
                var radioButtons = rdlUser.getElementsByTagName('input');
                radioButtons[1].checked = true;
            }
         }
        });
    });
})

Below is a snippet that uses id's without server code.

$('#radio1').change(function(e){
  var radioBtnId = this.id;
  var $this = $(this);
  radconfirm('Are you sure you want to take leave?', function(arg){
    // Not really sure what you want to do here...
    if (arg == true) {
      alert("User has selected Leave.")
    }    
    else {
      // Select "Available instead".
      $this.siblings('input').prop('checked',true);
      
      // Unselect "Leave"
      
      // With javascript
      var rdlUser = document.getElementById(radioBtnId);              
      rdlUser.checked = false;
      
      // With jQuery
      $this.prop('checked', false);
    }
  });
});
    
// Mocked for now...
function radconfirm(value, callback){
  var result = confirm(value);
  callback(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radios" id="radio1" value="Leave"/> <label for="radio1" >Leave</label>
<input type="radio" name="radios" id="radio2" value="Available"/> <label for="radio2" >Available</label>