ПОЖАЛУЙСТА, помогите мне .. RE: * ФОРМОВЫЕ ПОЛЯ * Я хочу скрыть () мое "type = text box", пока не будет выбрана опция Other в выпадающем меню - PullRequest
0 голосов
/ 12 января 2020
**HTML**   
```<fieldset> 

        <legend>Basic Info</legend>

        <label for="name">Name:</label>
        <input type="text" id="name" name="user-name">

        <label for="mail">Email:</label>
        <input type="email" id="mail" name="user-email">

       <label for="title">Job Role</label>
        <select id="title" name="user-title">
          <option value="full-stack js developer">Full Stack JavaScript Developer</option>
          <option value="front-end developer">Front End Developer</option>
          <option value="back-end developer">Back End Developer</option>
          <option value="designer">Designer</option>          
          <option value="student">Student</option>
          <option value="other">Other</option>
      </select> 

      <input type="text" id="other-title" placeholder="Your Job Role"> 

    </fieldset>```

Я ПОПЫТАЮСЬ:
ВЫПОЛНЕНО // Предотвратить запуск кода JQuery до завершения загрузки документа. ВЫПОЛНЕНО // Фокус 1-го поля по умолчанию

ЭТО МОЙ ВОПРОС: // Скрываем текстовое поле до тех пор, пока «Роль» не будет выбрано из вакансии. //

**JS**
```$(document).ready(function(){
    $('form:first *:input[type!=hidden]:first').focus();
    $("Other").change(function(){
        if($(this).val() == "Other")
    {
        $("#other-title").show();
    }
    else
    {
        $("#other-title").hide();
    }
        });
                  $("#other-title").hide();
}); ```

Ответы [ 4 ]

1 голос
/ 12 января 2020

Две основные проблемы с исходным кодом:

1 - Используя неправильный селектор для события onchange, замените "Other" на "#title"

2 - Вы проверяли, значение равно "Other" вместо "other", которое есть в вашем HTML. Будьте внимательны, сравнение строк чувствительно к регистру!

Ниже приведен рабочий фрагмент после применения этих двух изменений:

$(document).ready(function(){
  $('form:first *:input[type!=hidden]:first').focus();
    $("#title").change(function(){
      if($(this).val() == "other") {
        $("#other-title").show();
      }
      else {
        $("#other-title").hide();
      }
    });
  $("#other-title").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset> 

        <legend>Basic Info</legend>

        <label for="name">Name:</label>
        <input type="text" id="name" name="user-name">

        <label for="mail">Email:</label>
        <input type="email" id="mail" name="user-email">

       <label for="title">Job Role</label>
        <select id="title" name="user-title">
          <option value="full-stack js developer">Full Stack JavaScript Developer</option>
          <option value="front-end developer">Front End Developer</option>
          <option value="back-end developer">Back End Developer</option>
          <option value="designer">Designer</option>          
          <option value="student">Student</option>
          <option value="other">Other</option>
      </select> 

      <input type="text" id="other-title" placeholder="Your Job Role"> 

    </fieldset>
1 голос
/ 12 января 2020

Я думаю, что вы использовали значение в селекторе jquery.

$("Other").change(function(){
     if($(this).val() == "Other")

замените эту строку на строки ниже

$("#title").change(function(){
      if($(this).children('option:selected').val() == "other")

// Вы получите выбранное значение в выпадающий с помощью приведенного ниже кода.

$('#ELEMENT').children('option:selected').val()
0 голосов
/ 12 января 2020

ЭТО ТО, ЧТО РАБОТАЕТ Спасибо ВСЕМ :-) Анис Р. On Point вот что помогло


    $('#title').change(function(){
    if($('#title').val() == "other")
{
    $('#other-title').show();
}
else
{
    $('#other-title').hide();
}
    });
              $('#other-title').hide();
});```
0 голосов
/ 12 января 2020

Изучив ваш вопрос, я обнаружил, что значение, указанное в поле выбора для опции "прочее", написано строчными буквами, а значение, которое вы сравниваете в jquery коде изменения, - в предложении.

А также неверно указан идентификатор элемента. Вам нужно изменить его на «title»

<option value="Other">Other</option>

$("#title").change(function(){
   if($(this).val() == "Other")
   {
       $("#other-title").show();
   }
   else
   {
       $("#other-title").hide();
   }
 });

Надеюсь, это вам поможет.

...