Stack Stack - 6 months ago 16
HTML Question

How to set default value of input if value is empty? jQuery

Example, i have input where default value is 5.
But user remove it using backspace, so after that i want to set default value again.

Answer

Lets say your input is having a id test you can do like below

$('#test').on('change blur',function(){
      if($(this).val().trim().length === 0){
        $(this).val(5);
      }
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" type="text" value = "5" />

Comments