2014-11-14 85 views
1

我是编码新手(试图学习),我无法弄清楚如何获取函数外的复选框值。功能之外的复选框变量

的Javascript:

$(document).ready(function() { 

    var quantity= parseInt($('#phones').val()); 

    $("#check1 input:checkbox").change(function() { 
     var feature = 0; 
     $("#check1 input:checkbox").each(function() { 
      if ($(this).is(':checked')) { 
       feature += parseInt($(this).prop('value')); 
      } 
     }); 

    }); 

    var grand = feature * (quantity * Number ('0.1')) 

    var total = quantity + grand 

}); 

HTML:

<input id="phones" type="numerical" value="0" style="text-align: right"/> 

<div id="check1"> 

<input type="checkbox" value="1" /> 
+0

你是什么意思是什么呢? – OnlyMAJ 2014-11-14 16:29:19

+0

您无法在事件处理程序中保留所有变量和数学的任何特殊原因? – melancia 2014-11-14 16:29:29

+0

有多个复选框,每个复选框的默认值为0,当它被选中时= 1.复选框的值乘以一个方程(每个复选框有不同的方程),所有复选框的结果和产品的数量作为总计加起来。 – 2014-11-14 16:35:14

回答

0
function getResult(feature, phones) { 
    if (feature <= 0 || phones <= 0) { 
    return 'Error...., enter the number of phones and check some checkbox'; 
    } 

    return (feature * (+phones * 0.1)) + +phones; 
} 

function getFeature() { 
    var feature = 0; 

    $('#check1 input:checkbox:checked').each(function() { 
    feature += +$(this).prop('value') || 1; 
    }); 

    return feature; 
} 

$(document).ready(function() { 
    var $phones = $('#phones'), 
     $result = $('#result'); 

    $("#check1 input:checkbox").change(function() { 
    $result.html(getResult(getFeature(), $phones.val())); 
    }); 

    $("#phones").keyup(function() { 
    $result.html(getResult(getFeature(), $phones.val())); 
    }); 
}); 

演示:http://jsbin.com/hivilu/2/