我有一個更新操作來更新基於我的文本框輸入的值。我使用JavaScript進行驗證。腳本和驗證僅適用於第一個文本框值。
我查看代碼驗證MVC4中的文本框
@foreach (var item in Model)
{ <tr>
<td align="right" class="Text_nocolor" valign="top">
@using (Html.BeginForm("Update", "Cart", new { UserID = Request.QueryString["UserID"] }, FormMethod.Post, new { id = "myForm" }))
{
@Html.Hidden("id", @Request.QueryString["UserID"] as string)
@Html.Hidden("productid", item.ProductID as string)
<input id="Quantity" type="text" class="Text_nocolor" name="Quantity" value="@item.Quantity" onblur="return allownumbers() " maxlength="3"/>
@Html.Hidden("unitrate", item.Rate)
<input type="submit" value="Edit" class="Text_nocolor" onclick="return RegainFocus();" />
}
</td >
<tr>
}
腳本我用:
<script type="text/javascript">
function RegainFocus() {
if ((document.getElementById("Quantity").value).length == 0) {
document.getElementById("Quantity").focus();
alert("Quantity cannot be empty");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
else if ((document.getElementById("Quantity").value) > 100) {
alert("There is no enough inventory for this product to fulfill your order");
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
}
function allownumbers() {
var val = parseInt(document.getElementById("Quantity").value);
if (!val || val < 1) {
alert('Please enter a valid value');
document.getElementById("Quantity").value = document.getElementById("Quantity").defaultValue;
return false;
}
document.getElementById("Quantity").value = val;
return true;
}
</script>
我還檢查我是否可以得到的文本框不同的ID。但是,所有的文本框都有相同的ID,驗證不適用於除第一個文本框之外的其他文本框。
任何建議。
編輯::
function allownumbers() {
alert('fasfa');
var elements = document.getElementsByName('Quantity');
for (var i = 0; i < elements[i].length; i++) {
alert(elements);
if (!elements || elements < 1) {
alert('Please enter a valid value');
return false;
}
else if (elements > 100) {
alert('Please enter a value less than 100');
return false;
}
}
return true;
}
模型具有價值和每一個文本框,在其中包含的值。但元素只返回NaN值。
document.getElementsByName('Quantity')將NaN作爲值返回。 – kk1076
也許有沒有項目在模型中的foreach循環 – karaxuna
請檢查我的編輯。 – kk1076