一個簡單的解決方案是使用jQuery函數$.trim
//removes leading and trailing spaces on every text field "on focus out"
$(":text").each(function(index) {
$(this).focusout(function() {
var text = $(this).val();
text = $.trim(text);
$(this).val(text);
});
});
====================
下面是一個簡單的代碼
//removes leading and trailing spaces on every text field "on focus out"
$(":text").each(function(index) {
$(this).focusout(function() {
var text = $(this).val();
text = $.trim(text);
$(this).val(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First Name<br>
<input id="name" type="text" required><br>
Surname<br>
<input id="surname" type="text" required><br>
Address<br>
<input id="address" type="text" required><br>