How to disable scroll to change number in <input type=”number”> field using JavaScript/jQuery?
Given an HTML document containing <input type = “number”> attribute and the task is to disable the mouse scroll wheel to change number value using JavaScript/jQuery.
Approach:
- Select the element.
- Add an event to that element which will call a function when scrolling starts.
- Make the element blur on scrolling.
Example 1: This example implements the above approach using JavaScript.
<!DOCTYPE HTML> < html > < head > < title > How to disable scroll to change number value in < input type = "number" > attribute in JavaScript/jQuery? </ title > < script src = </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < form > < input id = "input" type = "number" /> </ form > < br > < button onclick = "GFG_FUN()" > click here </ button > < p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to disable" + " scrolling on input element."; function GFG_FUN() { var input = document.getElementById("input"); input.addEventListener("mousewheel", function(event){ this.blur() }); el_down.innerHTML = "Mouse wheel disabled!"; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example 2: This example implements the above approach using jQuery.
<!DOCTYPE HTML> < html > < head > < title > How to disable scroll to change number value in < input type = "number" > attribute in JavaScript/jQuery? </ title > < script src = </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < form > < input id = "input" type = "number" /> </ form > < br > < button onclick = "GFG_FUN()" > click here </ button > < p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;" > </ p > < script > var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to disable" + " scrolling on input element."; function GFG_FUN() { $('#input').on("wheel", function (e) { $(this).blur(); }); el_down.innerHTML = "Mouse wheel disabled!"; } </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Please Login to comment...