如何将复选框值传递给javascript函数

时间:2017-02-16 06:25:42

标签: javascript php

我的代码是:

<input type="checkbox" name="area" id="area" value="0">Some Text1</input>
<input type="checkbox" name="area" id="area" value="80">Some Text2</input>

和javascript代码

function calc(){var textValue1 = document.getElementById('quantity').value;
var textValue2 = document.getElementById('area').value;
document.getElementById('cost').value = textValue1 * textValue2 ; }

但它不起作用。

4 个答案:

答案 0 :(得分:0)

试试这个:

valueChange = function(item){
	alert(item.value);
}
<form name="form1" method="post" action=" insert_data.php">
    Delivery Location
    <input onChange="valueChange(this)" type="checkbox" name="area" id="area" value="0">Inside city </input>
    <input onChange="valueChange(this)" type="checkbox" name="area" id="area" value="80">Outside city </input>
    </form>

答案 1 :(得分:0)

使用JQuery的示例示例...

<!DOCTYPE html>
<html>
<head>
    <title></title>

    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

    <script type="text/javascript">
        $( document ).ready(function() {

            $( "#target" ).submit(function( event ) {
                $('input[name="vehicle"]:checked').each(function() {
                    console.log(this.value);
                });

                return false;
            });

        });
    </script>
</head>
<body>
    <form id='target' action="/action_page.php">
        <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
        <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

答案 2 :(得分:0)

问题是id属性应该是唯一的。在您的情况下,您有2个id="area"元素会混淆document.getElementById()方法。您可以使用选择器查询来实现您想要的效果。不需要其他库,例如jQuery。

这是一个有效的例子:

function calculate () {
  var selected = document.querySelector('[name="area"]:checked')
  
  if (!selected) {
    alert('Please select a value')
    return 
  }
  
  var quantity = 5 // you can get this from a different place
  
  alert('Final value: ' + selected.value * quantity)
 
}


document.getElementById('submit').addEventListener('click', calculate)
<form name="form1" method="post" action=" insert_data.php">
    Delivery Location
    <input type="checkbox" name="area" id="inside" value="0">Inside city </input>
    <input type="checkbox" name="area" id="outside" value="80">Outside city </input>
    <button id="submit">Calculate</button>
</form>

答案 3 :(得分:0)

在控制台中尝试以下JS代码。你可以根据你想要的事件使用它

var checkedValue = null; 
var inputElements = document.getElementsByName('area');
for(var i=0; inputElements[i]; ++i){
      if(inputElements[i].checked){
           checkedValue = inputElements[i].value;
           break;
      }
}