javascript - 当选择表单中的七个值之一时尝试显示复选框

标签 javascript jquery

如果选择了标有 data-auth="need-purchase-auth"的七个职位之一,则尝试显示 #authorized_to_purchase_box。

不知道为什么它不起作用。请批评/让我知道是否有更好的方法来做到这一点。

HTML:

<select name="job_title" id="job_title" onchange='showAuthBox(this);'>
    <option selected disabled hidden style='display: none' value=''></option>
    <option id="Superintendent" value="Superintendent">Superintendent</option>
    <option id="Assistant-Superintendent" value="Assistant Superintendent">Assistant Superintendent</option>
    <option id="Principal" value="Principal">Principal</option>
    <option id="Vice-Principal" value="Vice Principal">Vice Principal</option>
    <option id="Counselor" data-auth="need-purchase-auth" value="Counselor">Counselor</option>
    <option id="Testing-Coordinator" data-auth="need-purchase-auth" value="Testing Coordinator">Testing Coordinator</option>
    <option id="Curriculum-Director" data-auth="need-purchase-auth" value="Curriculum Director">Curriculum Director</option>
    <option id="Administrator" data-auth="need-purchase-auth" value="Administrator">Administrator</option>
    <option id="Teacher" data-auth="need-purchase-auth" value="Teacher">Teacher</option>
    <option id="Parent" data-auth="need-purchase-auth" value="Parent">Parent</option>
    <option id="Student" data-auth="need-purchase-auth" value="Student">Student</option>
</select>

Jquery:

function showAuthBox(val) {
    alert(val.dataset.auth);
    if(val.dataset.auth == "need-purchase-auth") {
        $('#authorized_to_purchase_box').css("display", "block");
    } else {
        $('#authorized_to_purchase_box').css("display", "none");
    }
}

最佳答案

所以,我稍微修改了代码以使用 jQuery 的更改事件。

这是代码:

$("#job_title").change(function() {
  var auth = $(this).children(":selected").data('auth');
  if (auth == 'need-purchase-auth') {
    $("#authorized_to_purchase").show();
  } else {
    $("#authorized_to_purchase").hide();
  }
});

基本上,我们在选择框上放置了一个事件监听器,以便在您选择不同的选项时触发。然后,我们必须通过检查哪个选项具有 :selected 属性来找到选择了哪个选项。然后,我们使用 attr() 方法获取 data-auth 属性值。最后,您只需检查 data-auth 值是否等于您要查找的值。如果是这样,请显示该复选框。如果没有,请将其隐藏。如果您需要对我的代码进行进一步说明,请告诉我。

关于javascript - 当选择表单中的七个值之一时尝试显示复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40642939/

相关文章:

jquery - 华丽的弹出窗口 : How to add a custom close button inside a popup form?

javascript - iOS 上 Cordova inAppBrowser 中的executeScript执行不一致

javascript - 如何在 View 中使用 Angular 常量?

javascript - 如何检查 JASMINE (JS) 框架中点击时显示特定 div

javascript - js脚本一直执行onchange

jquery - 切换样式表

javascript - slideDown() slideUp() 反转

javascript - 使用 Javascript 确定 Flash SWF 影片何时结束

javascript - 如何将文本添加到图像 anchor ?

javascript - 如何在 jquery 中为对象键创建一个工作变量以避免额外的代码