3

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 );

    });
  });
5
  • you could use data-attributes. Commented Mar 12, 2014 at 16:10
  • if maxqty really is 10a then numerical comparisons are going to fail. And what is that code supposed to do, because you don't seem to be trying to use the max attribute anywhere. Commented Mar 12, 2014 at 16:10
  • Where you are passing? Commented Mar 12, 2014 at 16:12
  • the a was a typo. it's a plus minus button for the input; the maxqty is the upper limit. Commented Mar 12, 2014 at 16:16
  • I don't know what further you want to do with this, but the thing that you want to do here can be easily done without any js using HTML5's numeric only input box. Commented Mar 12, 2014 at 16:21

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

If you're going to use parseInt() don't forget the radix.
Good point, I suppose Number would be simpler... had parseInt on the brain this morning :p
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.