gpt4 book ai didi

javascript - 单选按钮值添加到数组?

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

我正在构建一个向导作为一个学习元素,我想在最后一页上汇总整个向导中选中的所有单选按钮...我是否通过数组来完成此操作?如果是这样,我如何将每个单选按钮值添加到数组,然后将其记录到摘要页面?还有另一种方法吗?请帮忙。

最佳答案

这是一个例子,希望它或多或少能满足你的需要:

HTML

//First HTML DIV
<div>
<input type="radio" name="image_size" value="100x100"> 100x100<br>
<input type="radio" name="image_size" value="200x200"> 200x200<br>
<input type="radio" name="image_size" value="500x500"> 500x500<br>
<input type="button" value="Next" id="Next_ImageSize" />
</div>
//Second HTML DIV
<div>
<input type="radio" name="image_color" value="blue"> blue<br>
<input type="radio" name="image_color" value="green"> green<br>
<input type="radio" name="image_color" value="yellow"> yellow<br>
<input type="button" value="Next" id="Next_ImageColor" />
</div>
//Summary HTML DIV
<div>
<h1>Summary</h1>
<p id="values"><p>
</div>

JAVASCRIPT:(使用 Jquery 库)

var _SummaryArr = []; //empty array
var _SummaryObj = []; //empty array (used for array of objects)

//Add the selected radio button to the array
$("[name='image_size']").change(function() {
_SummaryArr[0] = $(this).val(); //Index 0 for the first div
console.log(_SummaryArr[0]); //log to see the result
});
//Add the selected radio button to the array
$("[name='image_color']").change(function() {
_SummaryArr[1] = $(this).val(); //Index 1 for the second div
console.log(_SummaryArr[1]); //log to see the result
});



//Add the selected radio button to the array
$("[name='image_size']").change(function() {
_SummaryObj[0] = { "image_size" : $(this).val() }; //Index 0 for the first div
console.log(_SummaryObj[0]); //log to see the result
});

//Adding the values to the summary using array
for (var i = 0; i < _SummaryArr.length; i++) {
if (i == 0)
$("#values").html("<span>Image size: " + _SummaryArr[i] + "</span>");

if (i == 1)
$("#values").html("<span>Image color: " + _SummaryArr[i] + "</span>");
}
//Adding the values to the summary using object array
for (var i = 0; i < _SummaryObj.length; i++) {
if (i == 0)
$("#values").html("<span>Image size: " + _SummaryObj[i].image_size + "</span>");

}

JavaScript:( native )

//Get all the radio button elements by name
var rad = document.getElementsByName('image_size');

//Iterate through all the buttons and assign click event listener
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
_SummaryObj[0] = {"image_size":this.value}; //for the first div
//or
//_SummaryObj.push({"image_size":this.value});
};
}

for (var i = 0; i < _SummaryObj.length; i++) {
if (i == 0) //simple check to assign the name (this can easily be replaced by some dynamic function)
document.getElementById("values").innerHTML = "Image size:" + _SummaryObj[i].image_size;
}

关于javascript - 单选按钮值添加到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011079/

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