2013-04-22 6 views
8

У меня есть инструкция if-else, которая дала мне странный отклик ... всякий раз, когда я выбираю «вывод» сначала, ничто другое после этого не может появиться ... FYI, я использую multi select, поэтому я могу выбрать и показать как можно больше как я хочу.Как сделать случай переключения для jQuery?

$('#outputText').hide(); 
    $('#armCB').hide(); 
    $('#outputCB').hide(); 
    $('#zoneText').hide(); 
    $('#counterText').hide(); 
    $('#flagText').hide(); 
    $('#sensorText').hide(); 

('#select-choice-1').change(function(){ 
     if ($('#output').is(':selected')){ 
      $('#outputText').show(); 
     } 
     else if ($('#arm').is(':selected')){ 
      $('#armCB').show(); 
     } 
     else if ($('#zone').is(':selected')){ 
      $('#zoneText').show(); 
     } 
     else if ($('#counter').is(':selected')){ 
      $('#counterText').show(); 
     } 
     else if ($('#flag').is(':selected')){ 
      $('#flagText').show(); 
     } 
     else if ($('#sensor').is(':selected')){ 
      $('#sensorText').show(); 
     } 
     else{ 
      $('#outputText').hide(); 
      $('#armCB').hide(); 
      $('#zoneText').hide(); 
      $('#counterText').hide(); 
      $('#flagText').hide(); 
      $('#sensorText').hide(); 

     } 

Есть ли ошибка в инструкции if-else? или я должен использовать оператор case switch здесь? Если да, то как мне это сделать?

HTML:

<div id="display" style=" clear:both"> 
     <div class="left" style="float:left; width:48%"> 
     <div data-role="fieldcontain"> 
      <label for="select-choice-1" class="select">Select Category</label> 
      <select name="select-choice-1" id="select-choice-1" data-native-menu="false" data-mini="true" multiple="multiple" size="2"> 

       <option value="arm" id="arm">Arm</option> 
       <option value="zone" id="zone">Zone Input</option> 
       <option value="output" id="output">Output</option> 
       <option value="counter" id="counter">Counter</option> 
       <option value="flag" id="flag">Flag</option> 
       <option value="sensor" id="sensor">Sensor</option> 
      </select> 
     </div> 



     </div> 
     <div class="right" style=" float: right; width:48%"> 
      <div id="armCB"> 
       <fieldset data-role="controlgroup"> 
        <legend>Unit</legend> 
        <input type="checkbox" class="CB" name="armCB_1" id="armCB_1" class="custom" data-mini="true" /> 
        <label for="armCB_1">Arming Status</label> 
       </fieldset> 
      </div> 

      <div id="outputText"> 
       <p> Please enter an Output number and press "Add" button: </p> 
       <input style="background: white; color: black;" type="text" id="outputTextInput" value=""> 
       <input type="submit" id="outputAdd" value="Add"/> 
       <input type="submit" id="outputRemove" value="Remove"/> 
      </div> 
      <div id="zoneText"> 
       <p> Please enter a Zone number and press "Add" button: </p> 
       <input style="background: white; color: black;" type="text" id="zoneTextInput" value=""> 
       <input type="submit" id="zoneAdd" value="Add"/> 
       <input type="submit" id="zoneRemove" value="Remove"/> 
      </div> 
      <div id="counterText"> 
       <p> Please enter a counter number and press "Add" button: </p> 
       <input style="background: white; color: black;" type="text" id="counterTextInput" value=""> 
       <input type="submit" id="counterAdd" value="Add"/> 
       <input type="submit" id="counterRemove" value="Remove"/> 
      </div> 
      <div id="flagText"> 
       <p> Please enter a Flag number and press "Add" button: </p> 
       <input style="background: white; color: black;" type="text" id="flagTextInput" value=""> 
       <input type="submit" id="flagAdd" value="Add"/> 
       <input type="submit" id="flagRemove" value="Remove"/> 
      </div> 
      <div id="sensorText"> 
       <p> Please enter a Sensor number and press "Add" button: </p> 
       <input style="background: white; color: black;" type="text" id="sensorTextInput" value=""> 
       <input type="submit" id="sensorAdd" value="Add"/> 
       <input type="submit" id="sensorRemove" value="Remove"/> 
      </div> 
     </div> 
    </div> 
+0

, что проблема на выше if..else if..else? –

+0

@SJnawali - это мультиселектор, и если я сначала выбираю «вывод», другие, выбранные впоследствии, не будут отображаться. – yvonnezoe

ответ

13

That`s только стандартный JavaScript: http://www.w3schools.com/js/js_switch.asp

switch(n) { 
case 1: 
    //execute code block 1 
    break; 
case 2: 
    //execute code block 2 
    break; 
default: 
// code to be executed if n is different from case 1 and 2 
}       

, где переменная переключатель будет имя выбранного тега

+0

спасибо ... как я должен представлять «1» в качестве оператора выбора jquery? – yvonnezoe

+0

И может быть добавлен вариант с несколькими вариантами, опустив break; (s). – QMaster

1

Существует нет JQuery не Переключитесь заявление. Если вы хотите использовать оператор switch, вы можете обратиться к Javascript Switch.

Switch

Вот бы мой подход. я добавлю атрибут раздела данных для каждого параметра в # select-choice-1, который будет иметь идентификатор соответствующего div.

$('#select-choice-1').change(function(){ 
          $('#outputText').hide(); 
        $('#armCB').hide(); 
        $('#zoneText').hide(); 
        $('#counterText').hide(); 
        $('#flagText').hide(); 
        $('#sensorText').hide(); 

    //the above hide() methods can be removed if you can 
    //add a class for all of these sections and say $('.sectionDivs').hide() 
    var divId = $(':selected',this).data('section'); 
    $('#' + divId).show(); 
  
    } 
+0

Ох спасибо! может быть, вы можете мне помочь с этим тоже http: // stackoverflow.com/questions/16099958/jquery-javascript-how-to-display-the-value-get-from-val/16100003? noredirect = 1 # comment22989483_16100003 http://stackoverflow.com/questions/16139196/jquery-assign- и-call-id-with-variable – yvonnezoe

5

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

$('#select-choice-1').change(function(){ 
    $('.elements').hide(); 
    $('#' + this.value + 'Text').show(); 
}); 

Update: As вы используете несколько атрибутов для элемента select, вы можете использовать метод jQuery val, он возвращает массив выбранных параметров, затем вы можете создать селектор на основе выбранных значений.

$('#select-choice-1').change(function(){ 
    $('div.right > div').hide(); 
    var selector = '#' + $(this).val().join('Text, #') + 'Text'; 
    $(selector).show(); 
}); 

http://jsfiddle.net/3AbJq/

+0

может не работать для 'armCB' –

+0

@ArunPJohny Да, но изменение ID не очень сложно. – undefined

+0

да, вы правы –

1

Если это множественный выбор, не используйте else if

$('#select-choice-1').change(function() { 
    $('#outputText').hide(); 
    $('#armCB').hide(); 
    $('#zoneText').hide(); 
    $('#counterText').hide(); 
    $('#flagText').hide(); 
    $('#sensorText').hide(); 

    if ($('#output').is(':selected')) { 
     $('#outputText').show(); 
    } 
    if ($('#arm').is(':selected')) { 
     $('#armCB').show(); 
    } 
    if ($('#zone').is(':selected')) { 
     $('#zoneText').show(); 
    } 
    if ($('#counter').is(':selected')) { 
     $('#counterText').show(); 
    } 
    if ($('#flag').is(':selected')) { 
     $('#flagText').show(); 
    } 
    if ($('#sensor').is(':selected')) { 
     $('#sensorText').show(); 
    } 
}); 

Демо: Fiddle

Вы можете упростить его к чему-то, как показано ниже, если вы можете внести некоторые изменения в разметку

$(function(){ 

    var $ctitems = $('#select-choice-1-items'); 
    var $items = $('.item', $ctitems).hide(); 

    $('#select-choice-1').change(function(){ 
     $items.hide() 
     $('option:selected',this).each(function(){ 
      var id = $(this).attr('id'); 
      $('#' + id + 'Item').show() 
     }); 
    }); 
}); 

HTML

<div id="display" style=" clear:both"> 
    <div class="left" style="float:left; width:48%"> 
     <div data-role="fieldcontain"> 
      <label for="select-choice-1" class="select">Select Category</label> 
      <select name="select-choice-1" id="select-choice-1" data-native-menu="false" data-mini="true" multiple="multiple" size="2"> 
       <option value="arm" id="arm">Arm</option> 
       <option value="zone" id="zone">Zone Input</option> 
       <option value="output" id="output">Output</option> 
       <option value="counter" id="counter">Counter</option> 
       <option value="flag" id="flag">Flag</option> 
       <option value="sensor" id="sensor">Sensor</option> 
      </select> 
     </div> 
    </div> 

    <div id="select-choice-1-items" class="right" style=" float: right; width:48%"> 
     <div id="armItem" class="item"> 
      <fieldset data-role="controlgroup"> 
       <legend>Unit</legend> 
       <input type="checkbox" class="CB" name="armCB_1" id="armCB_1" class="custom" data-mini="true" /> 
       <label for="armCB_1">Arming Status</label> 
      </fieldset> 
     </div> 

     <div id="outputItem" class="item"> 
      <p> Please enter an Output number and press "Add" button: </p> 
      <input style="background: white; color: black;" type="text" id="outputTextInput" value=""/> 
      <input type="submit" id="outputAdd" value="Add"/> 
      <input type="submit" id="outputRemove" value="Remove"/> 
     </div> 
     <div id="zoneItem" class="item"> 
      <p> Please enter a Zone number and press "Add" button: </p> 
      <input style="background: white; color: black;" type="text" id="zoneTextInput" value=""/> 
      <input type="submit" id="zoneAdd" value="Add"/> 
      <input type="submit" id="zoneRemove" value="Remove"/> 
     </div> 
     <div id="counterItem" class="item"> 
      <p> Please enter a counter number and press "Add" button: </p> 
      <input style="background: white; color: black;" type="text" id="counterTextInput" value=""/> 
      <input type="submit" id="counterAdd" value="Add"/> 
      <input type="submit" id="counterRemove" value="Remove"/> 
     </div> 
     <div id="flagItem" class="item"> 
      <p> Please enter a Flag number and press "Add" button: </p> 
      <input style="background: white; color: black;" type="text" id="flagTextInput" value=""/> 
      <input type="submit" id="flagAdd" value="Add"/> 
      <input type="submit" id="flagRemove" value="Remove"/> 
     </div> 
     <div id="sensorItem" class="item"> 
      <p> Please enter a Sensor number and press "Add" button: </p> 
      <input style="background: white; color: black;" type="text" id="sensorTextInput" value=""/> 
      <input type="submit" id="sensorAdd" value="Add"/> 
      <input type="submit" id="sensorRemove" value="Remove"/> 
     </div> 
    </div> 
</div> 

Демо: Fiddle

+0

ahh да, что было частью моей программы, которую я не включил в мой вопрос выше. Но проблема в том, что сначала выбирается «выход», другие не отображаются. :( – yvonnezoe

+0

@yvonnezoe вы можете поделиться html также –

+0

@yvonnezoe также попробуйте [ответ неопределенного ответа] (http://stackoverflow.com/questions/16139948/how-do-i-do-a-switch-case-for-jquery/16140092? Noredirect = 1 # answer-16140015) –

Смежные вопросы