Reputation: 117
I'm working with PHP+MySQL. In one page I have a form with aprox. 30 inputs.
After showing the form, at the end I execute some jQuery sentences styling the form.
Well, some rows in my SQL have data empty inputs, so I show empty inputs. I want to fill the form with "------" without writing that slashes into DB because makes SQL much bigger.
I'm trying "replaceWith", but i dont know if this implementation with "empty" is correct. This does not work, even without .is(:empty)
<script>
$('#form').find('input[type=text]').is(':empty').replaceWith(function()
{
return this.val('------');
});
</script>
Upvotes: 0
Views: 2855
Reputation: 2136
Use something like this:
<script>
$('#form').find('input[type=text]').each(function(e){
if($(this).val()=="") $(this).val("---");
})
</script>
Upvotes: 2
Reputation: 3338
Have you considered using the HTML placeholder
attribute?
You could use placeholder
to make the dashes appear in light grey text without actually changing the value of the input. They would automatically be added to any blank fields on your page:
<input type="text" placeholder="----" value="asdf" name="notempty"
title="This has a placeholder, but doesn't show it because the input is filled with something" />
<input type="text" placeholder="----" value="" name="empty"
title="This is empty, so it shows the dashes" />
The placeholder text would not be included in your $_POST
data. In this example, $_POST['empty']
would be blank.
The placeholder
attribute is supported by many of the modern browsers, but not IE9:
http://caniuse.com/#feat=input-placeholder
There are various jQuery plugins that imitate this effect as well. You can read about a few of them here:
How do I get placeholder text in firefox and other browsers that don't support the html5 tag option?
Upvotes: 1
Reputation: 318232
jQuery's :empty
finds elements with no children, not elements without a value, and as an input can't have children it finds nothing.
And jQuery's is()
returns a boolean, not a collection.
jQuery's replaceWith
replaces the entire element, not just the value.
Check the value instead.
$('#form input[type=text]').val(function(_, val) {
return val.length === 0 ? '------' : val;
});
or
$('#form input[type=text]').filter(function() {
return this.value.length === 0;
}).val('------');
Throw in a $.trim
to trim off whitespace if needed
Upvotes: 3