简体   繁体   中英

Can i pass the ID name in an onChange event for a textbox?

I have 3 textboxes to do a check on the entered date. The code I originally had was for one textbox. Is there a way to pass an ID name to the onChange event

<asp:TextBox ID="txtDate" runat="server" Width="110px" onChange="checkEnteredDate('txtDate')"></asp:TextBox>

function checkEnteredDate(var textBox = new String();) {
            var inputDate = document.getElementById(textBox);
            //if statement to check for valid date
            var formatDate = new Date(inputDate.value);
            if (formatDate > TodayDate) {
                alert("You cannot select a date later than today.");
                inputDate.value = TodayDate.format("MM/dd/yyyy");
            }
}

为了传递文本框的ID,您必须在Page_Load后面的代码中执行此操作:

txtDate.Attributes["onchange"] = String.Format("checkEnteredDate('{0}');",txtDate.ClientID);

You can pass this as the parameter on the onChange assignment:

<asp:TextBox ID="txtDate" runat="server" Width="110px"
 onChange="checkEnteredDate(this.id)"></asp:TextBox>

I actually figured it out. I did the following:

...onChange="checkEnteredDate(this)"...

function checkEnteredDate(inputDate) {            
            //if statement to check for valid date
            var formatDate = new Date(inputDate.value);
            if (formatDate > TodayDate) {
                alert("You cannot select a date later than today.");
                inputDate.value = TodayDate.format("MM/dd/yyyy");
            }
}

getElement was messing me up. Thanks for the suggestions, they brought me in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM