javascript 动态检查asp net复选框而无需回发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7133173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically check asp net checkbox without postback
提问by Adam Schiavone
I have an account management page that will let users change information about themselves. I want to have a checkbox checked when they click on a textbox to start editing it, so that they know, and the program knows what will be updated. I think I can do this with a postback, but I would like to avoid the extra postback if possible.
我有一个帐户管理页面,可以让用户更改自己的信息。我想在他们单击文本框开始编辑时选中一个复选框,以便他们知道,并且程序知道将更新什么。我想我可以通过回发来做到这一点,但如果可能的话,我想避免额外的回发。
I figure that this could be done with javascript... but I dont know how.
我认为这可以用 javascript 来完成……但我不知道如何。
--Edit--
- 编辑 -
@Muhammad Akhtar
@穆罕默德·阿赫塔尔
I made a blank page and tried this here is the code:
我做了一个空白页,并尝试这里是代码:
<%@ Page Title="" Language="C#" MasterPageFile="~/BlueBlack.Master" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="LinkFactory.WebForm2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Head" runat="server">
<script type="text/javascript">
function update()
{
if(document.getElementById('<%=check.ClientID %>').value != '')
{
document.getElementById('<%=check.ClientID %>').checked = true;
}
else
{
document.getElementById('<%=check.ClientID %>').checked = false;
}
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:CheckBox ID="check" runat="server" />
<asp:TextBox ID="TextBox1" runat="server" onkeypress="update();"></asp:TextBox>
</asp:Content>
-- Edit 2 --
-- 编辑 2 --
About the answer:
关于答案:
I used his script in the header of my page. For some reason I need to type 2 characters for it to work, but I think that's alright
我在页面的标题中使用了他的脚本。出于某种原因,我需要输入 2 个字符才能工作,但我认为没关系
采纳答案by Muhammad Akhtar
You can use onkeypress
event and call JS function
您可以使用onkeypress
事件并调用 JS 函数
<asp:TextBox ID="TextBox1" runat="server" onkeypress="update();"></asp:TextBox>
function update()
{
if(document.getElementById('<%=TextBoxID.ClientID %>').value != '')
{
document.getElementById('<%=CheckBoxID.ClientID %>').checked = true;
}
else
{
document.getElementById('<%=CheckBoxID.ClientID %>').checked = false;
}
}
回答by Peter Olson
You can do this in Javascript without having to add inline events to your markup, which makes it look better and is easier to maintain:
您可以在 Javascript 中执行此操作,而无需向标记添加内联事件,这使其看起来更好且更易于维护:
document.getElementById('<%=TextBoxID.ClientID %>').focus = function() {
document.getElementByID('<%=CheckBoxID.ClientID %>').checked = true;
}
This assumes that you want the event to fire when focus is put on the textbox.
这假设您希望在将焦点放在文本框上时触发事件。