通过原型/构造函数从复选框输出值

Output values from checkboxes via protoype/constructor

本文关键字:复选框 输出 构造函数 原型      更新时间:2023-09-26

我试图从表单元素输出值,我设法从select元素输出单个值,但如果选择了多个复选框,我如何输出多个值。看看有没有人能帮忙?也许我需要通过数组传递复选框值!

<head><title></title></head>
<style>
#box{
border:solid 1px red;
height:16px;
}
</style>
<body>
size : <select id = "test1">
<option>Large</option>
<option>Medium</option>
<option>small</option>
</select>
Base : <select id = "test2">
<option>Thick</option>
<option>Thin</option>
</select>
Tomato:<Input type ="checkbox">
Onion:<Input type ="checkbox">
Paprika:<Input type ="checkbox">

<input type="submit" value = "Submit" onclick ="buttonClick()" />
<br /> <br />
<div id ="box"></div>

<script type = "text/javascript">
function Pizza(s,t){
this.size = s;
this.type = t;
}
Pizza.prototype.myPizza = function(){
document.getElementById('box').innerHTML = "This is a " + this.size + " Pizza with " +  this.type + " base and the toppings include: ";
}
function buttonClick(){
x = document.getElementById('test1').value;
y = document.getElementById('test2').value;
Tuesday = new Pizza(x,y);
Tuesday.myPizza();
}
</script>
</body>
</html>

代码也可以在此处查看:http://jsfiddle.net/bhEeZ/2/

这应该做到:jsFiddle示例

function Pizza(s, t, tops) {
    this.size = s;
    this.type = t;
    this.toppings = tops;
}
Pizza.prototype.myPizza = function() {
    document.getElementById('box').innerHTML = "This is a " + this.size + " Pizza with " + this.type + " base and the toppings include: " + this.toppings.join(', ');
};
function buttonClick() {
    x = document.getElementById('test1').value;
    y = document.getElementById('test2').value;
    z = new Array();
    var chk_arr = document.getElementsByName("topping[]");
    for (var i = 0; i < chk_arr.length; i++) {
        if (document.getElementsByName("topping[]")[i].checked) z.push(document.getElementsByName("topping[]")[i].value);
    }
    Tuesday = new Pizza(x, y, z);
    Tuesday.myPizza();
}​