我有一个包含2个范围输入的表单来设置$ target值(如下面的代码所示。)在提交表单时,将这些输入存储到数据库中。最初显示每个滑块的存储值,但是当范围滑块移动时,javascript会显示新选择的值。
我现在正试图动态显示总共2个范围输入,即根据存储的值显示总数,但是,如果移动范围滑块,则总计还应动态更改。
<label for="monday">Monday - $<span id="monday"><?php echo number_format($set_monday) ?> </span></label>
<?php if (!empty($set_monday)) { ?>
<input type="range" min="0" max="5000" id="monday" name="monday" value=<?php echo $set_monday ?> step="100" oninput="showValue1(this.value)" />
<?php } else { ?>
<input type="range" min="0" max="5000" id="monday" name="monday" value="0" step="50" oninput="showValue1(this.value)" />
<?php } ?>
<script type="text/javascript"> function showValue1(newValue) { document.getElementById("monday").innerHTML=newValue;} </script>
<label for="tuesday">Tuesday - $<span id="tuesday"><?php echo number_format($set_tuesday) ?></span></label>
<?php if (!empty($set_tuesday)) { ?>
<input type="range" min="0" max="5000" id="tuesday" name="tuesday" value=<?php echo $set_tuesday ?> step="100" oninput="showValue2(this.value)" />
<?php } else { ?>
<input type="range" min="0" max="5000" id="tuesday" name="tuesday" value="0" step="50" oninput="showValue2(this.value)" />
<?php } ?>
<script type="text/javascript"> function showValue2(newValue) { document.getElementById("tuesday").innerHTML=newValue;} </script>
<label>Total Target = $
<?php
$sum_total = $set_monday + $set_tuesday;
echo number_format($sum_total);
?>
</label>
我无法弄清楚如何添加函数的输出并混合添加php和javascript变量,有人可以帮忙吗?
答案 0 :(得分:1)
标签内的跨度和输入ID都是相同的,这是错误的。确保HTML元素具有唯一ID。此外,需要javascript动态计算总和。基于此,您的代码应如下所示:
<label for="monday">Monday - $<span id="monday"><?php echo number_format($set_monday) ?> </span></label>
<?php if (!empty($set_monday)) : ?>
<input type="range" min="0" max="5000" id="mondayRange" name="monday" value=<?php echo $set_monday ?> step="100" oninput="showValue(this)" />
<?php else : ?>
<input type="range" min="0" max="5000" id="mondayRange" name="monday" value="0" step="50" oninput="showValue(this)" />
<?php endif; ?>
<label for="tuesday">Tuesday - $<span id="tuesday"><?php echo number_format($set_tuesday) ?></span></label><br>
<?php if (!empty($set_tuesday)) : ?>
<input type="range" min="0" max="5000" id="tuesdayRange" name="tuesday" value=<?php echo $set_tuesday ?> step="100" oninput="showValue(this)" />
<?php else : ?>
<input type="range" min="0" max="5000" id="tuesdayRange" name="tuesday" value="0" step="50" oninput="showValue(this)" />
<?php endif; ?>
<label id="total">Total Target = $
<?php
$sum_total = $set_monday + $set_tuesday;
echo number_format($sum_total);
?>
</label>
<script type="text/javascript">
function showValue(range)
{
var sum = parseInt(document.getElementById('mondayRange').value) + parseInt(document.getElementById('tuesdayRange').value);
document.getElementById(range.id.substr(0, range.id.length - 5)).innerHTML = range.value;
document.getElementById('total').innerHTML = 'Total Target = $' + sum;
}
</script>