开发者

in asp.net how can I dynamically hide one field based off anothers value?

开发者 https://www.devze.com 2023-01-19 01:06 出处:网络
I have 4 asp:Textbox fields on a form.IDs being A1, A2 and B1, B2 for simplicity. If any one of the As or Bs is populated, I need to hide the other one.So I enter something in A1, hide A2, enter somet

I have 4 asp:Textbox fields on a form. IDs being A1, A2 and B1, B2 for simplicity. If any one of the As or Bs is populated, I need to hide the other one. So I enter something in A1, hide A2, enter something in B2, hide B1.

I thought I could use a javascript OnBlur event to do this but it doesn't do anything unfortunately. I'm trying to get the fields to appear/disappear without having to do a postback.

Any suggestions or exam开发者_StackOverflow中文版ples would be great.

thanks, Q


piece of cake, and without jQuery :P

<script>
    function txtChange(x1, x2){
        x1=document.getElementById(x1);
        x2=document.getElementById(x2);
        x2.style['display'] = (x1.value.length>0) ? 'none' : '';
    }
</script>

and

protected void Page_Load(object sender, EventArgs e)
{
    a1.Attributes["onchange"] = string.Format("txtChange('{0}','{1}')", a1.ClientID, a2.ClientID);
    a2.Attributes["onchange"] = string.Format("txtChange('{0}','{1}')", a2.ClientID, a1.ClientID);
    b1.Attributes["onchange"] = string.Format("txtChange('{0}','{1}')", b1.ClientID, b2.ClientID);
    b2.Attributes["onchange"] = string.Format("txtChange('{0}','{1}')", b2.ClientID, b1.ClientID);
}


Add the event trigger onKeyDown to your four text boxes (You can read about key press event handlers here: http://help.dottoro.com/ljlkwans.php) and use the handler to hide the unwanted text box. Or if you just want to disable and not hide it this will work for you:

<asp:TextBox ID="A1" onKeyDown="disableText('A2')" runat="server"></asp:TextBox>

And then for the javascript:

function disableText(textbox)
{
    document.getElementById(textbox).disabled=true;
}


with jquery

$(function(){
    $('#A1').blur(function(){
    if ($('#A1').value() == "")
    {
        $('#A2').fadeIn();
    }
    else
    { 
        $('#A2').fadeOut();
    }
    });
});

Though if you're using a master page id's will be different!

0

精彩评论

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