javascript - jquery 在单击单选按钮时添加和减去值

标签 javascript jquery

我正在尝试在用户单击单选按钮时添加和减去值。所有单选按钮都是根据数据库值动态创建的。

一个标题内可能有多个类别,但用户只能选择一个。当用户选择另一个选项时,我一直在减去该值。

如果你足够友善 ;),你可以在你的编辑器中检查这个粘贴(哦是的..在编程方面我是一个新手。)

任何解决方案或不同的方法将不胜感激。

谢谢...

代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
.active {
 background: #ccc;
}
.program {
 border:1px solid blue;
}
.program td, .program th {
 padding:10px;
 border:1px solid grey;
}
.grandTotal {
 width:200px;
 height:35px;
 font-size:18px;
 font-weight:bold;
 text-align:center;
 line-height:35px;
 background-color:#999;
 margin-top:35px;
}
</style>
</head>

<body>
<div class="program-box">
  <span>You can select or deselect the radio button</span>
  <h2>Heading1</h2>
  <table class="program" cellpadding="0" cellspacing="1">
    <tr>
      <th class="w-5"></th>
      <th class="w-35">Name</th>
      <th class="w-30">Location</th>
      <th class="w-10">#days</th>
      <th class="w-10">Price</th>
    </tr>
    <tr>
      <td><input name=cat1 value=3 id=3 type='radio' class='v'/></td>
      <td>categeory 1</td>
      <td>location1</td>
      <td>5</td>
      <td class="price1">100</td>
    </tr>
  </table>
  <h2>Heading2</h2>
  <table class="program" cellpadding="0" cellspacing="1">
    <tr>
      <th class="w-5"></th>
      <th class="w-35">Name</th>
      <th class="w-30">Location</th>
      <th class="w-10">#days</th>
      <th class="w-10">Price</th>
    </tr>
    <tr>
      <td><input name=cat2 value=1 id=1 type='radio' class='v'/></td>
      <td>category2</td>
      <td>location2</td>
      <td>4</td>
      <td class="price1">200</td>
    </tr>
    <tr>
      <td><input name=cat2 value=2 id=2 type='radio' class='v'/></td>
      <td>category2</td>
      <td>location3</td>
      <td>8</td>
      <td class="price1">150</td>
    </tr>
  </table>

  <div class="price">
    <div class="grandTotal">1800</div>
  </div>
</div>
</div>
<script type="text/javascript">

$(document).ready(function () {

  $("input[type='radio']").mousedown(function(e) {
                if ($(this).attr("checked") == true) {

                   setTimeout("$('input[id=" + $(this).attr('id') + "]').removeAttr('checked');", 200);
       }
                else {
                    return true
                }
            });


});

 $(".v").click(function() {


  $(this).toggleClass("active");


  $(this).closest('.program').find('.v').not(this).removeClass('active');


  var actPrice = 1800; // default 1800
  actPrice = parseInt(actPrice); // convert this to integer


  var isSet = $(this).hasClass("active");


  var grandTotal=$(".grandTotal").text();

  if (grandTotal=="")
  {
   //alert('no total till now');
   var grandTotal=0;
  } else {
   grandTotal=parseInt(grandTotal);
   //alert(grandTotal);
  }


  var div=parseInt($(this).closest('tr').find(".price1").text());

  if(isSet)
  {
   if(grandTotal>0){
    var total = grandTotal+div;
   } else {
    var total = actPrice+div;
   }
   //alert(total);
   $(".grandTotal").html(total);
  } else 
  {
   var div2 = parseInt($(this).closest('tr').find(".price1").text());
   var newTotal = grandTotal-div2;
   $(".grandTotal").html(newTotal);

  }


 });


</script>
</div>
</body>
</html>

最佳答案

你非常接近!我稍微修改了你的代码并清理了一些东西,但你几乎就在那里:

$(document).ready(function() {
    $("input[type='radio']").mousedown(function(e) {
        var self = this;
        /* Use 'checked' property instead of wrapping in jQuery object */
        if (self.checked) {
            /* Use setTimeout with a function instead of JS string */
            setTimeout(function() {
                self.checked = false;
            }, 200);
        }
        else {
            return true;
        }
    });
    /* Assign click handler inside document.ready: */
    $(".v").click(function() {
        /* Cache selectors that are used over and over: */
        var $this = $(this);
        var $grandTotalContainer = $(".grandTotal");

        /* Call parseInt with radix parameter: */
        var grandTotal = parseInt($grandTotalContainer.text(), 10);
        var price =
            parseInt($this.closest('tr').find(".price1").text(), 10);
        var siblingAmounts = 0;
        var name = $this.attr("name");

        /* Find prices of items in the same "group": */   
        $("input[name='" + name + "'].active")
            .not($this)
            .each(function() {
                siblingAmounts +=
                    parseInt($(this).closest("tr").find(".price1").text(), 10);
            });

        $this.toggleClass("active");
        $("input[name='" + name + "']").not($this).removeClass("active");

        if ($this.hasClass("active")) {
            grandTotal -= siblingAmounts;
            grandTotal += price;
        }
        else {
            grandTotal -= price;
        }
        $grandTotalContainer.html(grandTotal);
    });
});

注意事项:

  • 使用 JavaScript 字符串而不是函数调用 setInterval 被认为是不好的做法,因为它会调用 eval() which can cause problems .
  • 直接访问有效的 DOM 元素属性优于将 this 包装在 jQuery 对象中并使用 jQuery 方法访问这些属性。
  • 调用 parseInt强烈建议使用 radix 参数,否则 JavaScript 会尝试采用基数。
  • 我删除了使用默认总计的代码,只解析了总计 div 中的值。
  • 我使用 attribute equals selector 选择被点击的 input 的 sibling
  • 确保并缓存您反复使用的 jQuery 结果。如果缓存查询结果,则可以避免执行 jQuery 函数的开销。
  • 您不应将整数用作 HTML 元素的 id,因为它们在 HTML 4.01 规范下是无效的。

这是一个工作示例:http://jsfiddle.net/andrewwhitaker/8Atf8/1/

希望对您有所帮助!

关于javascript - jquery 在单击单选按钮时添加和减去值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4842608/

相关文章:

javascript - 在 <div> 元素上如何确定 href 和 onClick 调用的优先级?

javascript - 如何将复选框的值传递给 MVC5 中的 ActionResult?

Javascript + Codeigniter - 仅显示输出

javascript - iframe 内的按钮单击功能会更改该父 iframe 的高度(跨域)

javascript - 删除 AJAX 响应中的空白

javascript - 奇数数组之和 - JS

javascript - 是否有跨浏览器的方式来设置第三方(跨域)异步 Dom 注入(inject)脚本的超时?

javascript - 将 id 属性分配给 li 不起作用

javascript - 使用 javascript 将值相乘

javascript - ASP.NET MVC 中的按钮提交