Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If input value is blank, assign a value of "empty" with Javascript

So I have an input field, if it's blank, I want its value to be the words "empty", but if there is any value inputted, I want the value to be the inputted value. I want to use javascript for this, any idea how this can be done?

UPDATE: Sorry, I don't think I explained it too well. I don't mean placeholder text. I mean the captured value of it. So if it's blank, the captured val() for it should be "empty", if it's filled, the captured val() for it should be that val()

like image 255
Maverick Avatar asked Jul 19 '11 19:07

Maverick


2 Answers

If you're using pure JS you can simply do it like:

var input = document.getElementById('myInput');

if(input.value.length == 0)
    input.value = "Empty";

Here's a demo: http://jsfiddle.net/nYtm8/

like image 122
Jamie Dixon Avatar answered Sep 20 '22 14:09

Jamie Dixon


I'm guessing this is what you want...

When the form is submitted, check if the value is empty and if so, send a value = empty.

If so, you could do the following with jQuery.

$('form').submit(function(){
    var input = $('#test').val();
    if(input == ''){
         $('#test').val('empty');
    }    
});

HTML

<form> 
    <input id="test" type="text" />
</form>

http://jsfiddle.net/jasongennaro/NS6Ca/

Click your cursor in the box and then hit enter to see the form submit the value.

like image 29
Jason Gennaro Avatar answered Sep 22 '22 14:09

Jason Gennaro