Как правильно переключаться между div в веб-форме, используя это решение Javascript? - PullRequest
0 голосов
/ 27 апреля 2018

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

Работает правильно:

  1. Сначала ни один из div не отображается.

  2. Далее, div с ID = "repIfChoose" отображается, когда я нажимаю переключатель рядом с "Выбрать".

Не работает должным образом:

  1. Div с ID = "repIfAdd" не отображается, когда я нажимаю переключатель рядом с "Добавить".

  2. Как только div с ID = "repIfChoose" впервые отображается, ничего не происходит, когда я переключаюсь между переключателями впоследствии (то есть div repIfChoose не скрыт и div repIfAdd не отображается.)

Я знаю, что в JQuery могут быть более простые решения, но я бы предпочел сделать это в ванильном Javascript. Может ли кто-нибудь помочь мне решить две вышеуказанные ошибки и любые другие ошибки, которые вы можете заметить? Спасибо.

<!DOCTYPE html>
<html>

<head></head>

<body>

  <!--Radio button to switch between choose and add sales representative (choose default)-->
  Choose <input type="radio" onclick="repVisible();" id="chooseInput" name="repRadio">
  <br><br> Add <input type="radio" onclick="repVisible();" id="addInput" name="repRadio">

  <div class="form-group" id="repIfChoose" style="display:none">
    <label>Choose Sales Representative</label>
    <select name="SalesRep">
      <option value="" disabled selected>Choose Sales Representative</option>
      <option value="">Adam</option>
      <option value="">Bill</option>
      <option value="">Carl</option>
    </select>
  </div>

  <div class="form-group" id="repIfAdd" style="display:none">
    <label>Add Sales Representative</label>
    <input type="text" placeholder="e.g. Alex Branson" name="SalesRep">
  </div>

  <script>
    function repVisible() {
      if (document.getElementById('chooseInput').checked) {
        document.getElementById('repIfChoose').style.display = 'block';
        document.getElementById('repifAdd').style.display = 'none';
      }
      if (document.getElementById('addInput').checked) {
        document.getElementByID('repIfChoose').style.display = 'none';
        document.getElementByID('repIfAdd').style.display = 'block';
      }
    }
  </script>

</body>

</html>

Ответы [ 3 ]

0 голосов
/ 27 апреля 2018

Для достижения ожидаемого результата внесите следующие изменения, чтобы исправить ошибки синтаксиса и опечатки

  1. document.getElementById был использован с неправильным регистром, как getElementBy ID
  2. имя-идентификатора должно использоваться с тем же именем, что и с учетом регистра - должно быть repIfAdd вместо repifAdd

        function repVisible() {
            if (document.getElementById('chooseInput').checked) {
                document.getElementById('repIfChoose').style.display = 'block';
                document.getElementById('repIfAdd').style.display = 'none';
            }
            if (document.getElementById('addInput').checked){ 
                document.getElementById('repIfChoose').style.display = 'none';
                document.getElementById('repIfAdd').style.display = 'block';
            }   
        }
<head></head>
<body>

    <!--Radio button to switch between choose and add sales representative (choose default)-->
    Choose <input type="radio" onclick="repVisible();" id="chooseInput" name="repRadio">
    <br><br>
    Add <input type="radio" onclick="repVisible();" id="addInput" name="repRadio">

    <div class="form-group" id="repIfChoose" style="display:none">
        <label>Choose Sales Representative</label>
        <select name="SalesRep">
            <option value="" disabled selected>Choose Sales Representative</option>                         
            <option value="">Adam</option>
            <option value="">Bill</option>
            <option value="">Carl</option>
        </select>
    </div>

    <div class="form-group" id="repIfAdd" style="display:none">
        <label>Add Sales Representative</label>
        <input type="text" placeholder="e.g. Alex Branson" name="SalesRep">
    </div>              



</body>

пример кода - https://codepen.io/nagasai/pen/MGbPpv

0 голосов
/ 27 апреля 2018

У вас getElementById() было несколько прописных D; Более того, у ваших имен были проблемы с регистром. В противном случае работает:

https://jsfiddle.net/4qswkyLp/

Обязательно используйте консоль разработчика в своем браузере для отладки кода, для большинства браузеров легко использовать F12 на ПК.

0 голосов
/ 27 апреля 2018

У вас плохие опечатки ... исправьте их и дайте мне знать, если это то, что вы ищете.

<!DOCTYPE html>
<html>
<head></head>
<body>

    <!--Radio button to switch between choose and add sales representative (choose default)-->
    Choose <input type="radio" onclick="repVisible();" id="chooseInput" name="repRadio">
    <br><br>
    Add <input type="radio" onclick="repVisible();" id="addInput" name="repRadio">

    <div class="form-group" id="repIfChoose" style="display:none">
        <label>Choose Sales Representative</label>
        <select name="SalesRep">
            <option value="" disabled selected>Choose Sales Representative</option>                         
            <option value="">Adam</option>
            <option value="">Bill</option>
            <option value="">Carl</option>
        </select>
    </div>

    <div class="form-group" id="repIfAdd" style="display:none">
        <label>Add Sales Representative</label>
        <input type="text" placeholder="e.g. Alex Branson" name="SalesRep">
    </div>              

    <script>    
        function repVisible() {
            if (document.getElementById('chooseInput').checked) {
                document.getElementById('repIfChoose').style.display = 'block';
                document.getElementById('repIfAdd').style.display = 'none';
            }
            if  (document.getElementById('addInput').checked){ 
                document.getElementById('repIfChoose').style.display = 'none';
                document.getElementById('repIfAdd').style.display = 'block';
            }   
        }
    </script>

</body>
</html>
...