检查是否选择了选项

时间:2019-10-18 07:30:16

标签: jquery

我正在使用HTML,CSS,PHP和jQuery在其CMS上为我的公司制作文件, 我使用几个select元素作为一个option作为返回原因。 隐藏某些内容,仅在选择某个选项时运行show()

jQuery代码:

// if option defective product is selected, vehicle information gets showed

$("select#ReasonReturn").change(function() {
  var data = $("select#ReasonReturn option:selected").val();
  if ($(this).val() === 'Defectiveproduct') {
    $("td[data-block=vehicle-information]").show();
    $("td[remark-block=remark-header]").text('Toelichting');
  }

});


// if option other is selected remark changes to other, namely / remark

$("select#ReasonReturn").change(function() {
  if ($(this).val() === 'Other') {
    $("td[remark-block=remark-header]").text('Anders, namelijk / Toelichting');
    $("td[data-block=vehicle-information]").hide();
  }

});

//if any other option is selected set to default

$("select#ReasonReturn").change(function() {
  if ($(this).val() != 'Other' && $(this).val() != 'Defectiveproduct') {
    $("td[remark-block=remark-header]").text('Toelichting');
    $("td[data-block=vehicle-information]").hide();
  }
}); 

您可以看到我当前正在使用change()事件来检测更改。 唯一的问题是,当我重新加载页面时,“缺陷产品”选项仍处于选中状态。什么也没发生,因为事件只会在更改时触发,而不是在选择时触发。

我的问题是:

是否有一种简单的方法可以在页面加载后直接检查所选值,而不是仅在更改时检查? 我希望我的问题很清楚,谢谢您的帮助!

PS:如有必要,我可以显示更多代码。

3 个答案:

答案 0 :(得分:0)

这应该为您完成页面刷新工作

@Column

答案 1 :(得分:0)

您可以在页面加载时检查选定的值。请尝试以下代码

$(document).ready(function(){
$("select#ReasonReturn option:selected").val();
});

答案 2 :(得分:0)

首先,您不需要注册多个change处理程序,只需使用if () {} else if(){}语句就可以使用一个更改事件处理程序进行操作。

第二,将所有代码放入DOM ready函数中,并在DOM准备就绪时调用change事件来完成工作。

  $(function(){

    $("select#ReasonReturn").change(function() {
      var data = $("select#ReasonReturn option:selected").val();

      if ($(this).val() === 'Defectiveproduct'){
        $("td[data-block=vehicle-information]").show();
        $("td[remark-block=remark-header]").text('Toelichting');
      }else if($(this).val() === 'Other') { 
        // if option other is selected remark changes to other, namely / remark
        $("td[remark-block=remark-header]").text('Anders, namelijk / Toelichting');
        $("td[data-block=vehicle-information]").hide();
      }else if ($(this).val() != 'Other' && $(this).val() != 'Defectiveproduct') {

        //if any other option is selected set to default
        $("td[remark-block=remark-header]").text('Toelichting');
        $("td[data-block=vehicle-information]").hide();
      }
    }).change();

  });