Show alert when select select

1

I have the following code

$query = mysql_query("SELECT id, nome, situacao FROM clientes ORDER BY nome") or print mysql_error()

<select class="js-example-basic-single form-control" id="cliente" name="cliente">
   <option value="Selecione o Cliente"> Selecione o Cliente</option>
        <?php                           
          while($dados = mysql_fetch_array($query)) { ?>
           <option value="<?php echo $dados['id'] ?>">
        <?php 
        if ($dados['situacao']==1) {
          $dados['situacao']='Em dia';
        } else {
          $dados['situacao']='Devendo';
        }
          echo $dados['nome'] . ' -> '. $dados['situacao']; 
        ?>
        </option>
        <?php } ?>
    </select>

I needed that with the same verification as the field situacao , I would show an alert showing that the client is

    
asked by anonymous 17.03.2017 / 19:32

1 answer

1

You can check whether the string within your option that was selected has the word Devendo , it shows the alert.

If you use jQuery it's an option:

$('select').on('change', function(){ 
  if( $(this).find('option:selected').text().indexOf('Devendo') > 0) {
    alert('O Cliente esta devendo!');
  }
});

If you do not want to use jQuery, below is just under Javascript:

var element = document.getElementById('cliente');

element.addEventListener("change", myFunction);

function myFunction() {
    var curSelected = this.querySelectorAll('option:checked')[0];
    if(curSelected && curSelected.innerHTML.indexOf('Devendo') > 0){
        alert ("O Cliente está devendo!");
    }
}

You can check it working as below:

/* utilizando jQuery */
$('select').on('change', function(){ 
  if( $(this).find('option:selected').text().indexOf('Devendo') > 0) {
    alert('O Cliente esta devendo pelo jQuery!');
  }
});



/* utilizando apenas Javascript */
var element = document.getElementById('cliente');

element.addEventListener("change", myFunction);

function myFunction() {
    var curSelected = this.querySelectorAll('option:checked')[0];
    if(curSelected && curSelected.innerHTML.indexOf('Devendo') > 0){
    	alert ("O Cliente está devendo pelo Javascript!");
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectclass="js-example-basic-single form-control" id="cliente" name="cliente">
   <option value="Selecione o Cliente"> Selecione o Cliente</option>
   <option value="Selecione o Cliente2"> Selecione o Cliente 2 Devendo</option>
   <option value="Selecione o Cliente3"> Selecione Devendoo Cliente</option>
   <option value="Selecione o Cliente4"> Selecione o Cliente</option>
</select>
    
17.03.2017 / 20:21