如何将单选按钮用于嵌套条件

时间:2014-10-22 02:50:00

标签: javascript jquery

所以我学习jQuery atm,并且必须根据选择制作贷款计算器,以及验证企业,然后输出结果。

我想确保你们知道我想要做什么,所以我在这里有一个应该发生的事情的流程图: http://i59.tinypic.com/8z02sh.jpg

显示应该发生的事情。问题是我不知道如何做到这一点是Jquery。我在网上找到的单选按钮选择器(通过这里的另一个问题)似乎很奇怪,我不知道如何使用它。我可以使用javascript做到这一点,但后来我不会学习任何东西。所以到目前为止,这是我的代码。

另外,我在我的JS的第14行(JSfiddle第14行)中得到错误,我无法弄清楚它是什么。

JSfiddle:http://jsfiddle.net/keup5vaw/1/

HTML:

<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">

</form>


<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="0">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="0">
<label for="under1">Under 600</label></p>
</form>


<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="0">
<label for="job2">I have worked at my current job less than 1 year.</label><br>

</form>

<input type="button" id="check" name="check" value="Check">
<div id="message"></div>

和JS -

  $('#check').click(function () {
    var salary;
    var isValid = $('#salaryForm').validate().form();
    // if validation passes, display a message
    if (isValid) {
        var salary = Number($('#salary').val());

        if (salary < 40000) {
            if ($('input[name=radio]:checked').length > 0) {
                if ($('input[name=job1]:checked').length > 0) {
                    $('#message').html("Loan Approved.")
                } else if {
                    $('#message').html("Loan Denied.")
                } else if {
                    $('#message').html("Loan Denied.")
                }
            }
        } else(salary >= 40000) {
            if ($('input[name=radio]:checked').length > 0) {
                if ($('input[name=job1]:checked').length > 0) {
                    $('#message').html("Loan Approved.")
                } else if {
                    if ($('input[name=job1]:checked').length > 0) $('#message').html("Loan Approved.")
                } else if {
                    $('#message').html("Loan Denied.")
                }
            }
        }
    });


// form validation
$('#salaryForm').validate({
    rules: {
        salary: {
            required: true,
            digits: true,
            range: [1, 1000000]
        }
    }

});

按照惯例,提前谢谢你,你们真棒。

编辑:在Mottie帮助之后更新了(谢谢!),仍然没有看到第14行出错了,但是将其他内容更改为else,并使用了整理。

4 个答案:

答案 0 :(得分:0)

如果检查radio是否检查有问题,您可以使用它比目前使用的更清洁,更直观。

if($("#id1").is(":checked")){

    // do something

}else if($("#id2").is(":checked")){

    // do something else

}

希望这有帮助。

答案 1 :(得分:0)

格式化javascript非常重要,可以为自己捕获这些类型的语法错误。正如@Mottie所说,使用某种javascript格式化程序来解决这些问题。整理http://jsbeautifier.org/是更好的开始。这是正确的代码

$('#check').click(function()
{
  var salary;
  var isValid = $('#salaryForm').validate().form();
  // if validation passes, display a message
  if (isValid)
  {
    var salary = Number($('#salary').val());

    if (salary < 40000)
    {
      if ($('input[name=radio]:checked').length > 0)
      {
        if ($('input[name=job1]:checked').length > 0)
        {
          $('#message').html("Loan Approved.")
        }
        else
        {
          $('#message').html("Loan Denied.")
        }
      }
      else
      {
        $('#message').html("Loan Denied.")
      }
    }
    else if (salary >= 40000)
    {
      if ($('input[name=radio]:checked').length > 0)
      {
        if ($('input[name=job1]:checked').length > 0)
        {
          $('#message').html("Loan Approved.")
        }
        else
        {
          if ($('input[name=job1]:checked').length > 0)
            $('#message').html("Loan Approved.")
        }
      }else
        {
          $('#message').html("Loan Denied.")
        }
      }
    }
});


// form validation
$('#salaryForm').validate(
{
  rules:
  {
    salary:
    {
      required: true,
      digits: true,
      range: [1, 1000000]
    }
  }

});

答案 2 :(得分:0)

修改你的jquery

http://jsfiddle.net/cvynLaqf/

 $('#check').click(function(){
        var salary;
        //var isValid = $('#salaryForm').validate().form();
        var isValid = true;
        // if validation passes, display a message
        if (isValid){
            var salary = Number($('#salary').val());
			
            if (salary < 40000){
                if ($('input[type=radio]:checked').length > 0){
                    if ($('input[value=over1]:checked').length > 0) {
                        //if over 600 do this
                        if ($('input[id=job1]:checked').length > 0)
                            $('#message').html("Loan Approved.");
                        else
                            $('#message').html("Loan Denied.");
                        }
                    else {
                        $('#message').html("Loan Denied.");}
                
                }
                else {
                    $('#message').html("Loan Denied.");

                }
        } else if( salary >= 40000){
            if ($('input[type=radio]:checked').length > 0){
                if ($('input[value=over1]:checked').length > 0) {
                    //over 600 do this
                    $('#message').html("Loan Approved.");}
                else {
                    //under 600 do this
                    if ($('input[id=job1]:checked').length > 0)
                        $('#message').html("Loan Approved.");
                    else
                        $('#message').html("Loan Denied.");
                }
            }
            else {
                $('#message').html("Loan Denied.");}
        }
    }
    });
	
	
    // form validation
    //$('#salaryForm').validate({
    //    rules: {
    //        salary: {
    //            required: true,
    //            digits: true,
    //            range: [1, 1000000]
    //        }
    //    }
	
    //});
<h1>Loan Calc</h1>
<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0)">
<label for="salary">Enter your annual salary</label>
<input type="text" name="salary" id="salary">

</form>


<form id="creditform" name="creditForm" method="Post" action="javascript:void(0)">
<p>Please select your Credit Score</p>
<p><input type="radio" name="radio" id="over1" value="over1">
<label for="over1">Over 600</label></p>
<p><input checked type="radio" name="radio" id="under1" value="under1">
<label for="under1">Under 600</label></p>
</form>


<p> How long have you worked at your current job? </p>
<input class="job" id="job1" name="job" type="radio" value="0">
<label for="job1">I have worked at my current job over 1 year.</label><br>
<br/>
<input checked class="job" id="job2" name="job" type="radio" value="1">
<label for="job2">I have worked at my current job less than 1 year.</label><br>

</form>

<input type="button" id="check" name="check" value="Check">
<div id="message"></div>

我注释了你的验证,因为我犯了错误

答案 3 :(得分:0)

尽管答案已经被接受,但我想我会发布一个更新的脚本,因为你刚开始学习jQuery以帮助你进一步提高。

你可能会让初学者的条件(if / else语句)变得复杂。

根据您想要完成的行为对其进行细分,并以同样的方式说明功能。

如果你(或其他人)需要在6个月内再次查看它,那么阅读会更容易。

有良好的信誉吗?

有工作吗?

贷款是否获批?

薪水好吗?

这是重写的功能小提琴。 http://jsfiddle.net/q3xpsLmL/

我还合并了各个表格以清理一下。我将验证更改为HTML 5的必需,type = number,min和max,因为.validate()插件不在小提琴中。 依靠HTML 5和jQuery submit()事件来验证表单。

如果您感兴趣,请参阅有关HTML 5验证和模式的更多信息: http://www.w3.org/html/wg/drafts/html/master/forms.html#the-pattern-attribute 您甚至可以使用css:valid和:invalid pseudo-classes

来设置样式

我很难为薪水很高的申请人解释你的逻辑。因此,如果这个人有良好的工资和良好的信誉或长期工作,我会批准。

如果您对此有疑问,请添加评论。

<强> HTML

<h1>Loan Calc</h1>

<form id="salaryForm" name="salaryForm2" method="Post" action="javascript:void(0);">
    <label for="salary">Enter your annual salary</label>
    <input id="salary" type="number" name="salary" min="0" max="1000000000" required>

    <p>Please select your Credit Score</p>
    <p>
        <input type="radio" name="radio" id="over1" value="over1">
        <label for="over1">Over 600</label>
    </p>
    <p>
        <input checked type="radio" name="radio" id="under1" value="under1">
        <label for="under1">Under 600</label>
    </p>
    <p>How long have you worked at your current job?</p>
    <input class="job" id="job1" name="job" type="radio" value="0">
    <label for="job1">I have worked at my current job over 1 year.</label>
    <br>
    <br/>
    <input checked class="job" id="job2" name="job" type="radio" value="1">
    <label for="job2">I have worked at my current job less than 1 year.</label>
    <br>
    <button type="submit" id="check" name="check">Check</button>
</form>
<div id="message"></div>

<强>的JavaScript

//use strict to ensure variables are defined and to prevent collisions
"use strict";

//define DOM elements so events do not need refind the element.
var salryForm = $('#salaryForm');
var salaryElement = $('#salary');
var messageElement = $('#message');
var radioButtons = $('input[type=radio]');
var goodCredit = radioButtons.filter('[name=radio][value=over1]');
var standingJob = radioButtons.filter('[name=job][value=0]');

var isLoanApproved = function(salary){
    //always be pecimistic and decline unless all conditions are met
    var result = false;
    var hasGoodCredit = goodCredit.is(':checked');
    var hasStandingJob = standingJob.is(':checked');
    var hasGoodSalary = (salary >= 40000);
    /*
     * if applicant doesn't have a good salary 
     *  they have to have good credit and standing job to be approved
     */
    if (!hasGoodSalary && hasGoodCredit && hasStandingJob) {        
        result = true;
    /**
     * otherwise if applicant does have a good salary
     * they only need to have either good credit or standing job to be approved
     */
    } else if(hasGoodSalary && (hasGoodCredit || hasStandingJob)) {
        result = true;
    }
    return result;
};

/**
 * track on submit rather than click so you can catch "<enter>" key presses as well
 */
salryForm.submit(function(e) {
    var salary = salaryElement.val();
    messageElement.html('Loan ' + (isLoanApproved(salary) ? 'Approved' : 'Denied'));
    return false;
});