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

时间:2012-08-28 14:40:09

标签: javascript

我正在尝试从表单元素输出值,我设法从选择元素输出单个值,但如果选择了多个复选框,如何输出多个值。看看是否有人可以帮忙?也许我需要通过数组传递复选框值!

<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/

1 个答案:

答案 0 :(得分:0)

应该这样做: jsFiddle example

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();
}​