Frankie
Frankie

Reputation: 499

Input field - remove value when onClick events and restore the value if not set

In the input field I set a default value. The default value must be removed when click inside the field, but if the value insert is blank and the mouse cursor leave the field, must be restored the default value. The default value must be writing in the database.

For example:

Default value: 0

When I leave the input field and the value is blank,the default value is restored .

<input type="text" onclick="if(this.value == 'value') { this.value = ''; }" value="value" />

How to restore the default value if any value is set to input after click?

Thanks

Upvotes: 0

Views: 2282

Answers (2)

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

Just attach listener to your input on the focus and blur events like bellow example ;

var inputToCheck = document.getElementById("inputNum");
inputToCheck.initialValue = inputToCheck.value || '';

inputToCheck.addEventListener("focus",function(e) {
     this.value == this.initialValue ? this.value = "" : "";
});

inputToCheck.addEventListener("blur",function(e) {
     this.value == "" ? this.value = this.initialValue : "";
})
<input type="text" id="inputNum" value="0" />

Another with jQuery :

var inputToCheck = $("#inputNum");
inputToCheck.data("initialValue", inputToCheck.val());

inputToCheck.on("focus",function(e) {
     this.value == $(this).data("initialValue") ? this.value = "" : "";
}).on("blur",function(e) {
     this.value == "" ? this.value = $(this).data("initialValue") : "";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputNum" value="0" />

Upvotes: 1

ABHIJITH GM
ABHIJITH GM

Reputation: 134

Does using placeholder attribute serve your requirement ?

This will show default value if the field is left blank., But won't send it to server when form is submitted with field value is blank.If you want to save the default value when user submits the form with blank input, write an obsubmit handler for the form that sets the value to default, or implement it in the server side to save default value in db if value is blank.

Upvotes: 0

Related Questions