问题
Is it possible to not allow a blank character / space in a input form like below?
<input type="text" value="" maxlength="30" name="email" class="formfield w0">
回答1:
Check this Fiddle. Relevant code:
$(function() {
$('#input1').on('keypress', function(e) {
if (e.which == 32){
console.log('Space Detected');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1" />
回答2:
Use HTML5's extended input types to apply constraint validation, which will prevent submitting the form with invalid emails in modern browsers:
<input type="email" value="" maxlength="30" name="email" class="formfield w0">
In older browsers, you can detect that the input's type is not "email", as it will default to "text" when a value is considered invalid. I'd recommend blocking the submission of the form, rather than preventing default action of the space key, which could be inadvertently circumvented by pasting or via other input methods.
The following code is an example of this, and should be executed after the document is ready:
var frm = document.getElementById('myform');
if (frm.email.type === 'text') {
frm.onsubmit = function () {
if (/\s/.test(frm.email.value)) {
// Tell your user the field is invalid here, e.g.
frm.email.className = 'invalid';
// Prevent form submission
return false;
}
}
}
Working demo: http://jsfiddle.net/hgc7C/
Don't forget that this is not a substitute for server-side form validation.
回答3:
Yes it is possible by using javascript/JQuery.
If you want it for all text boxes, then do as below.
$(function() {
$('.formfield input[type=text]').on('keypress', function(e) {
if (e.which == 32)
return false;
});
});
If you want it for a specific textbox, then add an id to the textbox input and replace .formfield input[type=text]
with #textBoxId
来源:https://stackoverflow.com/questions/19024825/not-allow-a-blank-character-space-in-a-input-form