我有一个用户可以选择的按钮网格。用户在文本框中输入他们想要选择的按钮数量,然后在网格中选择这些按钮。例如,如果用户在文本框中键入“2”并选择“2”按钮然后尝试选择第三个按钮,则会出现一个警告框,指出用户超出限制请取消选择按钮。
现在我想知道的是如何对其进行编码,以便如果用户选择的按钮数量少于文本框中的数量,那么会出现一条警告消息,说明要选择更多按钮?
由于
jsfiddle中的代码:点击here
答案 0 :(得分:0)
好吧,为了在每次用户选择一个按钮时都不显示警告,并且它恰好小于他/她选择的按钮数量,你需要添加某种提交按钮,并且只有脚本在点击它时检查情况。
<form onsubmit="validate.submit(); return false;">
<textarea id="input"></textarea>
<input type="submit" value="Submit" />
</form>
够简单,对吗?让我们为按钮的显示位置添加DIV
。
<form id="form" onsubmit="validate.submit(); return false;">
<textarea id="input"></textarea> <br />
<div id="buttons"></div> <hr />
<input type="submit" value="Submit" />
</form>
现在让我们设置JavaScript功能。
window.validate = ({
config: {
min: 1, // Minimum amount of buttons allowed.
max: 10 // Maximum amount of buttons allowed.
},
data: {
state: 0,
input: null,
buttons: null,
form: null
},
validate: function(refer) {
// Refer is the amount of check boxes checked.
if(refer < this.config.min)
{
alert("You checked to little!");
}
else if(refer > this.config.max)
{
alert("You checked to much!");
}
else
{
alert("You checked JUST right!");
}
},
submit: function() {
if(this.data.state === 1)
{
var refers = this.data.form.val,
refer = 1;
if(Object.prototype.toString.call(refers) === "[object Array]")
{
refer = refers.length;
}
this.validation(refer);
return refer;
}
else
{
this.data.state = 0;
try {
var q = this.data.input.value;
// Use Number object incase of cases where numbers have non-digit,
// characters, like Infinity, NaN, 1e+10, ect.
if(new Number(q).valueOf() === 0 && q.match(/\D/)) { throw new Error(); }
q = eval(q);
if(q > this.config.max)
{
alert("We cannot process that many buttons!");
}
else if(q < this.config.min)
{
alert("You must have at least " + this.config.min + " buttons!");
}
else
{
q = Math.abs(q); // Negative to positive integer.
// Textarea validation complete!
var html = "";
for(var i=q; i>0; i--)
{
html = html + "<input type=\"checkbox\" name=\"val\" />";
}
this.data.buttons.innerHTML = html;
this.data.state = 1;
}
} catch(e) {
alert("You didn't enter a valid Number!");
}
}
},
setup: function() {
window.onload = (function() {
validate.data.form = document.getElementById("form");
validate.data.input = document.getElementById("input");
validate.data.buttons = document.getElementById("buttons");
});
delete this.setup;
return this;
}
}).setup();
这是一个很快的例子。你可能有一些错误,因为我没有测试它。祝好运! :d