ecolema
ecolema

Reputation: 598

pass input max attribute as integer to jquery variable

I am trying to pass the max attribute as an integer to a jquery variable. Just can't seem to make it work. In the example the variable maxqty should be 6.

Any ideas appreciated.

HTML

<input name="qty" id="qty" type="text" value="1" size="3" maxlength="2" max="6" />

Jquery

var maxqty = 10

jQuery(function(){
    jQuery("#qtyplus").click(function(){
     if(jQuery('#qty').val()<maxqty)
     jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) + 1 );
    });
    jQuery("#qtyminus").click(function(){
     if(jQuery('#qty').val()>1)
      jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) - 1 );

    });
  });

Upvotes: 3

Views: 1613

Answers (2)

Ted
Ted

Reputation: 14927

You want parseInt($('#qty').attr('max'))

Like if( jQuery('#qty').val() < ( parseInt(jQuery('#qty').attr('max')) ) )

What you are trying to retrieve is an attribute on the elemenet, any of which can be retrieved with the .attr call.

Oh and just in case, jQuery .attr docs

Upvotes: 1

MamaWalter
MamaWalter

Reputation: 2113

You could use data-attributes to store your maximum.

Something like this:

<input name="qty" id="qty" type="text" value="1" size="3" maxlength="2" data-max="6" />

Js:

var input = jQuery('#qty');

jQuery("#qtyplus").click(function(){
 if(input.val()<jQuery('#qty').data('max'))
 input.val( parseInt(input.val()) + 1 );
});

jQuery("#qtyminus").click(function(){
 if(input.val()>1)
  input.val( parseInt(input.val()) - 1 );
});

FIDDLE DEMO

Upvotes: 0

Related Questions