用JavaScript显示表单中多个条件的文本

Displaying text with JavaScript from multiple conditions in form

本文关键字:条件 文本 JavaScript 显示 表单      更新时间:2023-09-26

在这个问题中,我想根据表单中选择的选项组合显示一些HTML文本。例如,在本例中,如果选择拼写作为子类别,并选择"更深入"(相当于"a"等级)作为性能等级,我希望显示一些文本。我在Rails form_for中开发了这个表单,但在浏览器中显示了呈现的表单。

<form class="new_english_grade" id="new_english_grade" action="/english_grades" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="VTtOS/86shuyQPW6/HfaduffmQiVXLiJb06IQp7+56LM8cD8KRnD3qLGbQBit4OuAIc92MYbFpPObR6ePYmY1g==" />
      <div class="field">
        <label for="english_grade_subcategory">Subcategory</label>
        <select name="english_grade[subcategory]" id="english_grade_subcategory"><option value="Spelling">Spelling</option>
    <option value="Reading">Reading</option>
    <option value="Writing">Writing</option></select>
      </div>
      <div class="field">
        <label for="english_grade_performance_grade">Performance grade</label>
        <select name="english_grade[performance_grade]" id="english_grade_performance_grade"><option value="Not-started">Not-started</option>
    <option value="Working-towards">Working-towards</option>
    <option value="Working-at">Working-at</option>
        <option value="Greater-depth">Greater-depth</option></select>
      </div>
</form>

我想显示的文本例如:

<div id = "spelling_greater_depth">
  This text is displayed only if 'spelling' and 'greater-depth' are selected in options
</div>

我最初设置我的CSS为:

#spelling_greater_depth
{
  display: none;
}

我的JavaScript还没有真正工作,所以我没有包括它,但我试图实现它使用这个:

我想这可能足够让你开始https://jsfiddle.net/sxh0n7d1/37/

但是这个问题很难回答,你能澄清你的问题吗?或者如果答案接近的话,你能给出反馈吗?

 $('select[name="english_grade"]').change(function () {
  $('#spelling_working_at').css("display","none");
  console.log($(this).val());
  var fieldToShow = $(this).val();
  $("#" + fieldToShow).css("display","block");
});