How to remove an Alert after selecting another in a select

Asked

Viewed 87 times

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 to show an "Alert" in bootstrap. That is, if the user selects the value "anu1", shows the Alert "Alert-Anu-1", this until then is working. What I’m not getting is to clear my values.

Ex: if you select the value anu1, it shows it, but if you select the value anu2, you have to clean the Alert of anu1 and show only the value of anu2 and so on.... How could I do that?

2 answers

1

You’re not taking the display, when you put with the display = "block" it is necessary to put display = "none", so go 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';   
    }
    /*...*/
});

1


I think you just need something like:

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

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

  • I liked it that way, but I can’t execute it. My Alerts and my values are written and not numbered like in the example.

  • My Alert is type: <div id="Alert-advertiser-one" class="Alert Alert-info Alert-dismissible" role="Alert"> <Strong>Petbusca.</Strong> Nice tool.... <a href="#" title="Learn More">Learn More...</a>. </div>

  • @Hitchleonardo doesn’t make a difference if you use other names for Ids. In that case you can use var alerts = $('[id^="alert-anunciante-"]');, the key here is ^= indicating ID beginning with "xxx". If you want an example to work join a jsFiddle or the whole code in the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.