javascript - 通过原型(prototype)/构造函数从复选框输出值

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

最佳答案

这应该可以做到: 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();
}​

关于javascript - 通过原型(prototype)/构造函数从复选框输出值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12161757/

相关文章:

javascript - 在 setInterval 中调用方法时出错

javascript - React 只为点击的元素提供动画

javascript - 了解客户端文件的对象 URL 以及如何释放内存

javascript - Kendo UI Mobile vs Sencha Touch vs Intel App Framework

javascript - 使 TinyMCE 跟随文本区域内的 anchor

javascript - 添加类后无法从元素中删除该类

javascript - 如何在 AngularJS 中的不同 Controller 中设置变量?

javascript - NodeJS/MySQL 查询数据 url 中的引号

reverseArrayInPlace 的 JavaScript 函数 -- Eloquent JavaScript Ch4

javascript - (jQuery) 使用 extend() 访问自定义属性时出现问题