I have a number of text input fields in an event registration channel that I would like to be pre-poulated with defaults and so not require entering anything unless it's different. This thread gives the javascript to add in the instructions box for Matrix fields, but I want it for a single Text input field and my javascript is rubbish.
-
I'm surprised someone hasn't written an add-on for this already. That could be really helpful for content admin.– Alex RoperCommented Feb 19, 2013 at 21:16
-
I agree, I've searched for an addon in the past to do just this, and I found other requests that went unanswered on the old EE forums.– Paul FrostCommented Feb 19, 2013 at 22:00
1 Answer
Since Field Instructions will allow HTML and JS, you can add the following in the Field Instructions for that custom field:
<script type="text/javascript">
$(document).ready(function() {
if ($('#field_id_23').is(':empty')) {
$('#field_id_23').val('This is the default text');
}
});
</script>
Just be sure to change field_id_23
to the correct field_id in your instance.
Important note: If you are entering this snippet in a custom field's Field Instructions make sure it does not use space characters for the indentation. If you copy and paste directly from here it will and they will be encoded to
which will break the JS.
As an alternative to using Field Instructions to hold your JavaScript, CP CSS & JS is useful for adding snippets of JS to the Control Panel.
Note that the above jQuery assumes you would never want to leave the text input blank. If that isn't the case, you'll want to incorporate a check that this is a new entry instead of relying on the .is(':empty')
conditional:
<script type="text/javascript">
$(document).ready(function() {
if ($('input[name="entry_id"]').val() == '0') {
$('#field_id_23').val('This is the default text');
}
});
</script>
-
1Thanks Alex I wanted to be able to insert multiple lines and needed to add a line break, so after a bit of trial and error I found that this works:
<script type="text/javascript"> $(document).ready(function() { if ($('input[name="entry_id"]').val() == '0') { $('#field_id_23').val('1st default text line'+'\n'+'2nd line'+'\n'+'3rd line'); } }); </script>
not sure if this is the best method though. Commented Feb 20, 2013 at 12:09 -
I've now installed CP CSS & JS extension, but am not sure if it's a good idea to put all my Custom field JS there or in each individual instruction field. It seems a bit remote and hidden from where it's affecting. But may be easier to maintain. Commented Feb 20, 2013 at 18:08