简体   繁体   中英

Javascript - disable buttons on value matched in input box

i am looking for solution i want to disable button if value of input box matched.

i got two buttons and an input box

<button type="button" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button> 
<button type="button" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>

<input type="text" id="count" value="0"/>

i want to disable buttonpassvalue if input box (count) is zero and disable second button buttonpassvalue1 if value of (count) is 5

thanks for your help.

Made a JSFiddle for you!

http://jsfiddle.net/fRHm9/

Basically, you make a change event listener and, when it changes, grab the element whose id is equal to the input's value. I assigned the buttons ids of -1 and 1. Check out the fiddle.

Basically, you could achieve this quite easily using plain javascript. But, when using javascript in order to be able to find a specific element efficiently you will need to specify an id for that element. So I would recommend you to change your buttons so that they use id attributes as follows...

<button type="button" id="buttonpassvalue" name="buttonpassvalue" value="-1" onclick="showUser1(this.value)"><< Previous</button> 
<button type="button" id="buttonpassvalue1" name="buttonpassvalue1" value="1" onclick="showUser2(this.value)">Next >> </button>

<input type="text" id="count" value=""/>

Note, that I added id attributes to each buttons. Now, you can run attach this javascript function to the keyup event of the text input element...

var input = document.getElementById('count');
input.onkeyup = function(){
    var buttonpassvalue = document.getElementById('buttonpassvalue');
    var buttonpassvalue1 = document.getElementById('buttonpassvalue1');
    var val = this.value.trim();


    if(val == "0"){
       buttonpassvalue.setAttribute("disabled","disabled");
       buttonpassvalue1.removeAttribute("disabled");
    }
    else if(val == "5"){
       buttonpassvalue.removeAttribute("disabled");
       buttonpassvalue1.setAttribute("disabled","disabled");
    }
    else{
       buttonpassvalue.removeAttribute("disabled");
       buttonpassvalue1.removeAttribute("disabled");
    }
};

I have created a JS Fiddler where you can see a quick demo. Also, note that this solution is using plain javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM