gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:43:01 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com