DieselHashtag
DieselHashtag

Reputation: 45

Use jQuery to show/hide div based on numeric input quantity

I'd be most appreciative if anybody could help me with this please.

I have the following input:

 <input onchange="UpdateItemQuantity(this.value,1284349,0,10352185,2579246,'','AU'); return false;" type="number" class="form-control cart-quantity" min="1" value="1"/>

I'd like to have a div display a message underneath if the input value is increased to 3 or more?

Project Context: Customer will add items to the cart and if they reach 3, they receive a free product

Is this possible?

Thank you in advance!

Upvotes: 1

Views: 1424

Answers (2)

PeterKA
PeterKA

Reputation: 24638

This demo show that (and how) the concept works.

$(function() {
    $('.quantity').on('input', function() {
        var states = ['hide','show'],    //possible states of the freebie div
            i = +this.value > 2 ? 1 : 0; //determine index of the states array
        $('.freebie')[states[i]]();      //example $('.freebie')['hide']() is equiv to $('.freebie').hide()
    })
    .trigger('input');
    //when using buttons to increment and decrement
    $('.increase,.decrease').on('click', function() {
        var diff = $(this).is('.increase') ? 1 : -1; //determin whether to decrement or increment
        $('.quantity').val(function() {
            return +this.value + diff; //decrement or increment
        });
        $('.quantity').trigger('input'); //manually trigger the 'input' event or whatever event triggers the freebies div to show
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="decrease">-</button>
<input type="number" class="quantity" value="0">	
<button type="button" class="increase">+</button>
<div class="freebie">
    <img src="http://momsneedtoknow.com/wp-content/uploads/2009/01/freebies.gif" />
</div>

Upvotes: 0

Nishanth Matha
Nishanth Matha

Reputation: 6081

In your html add a div below input:

<div id="free-prod"><p>You have a free product</p></div>

In CSS:

#free-prod {
    display:none
}

In your UpdateItemQuantity function just add the following code:

if(this.value >2) {
     $('#free-prod').show();
}
else{
    $('#free-prod').hide();
}

EDIT:

If you can edit the UpdateItemQuantity function (as said in comment). You can add a event listner to the element. I'd suggest giving some id to your input element and do

if($('#your_input_id').val() > 2 ) {
     $('#free-prod').show();
}
$('#your_input_id').on('change',function(){
    if($(this).val() > 2 ) {
        $('#free-prod').show();
    }
    else{
        $('#free-prod').hide();
    }
})

Demo https://jsfiddle.net/w8vwsx81/

Upvotes: 1

Related Questions