Hello,

I'm trying to display a message depending on the value of an input field. But it stops working when going back to default. Here's the JQuery code:

$(document).ready(function(){
    test();
});

function test()
{
    $('#quantity').keyup(function(){
        var quantity = $('input:text#quantity').val();
        if(isInteger(quantity))
        {
            var msg = false;
            if(quantity > 1)
            {
                msg = true;
            }

            // more code . . .

            if(msg === true)
            {
                 $('#result').html(quantity+' items');   
            }
            else
            {
                $('#result').hide();
            }
        }
    });
}

// same result by disabling this function
function isInteger(value)
{
    return /^[0-9]+$/.test(value);
}

This is the form:

<form>
    <input type="text" name="quantity" id="quantity" value="1" />
</form>

<div id="result"></div>

And here's a live example: http://jsfiddle.net/2vF3a/

To see the effect set 2, then 1 and then 2, expected result msg === true and message displayed.

The default value is 1 and to display the message it's enough to set 2 or an higher number, it seems to work fine until I go back to 1. In my intentions when going back to 1, the message has to disappear and, until this point, it's ok.

But when I type 2 or an higher number, the message doesn't appear anymore and I cannot understand why. I'm trying to achieve this effect by setting a variable msg at the top of the function var msg = false; and then switching to true when the value is higher than 1...

Any idea?
Thank you for your time!

Recommended Answers

All 2 Replies

You need to show the div when msg === true:

$('#result').html(quantity+' items');   
$('#result').show();   

// OR, using chaning

$('#result')
    .html(quantity+' items')
    .show();

Also, this is very ugly and with poor performance: $('input:text#quantity').val();
Use just #quantity or as you are already inside the event scope, you could use just $(this).

So, I think this code would be better wrote as:

$('#quantity').keyup(function(){
        var
            quantity = $(this).val()
            , $result = $('#result');

        if(isInteger(quantity))
        {
            var msg = false;
            if(quantity > 1)
            {
                msg = true;
            }

            // more code . . .

            if(msg === true)
            {
                 $result
                    .html(quantity+' items')
                    .show();   
            }
            else
            {
                $result.hide();
            }
        }
    });
commented: perfect! many thanks! +10

Thank you for the suggestions, I'm still learning js :)
Now it's perfect, many thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.