Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show field if true, hide field if false?

Want to have a notification box displayed if amount in fieldA is higher than amount in fieldB.

Currently have some code working but the notification box toggles on and off not depending on the actual amount.

What am I missing?

jquery:


 $(document).ready(function() {
     $('#fieldA').change(function(){
                if($(this).val()>$('#fieldb').val()){
                  //display it on the form
                  $('.labelNotification').toggle();
                  $('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
                }
            })
      });

HTML:

< p style="display: none;" class="error labelNotification">

like image 437
Alex Avatar asked Feb 25 '23 20:02

Alex


2 Answers

This is tailor-made for the toggle(boolean) method. Also, you have to be careful about appending to the notification label ... what if the user changes his answer twice? It's better to have multiple notification objects, each of which can contain stuff for a single type of notification.

$(function() {
    $('#fieldA').change(function() {
        var isLarger = +$(this).val() > +$('#fieldB').val();  // Note: convert to number with '+'
        var $labelNotification = $('.labelNotification');
        $labelNotification.toggle(isLarger);
        if (isLarger) {
            //display it on the form
            $labelNotification.html('Not recommended to have FieldA figure higher than FieldB.');
        }
    })
});
like image 146
Anthony Mills Avatar answered Mar 08 '23 00:03

Anthony Mills


If you're comparing numerical values (which it seems like you are), you should use parseInt or parseFloat to convert the (string) value returned by val() to an integer. According to the documentation for val, the function always returns a string value.

like image 31
Andrew Whitaker Avatar answered Mar 07 '23 23:03

Andrew Whitaker