Reputation: 75
I have put a text box where i want only numbers. I want to validate it in the client side and written the following code
@using (Html.BeginForm("LoyaltyPoints","Cart",FormMethod.Post))
{
<label>Enter point:</label>
<br />
@Html.TextBoxFor(m => m.txtLoyaltyPoints, new { @onkeypress = "OnlyNumeric(this)" })
<br />
<input type="submit" value="Submit" />
<br />
@ViewBag.LoyaltyPointsErrorMessage
}
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function OnlyNumeric(e) {
if ((e.which < 48 || e.which > 57)) {
if (e.which == 8 || e.which == 46 || e.which == 0) {
return true;
}
else {
return false;
}
}
}
now here my javascript is not firing. i tried keeping alert here but not working as intended. What could be the error. please help.
Upvotes: 2
Views: 16456
Reputation: 1
@Html.TextBoxFor(m => m.txtLoyaltyPoints, new { @onkeypress = "return onlyNos(event,this);" })
<script>
function onlyNos(e, t) {<br/>
if (window.event) {<br/>
var charCode = window.event.keyCode;<br/>
}<br/>
else if (e) {<br/>
var charCode = e.which;<br/>
}<br/>
else { return true; }<br/>
if (charCode > 31 && (charCode < 48 || charCode > 57)) {<br/>
alert("Please Enter only Numbers");<br/>
return false;<br/>
}<br/>
return true;<br/>
}
</script>
Upvotes: 0
Reputation: 2480
@Html.TextBoxFor(m => m.Height, new { @type = "number", @onkeypress = "ValidateNumber(event);" })
function ValidateNumber(event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.preventDefault ? theEvent.preventDefault() : (theEvent.returnValue = false);
}
Upvotes: 2
Reputation: 11
<td class="field_nameW">
[email protected]("PayFromBankId3_Amount", 0.00M, new { @class = "amount_field", @onblur = "FormatAmountDecimal(this,3);", @size = "7", title = "Amount", @maxlength = "11" })
<script>
$('#Id').numeric({ allow: "." });
</script>
Upvotes: 1
Reputation: 7462
You can replace onkeypress with onblur
i.e.
@Html.TextBoxFor(m => m.txtLoyaltyPoints, new { @onblur = "OnlyNumeric(this)" })
Upvotes: 1
Reputation: 863
use the following code:
@Html.TextBoxFor(m => m.txtLoyaltyPoints, new {@id ="txtLoyalty" })`
<script type="text/javascript">
$(document).ready(function () {
$("#txtLoyalty").keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
});
Upvotes: 2