Подтвердить что ты не робот

JQuery показать скрыть Div на основе выбора значения

У меня есть список выбора со значениями "все" и "пользовательские". При выборе со значением "custom" должен появиться div с классом "resources", а если значение "all", он должен быть скрыт.

Форма это:

<div>
    <label>Privileges:</label>
    <select name="privileges" id="privileges" class="" onclick="craateUserJsObject.ShowPrivileges();">
        <option id="all" value="all">All</option>
        <option id="custom" value="custom">Custom</option>
    </select>
</div>
<div class="resources" style=" display: none;">resources</div>

И JavaScript для этого:

ShowPrivileges: function() {
    var Privileges = jQuery('#privileges');
    var select = this.value;
    Privileges.change(function() {
        if (select === 'custom') {
            $('.resources').show();
        }
    });
}

Как это должно выглядеть, чтобы работать? Извините, я знаю, что это должно быть просто, но я новичок во всем этом.

4b9b3361

Ответ 1

Вам нужно использовать метод val:

var Privileges = jQuery('#privileges');
var select = this.value;
Privileges.change(function () {
    if ($(this).val() == 'custom') {
        $('.resources').show();
    }
    else $('.resources').hide(); // hide div if value is not "custom"
});

http://jsfiddle.net/RWUdb/

Ответ 2

Privileges.on('change',function(){
    if($(this).val()=='custom'){
        $('.resources').show();
    }else{
        $('.resources').hide();
    }
})

Ответ 3

Вы хотите добавить обработчик событий:

$("#privileges").change(craateUserJsObject.ShowPrivileges);

Затем в рамках функции ShowPrivileges:

var val = $("#privileges").val();
if(val == "whatever")
    //do something
else
    //do something

Ответ 4

  $("#privileges").change(function(){
     var select=  $(this).val();
       if(select=='custom'){
          //some code
         }
    }); 

или

  var select=$('#privileges :selected').val()
    if(select=='custom'){
    //some code
  }

Ответ 5

Вы делаете это слишком сложно:

Сначала отпустите встроенный onclick. Поскольку вы используете jQuery, динамически присоединяйте обработчик.

<div>
    <label>Privileges:</label>
    <select name="privileges" id="privileges">
        <option id="all" value="all">All</option>
        <option id="custom" value="custom">Custom</option>
    </select>
</div>
<div class="resources" style=" display: none;">resources</div>

Во-вторых, не слушайте клик, а затем присоедините обработчик change. Прикрепите его непосредственно

<script>
jQuery('#privileges').on('change',function(){
    if(jQuery(this).val()=='custom'){
        jQuery('.resources').show();
    } else {
        jQuery('.resources').hide();
    }
});
</script>

Ответ 6

Вы можете очистить HTML, отбросив onClick и удалив идентификаторы из параметров.

HTML:

<div>
    <label>Privileges:</label>
    <select name="privileges" id="privileges">
        <option value="all">All</option>
        <option value="custom">Custom</option>
    </select>
</div>
<div class="resources" style=" display: none;">resources</div> 

И ваш JavaScript мог бы просто сделать это:

$('#privileges').on('change', function() {
        if($(this).val() === 'all') {
            $('.resources').hide();
        } else {
            $('.resources').show();
        }
 });

Ответ 7

Это можно сделать с помощью toggle() в качестве сокращения:

$('#privileges').change(function() {
  $('.resources').toggle($(this).val() == 'custom');
});

Если вы хотите переключить отображение при загрузке страницы, вы можете вызвать то же событие change(), например:

$('#privileges').change(function() {
  $('.resources').toggle($(this).val() == 'custom');
}).change();

$('#privileges').change(function() {
  $('.resources').toggle($(this).val() == 'custom');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <label>Privileges:</label>
  <select name="privileges" id="privileges">
    <option id="all" value="all">All</option>
    <option id="custom" value="custom">Custom</option>
  </select>
</div>
<div class="resources" style=" display: none;">resources</div>