How to remove an alert after selecting another in a select

1

I have the following code:

HTML:

<select class="form-control btn-form" id="select-category">
      <option selected hidden>Selecione uma categoria:</option>
      <option value="anu1">Anunciante1</option>
      <option value="anu2">Anunciante/option>
      <option value="anu3">Anunciante3</option>
</select>

JS:

$('#select-category').change(function(){
  if($(this).val() == 'anu1'){     
      document.getElementById('alert-anu-1').style.display='block';   
  }

  if($(this).val() == 'anu2'){ 
    document.getElementById('alert-anu-2').style.display='block';
  }
  if($(this).val() == 'anu3'){ 
    document.getElementById('alert-anu-3').style.display='block';
  }
});

The idea is to have a list and then when the user selects an option show an "alert" in bootstrap. That is, if the user selects the value "anu1", it shows the alert "alert-anu-1", this has been working so far. What I can not do is clear the values.

Ex: if you select the value anu1, it shows, but if you select the value anu2, you have to clear the alert from anu1 and show only the one from anu2 and so on .... How could I do that?

    
asked by anonymous 13.03.2016 / 07:32

2 answers

1

I think that something like:

var alerts = $('[id^="alert-anu-"]');
$('#select-category').change(function() {
    alerts.hide();
    $('#alert-' + this.value).show();
});

So when the select changes it hides all the alerts and shows only what was chosen. I created the variable alerts to have these elements cached and avoid going to the DOM to fetch them many times.

    
13.03.2016 / 09:32
1

You are not taking display , when you put display = "block" you must put display = "none" , so it will hide the message.

$('#select-category').change(function(){
    for(var x=1;x<=3;x+=1) //apaga as 3 mensagens
        document.getElementById('alert-anu-'+x).style.display='none';

    if($(this).val() == 'anu1'){     
        document.getElementById('alert-anu-1').style.display='block';   
    }
    /*...*/
});
    
13.03.2016 / 08:42