如何将单选按钮放入嵌套条件中

how to work radio buttons into a nesting conditional

本文关键字:嵌套 条件 单选按钮      更新时间:2023-09-26

所以我学习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改为else if,并使用了整理。

如果您在检查是否检查了radio时遇到问题,您可以使用它,它比您当前使用的要干净得多,也更直观。

if($("#id1").is(":checked")){
    // do something
}else if($("#id2").is(":checked")){
    // do something else
}

希望这能有所帮助。

格式化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]
    }
  }
});

修改了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>

我评论了你的验证,因为我在我的部件上收到了一个错误

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

对于初学者来说,条件语句(if/else语句)过于复杂了。

根据你想要完成的行为将其分解,并以同样的方式说出功能。

如果你(或其他人)需要在6个月后再看一遍,它会更容易阅读。

信用良好?

有固定工作吗?

贷款批准了吗?

薪水不错吗?

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

我还合并了单独的表格来清理一下。我将验证更改为HTML5的required,type=number,min和max,因为.validate()插件不在其中。依靠HTML5和jQuerysubmit()事件来验证表单。

如果你感兴趣,可以了解更多关于HTML5验证和模式的信息:http://www.w3.org/html/wg/drafts/html/master/forms.html#the-模式属性您甚至可以使用css:valid和:invalid伪类对其进行样式设置

对于一个薪水不错的求职者,我很难理解你的逻辑。因此,我将其设置为批准此人是否有良好的薪水、良好的信用或长期工作。

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

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;
});