簡體   English   中英

如何從 html 中的復選框表單中獲取值?

[英]how can I get the value from a checkbox form in html?

我要寫一個頁面,允許用戶點擊項目的復選框,然后計算它的總量

但是我發現我無法從選中的復選框中獲取元素。 我如何返回該復選框的值

這是我的代碼:

function calculate(){
if(document.forms["listForm"].getElementsByTagName("item1").checked==true)
    prize1 = document.forms["listForm"].getElementsByTagName("item1Q").value * document.forms["listForm"].getElementsByTagName("item1").value
total = prize1
alert("The total is "+total)
}

 <form action="" id="listForm" >
<table border="1" >
  <tr> 
    <td style="text-align: center; width: 500px"><b>Books</b></td>
    <td style="text-align: center; width: 50px"><b>Quantity</b></td>
  </tr>
  <tr> 
    <td><input type="checkbox" name="item1" value="19.95" />
      XHTML Basic, $19.95</td>
    <td><input type="text" name="item1Q" value="0" size="2" maxlength="2" /></td>

缺少表單的 name 屬性。

像這樣定義

<form action="" id="listForm" name="listForm" >

定義JS:

function calculate() {
        if (document.forms["listForm"]["item1"].checked == true)
            prize1 = document.forms["listForm"]["item1Q"].value * document.forms["listForm"]["item1"].value
        total = prize1
        alert("The total is " + total)
    }
function calculate(){
if(document.forms["listForm"]["item1"].checked=true)

var prize1 = Number(document.forms["listForm"]["item1Q"].value) *       Number(document.forms["listForm"] ["item1"].value)
var total = prize1;
alert("The total is "+total);
}


<form action="" id="listForm" >
<table border="1" >
  <tr> 
<td style="text-align: center; width: 500px"><b>Books</b></td>
<td style="text-align: center; width: 50px"><b>Quantity</b></td>
</tr>
<tr> 
<td><input type="checkbox" name="item1" value="19.95"  onchange="calculate()"/>
  XHTML Basic, $19.95</td>
<td><input type="text" name="item1Q" value="2" size="2" maxlength="2" />     </td>

使用 jQuery 而不是 Javascript 將使代碼更具可讀性和可管理性。 如果這對您可行,請嘗試以下代碼:

https://jsfiddle.net/6q3o6ghn/

<script>
  $(document).ready(function(){
  $('input[name=item1]').on('change',function(){

   if($(this).is(':checked') == true) {
     calculate($(this).val());
    }
  });

  });
  function calculate(_value) {
        prize1 =  $('input[name=item1Q]').val() * _value;
        total = prize1
        alert("The total is " + total)
    }

</script>

 <form action="" name="listForm" id="listForm" >
    <table border="1" >
      <tr> 
        <td style="text-align: center; width: 500px"><b>Books</b></td>
        <td style="text-align: center; width: 50px"><b>Quantity</b></td>
      </tr>
      <tr> 
        <td><input type="checkbox" name="item1" value="19.95"/>
          XHTML Basic, $19.95</td>
        <td><input type="text" name="item1Q" value="0" size="2" maxlength="2" /></td></tr>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM