0
我想創建一個js代碼,所以在輸入字段(對於下面的HTML代碼),我只能把數字從0到12。但問題是,輸入已經有一個ID所以...這是我的代碼: HTML:輸入字段只接受從0到12的數字?
<!-- Months Textfield -->
<form>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" input id="d" data-in="" type="text" pattern="-?[0-9]*(\.[0-9]+)?" id="sample2" onchange="handleChange(this);">
<label class="mdl-textfield__label" for="sample2">Months...</label>
<span class="mdl-textfield__error">Please specify monthes in numbers not in letters !</span>
<input id="e" input type="hidden" data-in="" value="2628002.88" type="text" />
</div>
</form>
JS:
// Get all your elements stores
var a = document.getElementById("a");
var b = document.getElementById("b");
var c = document.getElementById("c");
var d = document.getElementById("d");
var e = document.getElementById("e");
var f = document.getElementById("f");
var h = document.getElementById("h");
var i = document.getElementById("i");
var j = document.getElementById("j");
var astored = a.getAttribute("data-in");
var bstored = b.getAttribute("data-in");
var dstored = d.getAttribute("data-in");
var estored = e.getAttribute("data-in");
var hstored = h.getAttribute("data-in");
var istored = i.getAttribute("data-in");
function calculate(input1, input2, output) {
output.innerHTML = input1.value * input2.value;
}
function add(input1, input2, input3, output) {
output.innerHTML = parseInt(input1.innerHTML) + parseInt(input2.innerHTML) + parseInt(input3.innerHTML);
}
setInterval(function(){
var temp;
if (a == document.activeElement) {
temp = a.value;
if (astored != temp){
astored = temp;
a.setAttribute("data-in",temp);
calculate(a, b, c);
}
} else if (b == document.activeElement) {
temp = b.value;
if (bstored != temp) {
bstored = temp;
b.setAttribute("data-in",temp);
calculate(a, b, c);
}
} else if (d == document.activeElement) {
temp = d.value;
if (dstored != temp) {
dstored = temp;
d.setAttribute("data-in",temp);
calculate(d, e, f);
}
} else if (e == document.activeElement) {
temp = e.value;
if (estored != temp) {
estored = temp;
e.setAttribute("data-in",temp);
calculate(d, e, f);
}
} else if (h == document.activeElement) {
temp = h.value;
if (hstored != temp) {
hstored = temp;
h.setAttribute("data-in",temp);
calculate(h, i, j);
}
} else if (i == document.activeElement) {
temp = i.value;
if (istored != temp) {
istored = temp;
i.setAttribute("data-in",temp);
calculate(h, i, j);
}
}
add(c, f, j, elem_to_print_into);
}, 50);
a.onblur = calculate(a, b, c);
b.onblur = calculate(a, b, c);
d.onblur = calculate(d, e, f);
e.onblur = calculate(d, e, f);
h.onblur = calculate(h, i, j);
i.onblur = calculate(h, i, j);
calculate(a, b, c);
calculate(d, e, f);
calculate(h, i, j);
感謝您幫助我創建的代碼,並把它在HTML ...
爲什麼事實上,它已經有一個id是一個問題嗎?此外,你應該考慮給一些有意義的ID而不是僅僅單個字母 – litelite
那麼,你可以幫助我的代碼?代碼用於輸入行。它已經有一個ID「D」,如果我創建一個JS代碼,它會有另一個ID!你有什麼想法 ? –
當您聽起來像只希望用戶輸入數字時,是否存在使用文本輸入字段的特定原因?如果將輸入的type屬性設置爲「number」,則可以使用'min'和'max'屬性來控制該字段中允許的最小值和最大值。例如:https://jsfiddle.net/GigabyteGiant/k3766k66/ –