我开发了一个表格,学生必须在其中输入科目名称和分数。我已经通过 javascript 制作了仅用于数字的输入框,但我无法进行验证,以便学生无法输入 0 作为分数。
$("#insertbotheli13").click(function () {
$("#tablebotheli13").each(function () {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function () {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="tablebotheli13" class="table table-striped table-hover">
<input type="button" class="btn green" value="Add New+" id="insertbotheli13"></input>
<thead>
<tr>
<th>Subject</th>
<th> Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control subject1" name="subject1">
</td>
<td>
<input type="text" class="form-control marks1 allownumericwithoutdecimal" name="marks1">
</td>
</tr>
</tbody>
</table>
最佳答案
您可以检查输入值是否为零,然后将其删除,检查下面的代码片段。
此外,由于您要动态添加输入,因此事件应该附加到事件委托(delegate)中:
$("body").on("keypress keyup blur paste", ".allownumericwithoutdecimal", function(event) {
if( $(this).val() == "0"){
$(this).val( $(this).val().replace(/0/g, "") );
}
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
希望这有帮助。
$("#insertbotheli13").click(function() {
$("#tablebotheli13").each(function() {
var tds = '<tr>';
jQuery.each($('tr:last td', this), function() {
tds += '<td>' + $(this).html() + '</td>';
});
tds += '</tr>';
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
});
$("body").on("keypress keyup blur paste", ".allownumericwithoutdecimal", function(event) {
if( $(this).val() == "0"){
$(this).val( $(this).val().replace(/0/g, "") );
}
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="tablebotheli13" class="table table-striped table-hover">
<input type="button" class="btn green" value="Add New+" id="insertbotheli13"></input>
<thead>
<tr>
<th>Subject</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control subject1" name="subject1">
</td>
<td>
<input type="text" class="form-control marks1 allownumericwithoutdecimal" name="marks1">
</td>
</tr>
</tbody>
</table>
关于javascript - 输入框中的标记不应为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001864/