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 the 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 disabled on scrolling.
Example 1: This example implements the above approach using JavaScript.
html
<!DOCTYPE HTML> < html > < head > < title > How to disable scroll to change number value in input type="number" attribute in JavaScript/jQuery? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < h3 > Click on the button to disable scrolling on input element </ h3 > < form > < input id = "input" type = "number" /> </ form > < br > < button onclick = "GFG_Fun()" > Click Here </ button > < h3 id = "GFG" style = "color: green;" ></ h3 > < script > let result = document.getElementById("GFG"); function GFG_Fun() { let input = document.getElementById("input"); input.addEventListener("mousewheel", function (event) { this.blur() }); result.innerHTML = "Mouse wheel disabled!"; } </ script > </ body > </ html > |
Output:
Example 2: This example implements the above approach using jQuery.
html
<!DOCTYPE HTML> < html > < head > < title > How to disable scroll to change number value in input type="number" attribute in JavaScript/jQuery? </ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < h3 > Click on the button to disable scrolling on input element </ h3 > < form > < input id = "input" type = "number" /> </ form > < br > < button onclick = "GFG_FUN()" > Click Here </ button > < h3 id = "GFG" style = "color: green;" > </ h3 > < script > let elm = document.getElementById("GFG"); function GFG_FUN() { $('#input').on("wheel", function (e) { $(this).blur(); }); el_down.innerHTML = "Mouse wheel disabled!"; } </ script > </ body > </ html > |
Output: