简体   繁体   中英

Show notification that value is max on arrow up click on input type="number"

I have input:

<input type="number" step="1" min="0" max="4" />

How can I display alert that max value is 4 when user clicks on up arrow and current value is already 4?

Try this

You have to tell the field it was already clicked and reached 4 before alerting next time

Browser that respect the max=4 will not allow the field to increment beyond 4 so the value on its own is not enough

 document.getElementById("num").addEventListener("click", function(e) { const value = this.value, max = this.getAttribute("max"), min = this.getAttribute("min"), minned = this.dataset.minned === "true"; maxed = this.dataset.maxed === "true"; if (value === max && maxed) { alert("Value is max"); } if (value === min && minned) { alert("Value is at 0"); } this.dataset.maxed = value === max ? "true" : "false"; this.dataset.minned = value === min ? "true" : "false"; }) document.getElementById("num").addEventListener("input", function(e) { const value = this.value || 0, min = this.getAttribute("min"), max = this.getAttribute("max"); if (value != "" && value > max || value < min) { alert(`Value should be between ${min} and ${max}`); this.value = ""; } this.dataset.maxed = value === max ? "true" : "false"; this.dataset.minned = value === min ? "true" : "false"; })
 <input id="num" type="number" step="1" min="0" max="4" />

Try this

 function handleMyInput(event){ const { value, max } = event.target if(value >= max) alert('Max value reached'); }
 <input type="number" step="1" min="0" max="4" id='myInput' onclick='handleMyInput(event)' />

As far as I can guess from your information adding an eventlistener would do what you want to:

 const input_number = document.getElementById("input_number"); input_number.addEventListener("change", function(){ if(input_number.value > 4) { alert("Max. number is 4!") } })
 <input id="input_number" type="number" step="1" min="0" max="4" />

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