开发者

jquery with check box in asp.net problem

I'm trying change an input mask for textbox when the the check box has been check or unckecked but the problem that always is picking up the else condation only even the check box it is check or not.

please advice to fix this problem.

here is my code:

<%@ Page Title="" Language="C#" MasterPageFile="~/Imam.Master" AutoEventWireup="true" 
CodeBehind="WebForm4.aspx.cs" Inherits="Imam_Contacts.WebForm4" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

<script src="js/jquery-1.4.1.js" type="text/javascript"></script>


<script src="js/jquery.maskedinput-1.2.2.js" type="text/javascript"></script>
<script type="text/javascript">



  if ($('#chkhtml:checked').size() > 0)
{
jQuery(function($) {

       $("#txthtml").mask("999-99-9999");
   });
 } else { 
 jQuery(functio开发者_开发知识库n($) {

       $("#txthtml").mask("99/99/9999");
   });
 }  

</script>


 </asp:Content>
 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
 <input id="chkhtml" type="checkbox" checked="checked" />

 </asp:Content>


<script type='text/javascript'>
    $('#chkhtml').click(function(){
        if ($(this).attr('checked'))
            $("#txthtml").mask("999-99-9999");
        else
            $("#txthtml").mask("99/99/9999");
    });

   $(function(){
       $("#txthtml").mask("99/99/9999"); // this is default mask
   });
</script>

I'm guessing you want to change the mask when checkbox changes its state but you don't know how you can achieve this.


Your code is running before the checkbox is rendered. Therefore, when the code runs, there are no checkboxes.

You need to wrap the entire if block in $(function() { ... }), which will execute the code in the function after the document finishes loading.

For example:

$(function() {
  if ($('#chkhtml:checked').length > 0) {
       $("#txthtml").mask("999-99-9999");
   } else { 
       $("#txthtml").mask("99/99/9999");
   }
});

Alternatively, you can use an inline conditional:

$(function() {
   $("#txthtml").mask(
        $('#chkhtml:checked').length > 0 ? "999-99-9999" : "99/99/9999"
    );
});


Along with the other answers, here's an alternate way to do it...

<script type='text/javascript'> 

    $(document).ready(function() {

        $('#chkhtml').click(function() { 
            if ($('#chkhtml').is(':checked')) {
                $("#txthtml").mask("999-99-9999");
            } 
            else {
                $("#txthtml").mask("99/99/9999"); 
            }
        });

    }); 

</script> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜