1

I have been trying to figure out how to make it so that if a specific checkbox is checked, the total amount in a textbox gets 50.00 added to it when the submit button is clicked, before it submits the form. In fact, it would be better to have the update happen as soon as the checkbox is checked.

Here's what i tried so far:

<!DOCTYPE html>
<html>
<head>
<script>
function toggle(){
var indoorCamping = 50.00;
var total = 0.00;
if(document.getElementByName('fifty').is(':checked')){
total = (indoorCamping + document.getElementsByName('Amount').value);
document.getElementsByName('Amount').value = total;
}

else{
return;
}
}
</script>
</head>
<body>

<p>Click the button to trigger a function.</p>

<input type="checkbox" name="fifty" value="indoor"/>

<label for="Amount">Amount <span class="req">*</span> <span 

id="constraint-300-label"></span></label><br />
                <input type="text" class="cat_textbox" id="Amount" name="Amount" />

<p id="demo"></p>

<button onclick="toggle()">Click me</button>

</body>
</html>
4

2 回答 2

1

文本输入的值最初始终是文本(字符串)。此值需要在添加之前显式转换为数字,否则它会连接文本。所以“20”会变成“5020”。

借用 mohkhan 的代码:

<script>
function toggle(checkbox){
    var indoorCamping = 50.00;
    var total = 0.00;
    if(checkbox.checked){
        total = (indoorCamping + document.getElementById('Amount').value * 1);
        document.getElementById('Amount').value = total;
    }
}
</script>

我乘以 1,这是将“20”转换为数字的一种方法。Number(x)parseInt(x)还有parseFloat(x)其他方式。

不过,我更喜欢使用对象变量amt

<script>
function toggle(checkbox) {
    var indoorCamping = 50.00;
    var total = 0.00;
    var amt = null;
    if (checkbox.checked) {
        amt = document.getElementById('Amount');
        total = (indoorCamping + amt.value * 1);
        amt.value = total;
    }
}
</script>
于 2013-07-28T01:37:01.270 回答
0

然后在复选框上添加点击事件。像这样...

<input type="checkbox" name="fifty" value="indoor" onclick="toggle(this);"/>

然后在你的脚本中......

<script>
function toggle(checkbox){
var indoorCamping = 50.00;
var total = 0.00;
if(checkbox.checked){
    total = (indoorCamping + document.getElementById('Amount').value);
    document.getElementById('Amount').value = total;
}
}
</script>
于 2013-07-28T00:42:45.043 回答