我想调用 javascript 函数,当 select 选项(它基于 for 循环)只被 selected 一次
I wanted to call the javascript function, when the select option(It is based on for loop) is selected only once
我的 Velocity 模板中有以下代码:
<tr>
<td>
<input name ="questions" id = "quest" type = "text" value = "$!question.question" size="30" style="border: none" readonly/>
</td>
<td>
<select id="rate" name="rating" **onchange="myFunction()**">
#set ($values = [0..2])
#foreach ($value in $values)
#set ($optValue = $value)
#if ($optValue == 0)
<option value="$optValue" selected>$optValue</option>
#else
<option value="$optValue">$optValue</option>
#end
#end
</select>
</td>
</tr>
在我的 Javascript 中,我正在定义函数 myFunction()。
function myFunction()
{
var count = document.getElementsByName('rating').length;
var total = 0;
for(x=0;x<count;x++)
{
var formRating = document.getElementsByName('rating')[x].value;
var formWeightage = document.getElementsByName('weightage') [x].value;
total=formRating + formWeightage;
console.log(total);
}
return total;
};
我在这里面临的问题是,
考虑上面的速度生成 5 行和 5 个 selected 框。
当 i select 第一个 select 选项值为 1 时,调用 js 函数 (myFunction) 并且 select boxes() 的所有剩余值也被 selected 和显示。
我只想获取 select 框 i select 的值。如何实现?
您可以获得具有 selected
属性的所有选项,如下所示:
function doSomethingWithSelectedOptions(){
var selectedElements = document.querySelectorAll("option[selected]");
// Iteration over all selected elements
for(var i=0; i<selectedElements.length; i++){
console.log("Selected element: "+selectedElements[i].innerHTML);
}
}
我的 Velocity 模板中有以下代码:
<tr>
<td>
<input name ="questions" id = "quest" type = "text" value = "$!question.question" size="30" style="border: none" readonly/>
</td>
<td>
<select id="rate" name="rating" **onchange="myFunction()**">
#set ($values = [0..2])
#foreach ($value in $values)
#set ($optValue = $value)
#if ($optValue == 0)
<option value="$optValue" selected>$optValue</option>
#else
<option value="$optValue">$optValue</option>
#end
#end
</select>
</td>
</tr>
在我的 Javascript 中,我正在定义函数 myFunction()。
function myFunction()
{
var count = document.getElementsByName('rating').length;
var total = 0;
for(x=0;x<count;x++)
{
var formRating = document.getElementsByName('rating')[x].value;
var formWeightage = document.getElementsByName('weightage') [x].value;
total=formRating + formWeightage;
console.log(total);
}
return total;
};
我在这里面临的问题是, 考虑上面的速度生成 5 行和 5 个 selected 框。 当 i select 第一个 select 选项值为 1 时,调用 js 函数 (myFunction) 并且 select boxes() 的所有剩余值也被 selected 和显示。 我只想获取 select 框 i select 的值。如何实现?
您可以获得具有 selected
属性的所有选项,如下所示:
function doSomethingWithSelectedOptions(){
var selectedElements = document.querySelectorAll("option[selected]");
// Iteration over all selected elements
for(var i=0; i<selectedElements.length; i++){
console.log("Selected element: "+selectedElements[i].innerHTML);
}
}