简体   繁体   中英

How to Show an Alert when Option is Selected

I'm trying to alert visitors about a minimum amount, and I just reached the point where I can show the alert, but for all changes... The point is that I want only to show the alert when the user clicks on option value = 1.

Here's what I've got (missing the IF clause):

<script> 
    function MinPecas(quantidade) {
        alert("MÍNIMO DE 30 PEÇAS PARA ORÇAMENTO");
    }  
</script>

<select name="quantidade" id="quantidade" onchange ="MinPecas(this.form)">
<option value="1">0 A 30 PÇS</option>
<option value="2">30 A 50 PÇS</option>
<option value="3">50 A 100 PÇS</option>
</select>

Try this one

 <script> function MinPecas(quantidade){ if(quantidade == 1) alert("MÍNIMO DE 30 PEÇAS PARA ORÇAMENTO"); } </script> <select onchange="MinPecas(this.value)" name="quantidade"> <option value="1">0 A 30 PÇS</option> <option value="2">30 A 50 PÇS</option> <option value="3">50 A 100 PÇS</option> </select> 

Try

$(document).ready(function(){
    $('[name=quantidade]').change(function(){
        if($(this).val() === '1'){
             alert();
        }
    });
 });

EDIT

Also for this to work you need to include jquery library!

Since you want the alert to be displayed when the element with value 1 is SELECTED try adding an empty option as the first choice.

<option>Please select</option>

It's a good idea to apply event listeners from the Javascript itself, as opposed to directly in the HTML. For this reason, use the element.addEventListener() method. If you pass it the event ( change ) function ( MinPecas ), it will call MinPecas whenever the value of the element is changed. Additionally, the this variable of the function will then be the element, so this.value will be equal to the value of the element. You can get the element using document.getElementById() , and then adding the event listener to that.

<select name="quantidade" id="quantidade">
    <option value="1">0 A 30 PÇS</option>
    <option value="2">30 A 50 PÇS</option>
    <option value="3">50 A 100 PÇS</option>
</select> 

<script> 
    function MinPecas(){
        if (this.value === '1'){
            alert("MÍNIMO DE 30 PEÇAS PARA ORÇAMENTO");
        }
     }

     document.getElementById('quantidade').addEventListener('change', MinPecas);

</script>

Lastly, you'll want to make sure that the <script> element is after the <select> , because if it runs beforehand, the select tag will not exist yet and the document.getElementById('quantidade') will not be able to find it and won't return anything.

I hope this works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM