Переключить шоу / скрыть на основе нескольких переключателей - PullRequest
0 голосов
/ 30 декабря 2018

Я работаю над отображением определенного div, когда выбрано несколько переключателей.Я могу заставить его работать, когда у меня просто есть 1 условие (значение радио равно X), но мне нужно, чтобы оно "ЕСЛИ radio1 равно X, а radio2 равно A)

Я пробовал несколько способов, но этоткажется наиболее перспективным, поскольку мне не нужно скрывать все другие возможности, как это происходит с другими сценариями, которые я пробовал.

<script type="javascript">
$(function() {

/* Code that works for 1 condition (show div named 1A with FirstSelector value is 1) */

    $('input[name=FirstSelector]').change(function() {
      $("div[name=1]").toggle(this.value === "1")
    }).filter(":checked").change()

    $('input[name=FirstSelector]').change(function() {
      $("div[name=2]").toggle(this.value === "2")
    }).filter(":checked").change()

/* Code for multiple IFs that is not working */

    $('input[name=FirstSelector]').change(function() {
      $("div[name=1A]").toggle(this.value === "1" && 'input[name=SecondSelector]'.value === "A" )
    }).filter(":checked").change()

})
</script>

<html>
<p>
First choice
</p>
<input type="radio" name="FirstSelector" value="1">Option 1
<input type="radio" name="FirstSelector" value="2">Option 2


<p>
Second choice
</p>
<input type="radio" name="SecondSelector" value="A">Option A
<input type="radio" name="SecondSelector" value="B">Option B

<div name="1" class="hide">
This is the result of just Option 1
</div>

<div name="2" class="hide">
This is the result of just Option 2
</div>

<div name="1A" class="hide">
This is the result of 1 and A
</div>

<div name="1B" class="hide">
This is the result of 1 and B
</div>

<div name="2A" class="hide">
This is the result of 2 and A
</div>

<div name="2B" class="hide">
This is the result of 2 and B
</div>
</html>

http://jsfiddle.net/antonio1475/df7ra8eu/

Спасибо

Ответы [ 4 ]

0 голосов
/ 30 декабря 2018

При всей скромности вот самое простое решение:

$(function() {

  var Msg = {};

  Msg['1-'] = 'This is the result of just Option 1'
  Msg['2-'] = 'This is the result of just Option 2'
  Msg['-A'] = 'This is the result of just Option A'
  Msg['-B'] = 'This is the result of just Option B'
  Msg['1A'] = 'This is the result of Options 1 and A'
  Msg['1B'] = 'This is the result of Options 1 and B'
  Msg['2A'] = 'This is the result of Options 2 and A'
  Msg['2B'] = 'This is the result of Options 2 and B'
  
  $('input[name=FirstSelector]').change( CalcMsg );
  $('input[name=SecondSelector]').change( CalcMsg );

  function CalcMsg() {
    var Ref = $('input[name=FirstSelector]:checked').val() || '-';
      Ref += $('input[name=SecondSelector]:checked').val()  || '-';

    $('#Msg').text( Msg[Ref] ).removeClass( "hide" );
  }
})
.hide {display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>  First choice </p>
<label><input type="radio" name="FirstSelector" value="1">Option 1</label>
<label><input type="radio" name="FirstSelector" value="2">Option 2</label>

<p> Second choice </p>
<label><input type="radio" name="SecondSelector" value="A">Option A</label>
<label><input type="radio" name="SecondSelector" value="B">Option B</label>

<div id="Msg" class="hide">
  This is the result of ...
</div>
0 голосов
/ 30 декабря 2018

Вот изменение, которое я внес в код java-скрипта.

$('input[name=FirstSelector]').change(function() {
    var radioValue = $("input[name='SecondSelector']:checked").val();
    $("div[name=1A]").toggle(this.value === "1" && radioValue && radioValue === "A" )
}).filter(":checked").change()

Обновленная скрипта: http://jsfiddle.net/145tbqx0/

0 голосов
/ 30 декабря 2018

Есть несколько проблем с кодом.Первый шаг к упрощению - использовать одну и ту же логику для каждого изменения:

$('input').change(() => {
  const first = $('input[name=FirstSelector]:checked').val();
  const second = $('input[name=SecondSelector]:checked').val();
  $("div[name=1]").toggle(first === "1");
  $("div[name=2]").toggle(first === "2");
  $("div[name=1A]").toggle(first === "1" && second === "A");
  $("div[name=1B]").toggle(first === "1" && second === "B");
  $("div[name=2A]").toggle(first === "2" && second === "A");
  $("div[name=2B]").toggle(first === "2" && second === "B");
});
.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
First choice
</p>
<input type="radio" name="FirstSelector" value="1">Option 1
<input type="radio" name="FirstSelector" value="2">Option 2


<p>
Second choice
</p>
<input type="radio" name="SecondSelector" value="A">Option A
<input type="radio" name="SecondSelector" value="B">Option B

<div name="1" class="hide">
This is the result of just Option 1
</div>

<div name="2" class="hide">
This is the result of just Option 2
</div>

<div name="1A" class="hide">
This is the result of 1 and A
</div>

<div name="1B" class="hide">
This is the result of 1 and B
</div>

<div name="2A" class="hide">
This is the result of 2 and A
</div>

<div name="2B" class="hide">
This is the result of 2 and B
</div>
0 голосов
/ 30 декабря 2018

У вас много проблем с вашим кодом, но для решения этой простой проблемы, связанной с тем, что DIV не показывает, посмотрите на эту проблему, получите значение из радиогруппы, используя jquery

Эта строка...

  $("div[name=1A]").toggle(this.value === "1" && $('input[name=SecondSelector]').val() === "A" )

Вам не хватало селектора jQuery $('') вокруг input[name=SecondSelector].Также вы пытались получить value, когда вы должны были вызывать функцию val(), поскольку это радиогруппа.

Вот последний

$('input[name=FirstSelector]').change(function() {
    console.log($('input[name=SecondSelector]').val());
    $("div[name=1A]").toggle(this.value === "1" && $('input[name=SecondSelector]').val() === "A" )
}).filter(":checked").change()
...