最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Form field quantity updown buttons, don't allow negative numbers? - Stack Overflow

programmeradmin6浏览0评论

Is there a way to make the minimum number be 0, and not allow the user to go below 0 when clicking down?

<form>
  <input type="text" name="name" value="0" />
  <input type="button" value="up" onclick="this.form.name.value++;" >
  <input type="button" value="down" onclick="this.form.name.value--;">
</form>

http://jsfiddle/KYDPd

Is there a way to make the minimum number be 0, and not allow the user to go below 0 when clicking down?

<form>
  <input type="text" name="name" value="0" />
  <input type="button" value="up" onclick="this.form.name.value++;" >
  <input type="button" value="down" onclick="this.form.name.value--;">
</form>
Share asked Apr 12, 2012 at 8:48 deflimedeflime 6132 gold badges10 silver badges17 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

If separate buttons are not necessary and HTML5 is an option you could just use this:

<form>
    <input type="number" min="0" name="name" value="0" />
</form>

This should do the trick. Check what the value is before you allow each operation. Also added an onchange to the text input to inforce your minimum 0 requirement. Agree with other answer that this should be in a function though.

http://jsfiddle/xqV6V/1/

<form>
    <input type="text" name="name" value="0" onchange="if(this.value<0){this.value=0;}" />
    <input type="button" value="up" onclick="if(this.form.name.value>=0){this.form.name.value++;}" >
    <input type="button" value="down" onclick="if(this.form.name.value>0){this.form.name.value--};">
</form>

You should probably put this JavaScript in a function.

<form>
    <input type="text" name="name" value="0" />
    <input type="button" value="up" onclick="this.form.name.value++;" >
    <input type="button" value="down" onclick="if(this.form.name.value>0)this.form.name.value--;">
</form>

Additional Answer with functions.

<script>

function ud_find_text(self) {
    var children = self.parentNode.getElementsByTagName('input');
    for (var i = 0; i < children.length; i++) {
        if (children[i].getAttribute('type') == 'text') {
            return children[i];
        }
    }
}

function ud_inc(self) {
    var text = ud_find_text(self);
    text.value++;
}

function ud_dec(self) {
    var text = ud_find_text(self);
    if (text.value > 0) text.value--;
}

</script>

<form>
  <input type="text" name="name" value="0" />
  <input type="button" value="up" onclick="ud_inc(this)" >
  <input type="button" value="down" onclick="ud_dec(this)">
</form>
发布评论

评论列表(0)

  1. 暂无评论