Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display x if x display y if y (bad title I know)

Tags:

html

jquery

Ok, so I have some jQuery code that displays an input box if an item with prefix Blue from dropdown menu is selected.

Code:

$(function() {
    $('#text1').hide();
    $('#select2').on('change', function(event) {
        var opt = this.options[ this.selectedIndex ];
        var picked_blue = $(opt).text().match(/Blue/i);
        if(picked_blue) {
            $('#text1').show();
        } else {
            $('#text1').hide();
        }
    });
});

But what I also need to add is to display something else if any other item from dropdown menu is selected. And what I need to display is another dropdown menu of items.

like image 575
Smiley Avatar asked Dec 19 '12 11:12

Smiley


People also ask

How do you write an IF THEN formula in Excel?

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")

How do you write an IF THEN formula in Excel with multiple criteria?

Another way to get an Excel IF to test multiple conditions is by using an array formula. To complete an array formula correctly, press the Ctrl + Shift + Enter keys together. In Excel 365 and Excel 2021, this also works as a regular formula due to support for dynamic arrays.


3 Answers

Shouldn't this work for you:

if(picked_blue) {
  $('#text1').show();
  $('#text2').hide();
} else {
  $('#text1').hide();
  $('#text2').show();
}

where text1 and text2 share the position in the DOM, with texts like 'blue' and 'not blue at all', respectively?

like image 184
SWeko Avatar answered Oct 09 '22 21:10

SWeko


You need to put condition in else part of your statement.

$(function() {
    $('#text1').hide();
    $('#select2').on('change', function(event) {
        var opt = this.options[ this.selectedIndex ];
        var picked_blue = $(opt).text().match(/Blue/i);
        if(picked_blue) {
            $('#text1').show();
        } else {
            $('#text1').hide();
            if($(opt).text().match(/Red/i))
            {
                  //You code here
            }
        }
    });
});

or shortening code.

$(function() {
    $('#text1').hide();
    $('#select2').on('change', function(event) {
       selectedVal = $(this).val().toLowerCase();
       switch (selectedVal){
         case 'blue':
            //Your code
            break;
          case 'red':
           //Your code
           break;
          case 'black':
            //Your code
            break;
          default:
            //your code
        }
   });
});
like image 36
Adil Avatar answered Oct 09 '22 22:10

Adil


Why cant you try with toggle function in Jquery

$('#text1').toggle();
like image 34
Vinoth Babu Avatar answered Oct 09 '22 23:10

Vinoth Babu