0

I want to have an alert if the input has a class of "saninput" and the value is not equal to "".

The code works for the first example but not any others. Does anybody know how to make it so all relevant inputs create an alert?

$(document).ready(function() {
  if ($(".saninput").val() != "") {
    var animal = $(".saninput").data("animal");
    alert(animal)
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="sheepid" data-animal="sheep" class="saninput" type="text" value="sheep">
<input id="cowid" data-animal="cow" class="saninput" type="text" value="cow">
<input id="dogid" data-animal="dog" class="saninput" type="text" value="dog">

Thanks in advance

Pedram
  • 15,766
  • 10
  • 44
  • 73
bevan7
  • 63
  • 1
  • 2
  • 11

4 Answers4

1

It won't work you need to loop through elements like this:

<script>

    $(document).ready(function(){
        $(".saninput").each(function(){
        if ($(this).val() != ""){
        var animal = $(".saninput").data("animal");
        alert (animal)
        };
    });
    });

</script>
maddy23285
  • 738
  • 6
  • 16
0

Hello please use this one for alert all value relevant to class :

$(document).ready(function(){
   $(".saninput").each(function( index ) {
     alert($(this).val());
   });
});
Lathiya Fenil
  • 290
  • 2
  • 8
  • You should try to explain what is 'wrong' about OPs code and how it can be improved so that everyone can learn from it – yarwest Jan 01 '18 at 15:54
0

http://api.jquery.com/val/

Get the current value of the first element in the set of matched elements ...

$(".saninput").each(function(){
  if ($(this).val() != ""){
    var animal = $(this).data("animal");
    alert (animal)
  };
});
Igor
  • 15,833
  • 1
  • 27
  • 32
0

You should iterate .saninput elements;

$( ".saninput" ).each(function() {
    alert($( this ).val());
});
lucky
  • 12,734
  • 4
  • 24
  • 46