Logo Luan Morina
Remove leading and trailing spaces from an input string

HTML

<div class="demo-container">
<div class="demo-content">
<form action="">
<div class="container clearfix">
<div class="container-input"><input type="text" class="form-control" id="input-name" placeholder="Name" name="input-name"></div>
<div class="container-submit-button text-right"><button id="submit-button" type="submit" class="btn btn-primary float-end">Submit</button></div>
</div>
</form>
</div> 
<div class="container-post-status">
<div id="post-status"></div>
</div>
</div>

CSS

.demo-container {
margin: 0 auto;
max-width: 600px;
}
.demo-content {
margin: 2em 0;
border: 1px solid rgba(199, 199, 199, 0.4);
padding: 2em 0;
}
.container-submit-button {
padding: 1em 0;
}
.container-post-status {
margin-top: 1em;
}
.demo-container-submit {
text-align: right;
margin-top: 2em
}
.message-error {
padding: 10px 20px;
background-color: #fc0;
border-radius: 4px;
margin-bottom: 1em;
}
.message-success {
padding: 10px 20px;
background-color: #CAFFCA;
border-radius: 4px;
margin-bottom: 1em;
}

JS

$(document).ready(function() {
// button styles
$(".submit-button").button()
// remove leading and trailing space:
$(function() {
$("#input-name").on("blur", function() {
var demoInput = $(this);
demoInput.val(demoInput.val().replace(/^\s+|\s+$/g, ''));
});
});
// display result
$('#submit-button').click(function() {
inputNameVal = $("#input-name").val();
if ($("#input-name").val() == "") {
$("#post-status").html('<div class="message-error">Please enter your name</div>');
return false;
} else {
$("#post-status").html('<div class="message-success">Thank you <strong>' + inputNameVal + '</strong>.</div>');
return false;
}
});
});
   Remove the leading and trailing space from an input field