Skip to content

Instantly share code, notes, and snippets.

@yashasvi9199
Created June 7, 2023 16:13
Show Gist options
  • Save yashasvi9199/47014c6140fe87c44914b38c841de175 to your computer and use it in GitHub Desktop.
Save yashasvi9199/47014c6140fe87c44914b38c841de175 to your computer and use it in GitHub Desktop.
This will allow user to input only restricted number of space
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
<h2>Please Enter Input</h2>
<input type="text" placeholder="Enter input" onkeypress="return restrict(this.value,event)">
<script>
function restrict(val, event) {
//console.log(val);
var k = event ? event.which : window.event.keyCode;
var limit = 0;
//Running a loop throught the string length so that it keeps on checking the number of spaces
for (let i = 0; i <= val.length; i++) {
if (val.includes(" ")) { // checks for availability of space in input field
limit++; // just a variable to store number of inputs for 'space'
}
if (limit == 2 && k == 32) { // in case user is trying to enter 'space' second time. K==32 is using ASCII code where 32 is space
return false;
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment