How to invoke an event after losing focus from a textbox that was just filled out?
I have two text boxes: A and B using Html.textboxfor
. TextBox 'A' is enabled and TextBox 'B' is disabled.
When I type values in Textbox 'A' and change focus away from the textbox, TextBox 'B' should be populated with some value.
For example: I am entering the value of TextBox A = "King"; if the focus is lost from the box, the value in the Textbox B should be "Pe开发者_开发知识库ter", which should be filled automatically.
you can jsut give the textbox an attrbiute of onblur and call a method which will fill the second textbox
something like:
<script language="javascript">
function fllB()
{
var txtB = document.getElementById("txtB");
var txtA = document.getElementById("txtA");
if (txtA.value == "King")
{
txtB.value = "Peter";
}
}
</script>
<input type="text" id="txtA" onblur="fillB()" />
<input type="text" id="txtB" />
Below is the javascript function that I wrote to validate my input "Price" currency value.
<script language="javascript">
function validatePrice(textBoxId) {
var textVal = textBoxId.value;
var regex = /^(\$|)([1-9]\d{0,2}(\,\d{3})*|([1-9]\d*))(\.\d{2})?$/;
var passed = textVal.match(regex);
if (passed == null) {
alert("Enter price only. For example: 523.36 or $523.36");
textBoxId.Value = "";
}
}
If you want to fire the validation after you lost a focus from text box, then use “onblur” event which is as same as OnLostFocus() in most of the WinForm controls.
<asp:TextBox ID="TextBox19" runat="server" Visible="False" Width="183px"
onblur="javascript:return validatePrice(this);"></asp:TextBox>
Since you are using ASP.NET, why dont you used the .NET toolbox like asp:textbox. It will be easier to maintain also.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text == "King")
{
TextBox2.Text = "Peter";
}
}
It looks as though you want your second textbox to always be disabled? If so include the disabled property in the textboxfor:
<%: Html.TextBoxFor( x => x.XXX, new { id = "txtA" }) %>
<%: Html.TextBoxFor( x => x.XXX, new { id = "txtB", disabled="true" }) %>
For the JavaScript, I'm assuming you are using the jquery that is included with mvc: (If you don't want to clear txtb if the value is removed from box A, then remove the else statement)
$(function()
{
$("#txtA").change(function()
{
if ($("#txtA").val().length > 0) {
$("#txtB").val(function()
{
// Do something to populate #txtb ex: Peter
var myVar = "Peter";
return myVar;
});
}
else
{
$("#txtB").val("");
}
});
});
jQuery:
<script type="text/javascript">
$(function()
{
$("#txtA").change(function()
{
if(this.value == "King")
$("#txtB").attr("disabled", "").val( "Peter" );
});
});
</script>
精彩评论