USP Pro can do a LOT, but there always are fringe cases where some task needs done that requires an alternate solution. To help dial it in, here is a growing collection of simple, plug-&-play jQuery snippets for fine-tuning the behavior of any USP Form.
Notes (read first)
1) jQuery is required for these snippets to work, so make sure that it is included on the page.
2) These snippets are written to be included directly in USP Form content (via the Edit Form screen). If instead you include the snippets via the plugin’s “CSS/JS” Settings or via your theme’s JavaScript file, remove the <script>
tags. That is, the <script>
tags are necessary only if adding the snippets directly to form content.
3) Remember to test thoroughly before going live with any of these snippets.
Grab data, use for hidden field
Let’s say you have a form that includes the following fields:
.
.
.
[usp_url]
<input name="usp-title" type="hidden" value="User Submitted Title">
.
.
.
The [usp_url]
shortcode will display the URL field in the form. But let’s say now that you want to use the URL as the default Post Title. To do so, we can use the following snippet of jQuery to copy the value of the URL field (usp-url
) to the hidden input (usp-title
):
<script>
jQuery(document).ready(function($) {
$('input[name="usp-url"]').change(function() {
$('input[name="usp-title"]').val($(this).val());
});
});
</script>
By changing the input names, this technique can be used and extended for a variety of form manipulations and customizations.
Use form URL as the submitted URL
Similar to the previous technique. Here we are grabbing the URL of the page where the form is located, and using it as the value of the URL field (which is hidden). The first step is to create a URL custom field and add it to the form. For example something like this:
type#hidden|label#null|class#form-url
Then after adding the custom field to the form, add the following jQuery snippet:
<script>
jQuery(document).ready(function($) {
$('.usp-submit').click(function() {
var formURL = $(location).attr('href');
$('.form-url').val(formURL);
});
});
</script>
Save changes and done. Once the above two steps are complete, the page URL will be used as the value of the URL field. All happens silently in the background, invisible to the user.
Use any element as submitted post title
This code snippet is similar to the previous, here we are using the value of h1
(can be any element) for the submitted post title. First, replace the [usp_title]
shortcode in your form with the following hidden field:
<input name="usp-title" id="usp-title" type="hidden">
Next, include the following jQuery snippet:
<script>
jQuery(document).ready(function($) {
$('.usp-submit').click(function() {
var usp_title = $('.target-element h1').text();
$('#usp-title').val(usp_title);
});
});
</script>
With this code in place, when the user clicks the form submit button, the contents of the h1
tag will be used as the value of the hidden title field. So after the post is submitted, its title will be the same as the target element (h1
in this example). The only change that’s required in the code above is to replace .target-element h1
with the actual element that you want to use for the submitted post title.
Note that this technique can be modified for use with any form field. Simply replace #usp-title
with the field’s ID attribute.
Clear default field values
Nice little snippet for targeting field values and clearing any auto-filled information. Just include the following:
<script>
jQuery(document).ready(function($) {
$('.usp-input-name').val('');
$('.usp-input-email').val('');
});
</script>
Here we are auto-clearing the values of the Name and Email fields. Customize to suit your needs.
Replace option text
This snippet replaces the text of the specified <option>
element.
<script>
jQuery(document).ready(function($) {
$('select option:contains("replace-this")').text('With whatever');
});
</script>
By default, USP <option>
elements have the same value
and text. So this snippet can be used to change the text to whatever is desired.
Set default selected option
This snippet can be used to set the default selected <option>
for the category field (when displaying as a select/dropdown menu). So instead of the default selected option being “Please select..”, it will be the option that is specified via the following code:
<script>
jQuery(document).ready(function($){
$('.usp-input-category').val('24');
});
</script>
Here we are targeting the class of the category field, .usp-input-category
, and setting its selected <option>
to the one that has a value
of 24
. Of course, you can change the option value to the one that you would like to use. Also, you can target other fields by changing .usp-input-category
to the class of the tag select field, taxonomy select field, or any other select/dropdown field. It may also work on radio fields, but I have not tested it.
Here is an alternate technique for setting the selected option:
$('.usp-input-category option[value="24"]').attr('selected',true);
And this technique targets the <option>
based on its text instead of its value
:
$('.usp-input-category option:contains("Web Design")').prop('selected',true);
So the option that has text of “Web Design” will be the default selected option when the page loads.
Remove attributes, clear placeholder input text
Although USP Pro can be set to exclude the placeholder attribute, we can use it as an example for removing field attributes in general.
<script>
jQuery(document).ready(function($) {
$('.usp-input').removeAttr('placeholder');
});
</script>
Here we are targeting all form inputs that have a class of .usp-input
and removing the placeholder
attribute. The joy of this technique is that you can swap out the selector and target any specific tags, and you can change the value of removeAttr()
to specify any attribute that you would like to remove.
Hide/disable error messages
Quick snippet to hide any default form-submission errors on the page:
<script>
jQuery(document).ready(function($) {
$('#usp-form-errors').remove();
});
</script>
Customize as desired to target specific errors.
Change the form’s action attribute
This snippet changes the form’s action
attribute:
<script>
jQuery(document).ready(function($) {
$('.usp-form').attr('action', 'http://example.com/custom.php');
});
</script>
Customize the specified URL to match your custom location.
Remove the “for” attribute
Here’s how to remove the for
attribute for any label(s):
<script>
jQuery(document).ready(function($) {
$('label[for="usp-category"]').each(function() { $(this).removeAttr('for'); });
});
</script>
Lots of possibilities here, could customize to target any field and remove any attribute.
Add tag that’s the same as selected category
This jQuery snippet grabs the value of the selected category (from dropdown/select menu), and then sets it as the value for a hidden tag field.
<script>
jQuery(document).ready(function($) {
$('select[name="usp-category"]').change(function() {
$('input[name="usp-tags"]').val($(this).find('option:selected').text());
});
});
</script>
So in your form you would have the category field:
[usp_category label="Category" include="all" type="dropdown" multiple="false"]
..and also the hidden tags field:
<input name="usp-tags" value="fixed" type="hidden">
Replace field value on form submit
This snippet can be used to change a field value when the form is submitted:
<script>
jQuery(document).ready(function($) {
$('.usp-submit').click(function() {
if ($('#usp-custom-yourfieldname').val() == '') {
$('#usp-custom-yourfieldname').val('whatever');
}
});
});
</script>
This is sort of a general technique that may be applied in numerous scenarios, depending on your form configuration, goals, etc.
Customize text in any label
Quick jQuery snippet to replace/customize a string of text in any form label(s). Just add the following code:
<script>
jQuery(document).ready(function($) {
$('label:contains("TEXT TO BE REPLACED")').each(function() {
var html = $(this).html();
html = html.replace('TEXT TO BE REPLACED', '<strong>TEXT TO BE REPLACED</strong>');
$(this).html(html);
});
});
</script>
There are a million things you could do with this. As-is, it simply wraps a <strong>
tag around the text to be replaced. You can customize things to replace text, add spans and other markup, etc.
Customize id attribute based on label value
This snippet grabs the label text for each input and used it as the input’s id
attribute.
<script>
jQuery(window).load( function($) {
var $label = jQuery('label');
$label.each(function() {
$this = jQuery(this);
var $newLabID = $this.text().toLowerCase().trim().replace(/ /g,'-');
$this.attr('ID',$newLabID);
});
});
</script>
This snippet makes all id
values lowercase, replacing blank spaces with hyphens, and trimming unwanted space.
Note that if you’re thinking about using this snippet to make radio and checkbox id
s more specific, so as to apply styles to individual options, there is no need as of USP Pro version 2.4. Newer versions of the plugin have option-specific id
attributes.
Remove empty options from select/dropdown menus
Here is a quick snippet that removes any empty options from select/dropdown menus:
<script>jQuery('select option').filter(function() { return !this.value || jQuery.trim(this.value).length == 0 || jQuery.trim(this.text).length == 0; }).remove();</script>
No edits are required. If you want to target only a specific field (instead of all select fields), replace the jQuery selector to make it more specific. For example, if we only want to remove blank options for the USP Tags field, the code would look like this:
<script>jQuery('#usp-tags option').filter(function() { return !this.value || jQuery.trim(this.value).length == 0 || jQuery.trim(this.text).length == 0; }).remove();</script>
So just replace #usp-tags option
in the above code with the actual selectors for the field(s) you want to target.
Require exactly “3” checkboxes to be checked
Three or any other number. Here is the magic code:
<script>
jQuery(document).ready(function($) {
$('.usp-custom-require input').on('change', function(e) {
var limit = 3;
var count = $('.usp-custom-require input:checked').length;
if (count > limit) $(this).prop('checked', '');
});
$('.usp-form').submit(function(e) {
var limit = 3;
var count = $('.usp-custom-require input:checked').length;
if (count < limit) {
alert('Please select exactly '+ limit +' items');
$('.usp-submit').attr('disabled', false).css('cursor', 'default');
return false;
}
return true;
});
});
</script>
As-is, this snippet requires the user to check exactly 3 checkboxes. You may need to modify the code to account for any specific checkbox fields you are targeting.
Limit number of selected options
For example, if you want to limit the number of tags that the user can select from the Tags field, add the following snippet:
<script>
jQuery(document).ready(function($) {
var last_valid_selection = null;
$('#usp-tags').change(function(event) {
if ($(this).val().length > 2) {
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
}
});
});
</script>
Notice the #usp-tags
selector? That is what targets the Tags field. You can change that to match whichever field you would like (e.g., Category field, custom select field). Also you can change the number of allowed selected options by changing 2
to whatever number. No other changes need made for this code to work.
Add markup to textarea
This snippet adds the specified markup to any <textarea>
:
<script>
jQuery(document).ready(function($) {
var content = '<div>Custom Markup</div>';
$('textarea').append(content.replace(/\&/g, '&').replace(/</g, '<').replace(/>/g, '>'));
});
</script>
You can customize the markup by editing the value of the content
variable. Also you can change the selector from textarea
to something more specific, like the class name of the Post Content field, .usp-content
.
Replace error-message text
This snippet enables you to change the default text displayed when the submitted form is returned with errors:
<script>
jQuery(document).ready(function($) {
$('.usp-error').each(function(index) {
var text = $(this).text();
$(this).text(text.replace('mycustomfield', 'My Custom Field'));
});
});
</script>
So for example, if you have a Custom Field defined as follows:
data-required#true|name#mycustomfield
The above jQuery snippet will replace the default error message, so instead of the error displaying “Required field: mycustomfield”, it will display “Required field: My Custom Field”. To target a specific Custom Field, change mycustomfield
to the name
you are using for the Custom Field (e.g., name#mycustomfield
).
Note: this snippet is required only for Custom Field errors. To customize Primary Field errors (like Name, Email, URL, et al) visit the plugin’s “More” settings/tab.
Replace placeholder attribute
This snippet can be used to customize any placeholder attribute:
<script>
jQuery(document).ready(function($) {
$('.class').attr('placeholder', 'New Value');
});
</script>
You can target any form field by replacing .class
with your selector. You also can change the attribute from placeholder
to whichever attribute you want to customize. Lastly, you can change the New Value
to the value that you would like to use for the attribute value.
Disable the submit button after first click
Quick jQuery snippet to disable the submit button after the user clicks it the first time when submitting the form. This can be useful to prevent users from clicking repeatedly on the submit button for whatever reason. Just add the following jQuery snippet to your form:
<div class="submitting"></div>
<script>
jQuery(document).ready(function($) {
$('.usp-form').on('submit', function(e) {
$('.usp-submit').css('cursor', 'wait');
$('.usp-submit').attr('disabled', true);
$('.submitting').text('Submitting form...');
});
});
</script>
With this code in place, the submit button will be disabled after the user clicks it the first time to submit the form. Also, while the form is being submitted, the empty “submitting” <div>
will display a message that says “Submitting form…”, to help the user understand what’s up. Additionally, you may want to look at the plugin settings for “Display Form on Success” (Advanced tab), and also “Unique Post Titles” and “Unique Post Content” (General tab). These settings can be used to help control the rate of form submissions, spam, etc.
Display overlay after form submit
This jQuery snippet displays an overlay with an animated “spinner” image when the form is submitted. Add the following code to your USP Form content (or add via plugin settings or theme files).
<style>.usp-form input[disabled], .usp-form input[disabled]:active, .usp-form textarea[disabled], .usp-form textarea[disabled]:active { color: #555; background-color: graytext; border-color: #555; cursor: inherit; }</style>
<div class="submitting"></div>
<script>
jQuery(document).ready(function($) {
$('body').append('<div id="overlay" style="display:none; position:absolute; top:0; left:0; z-index:9999; width:100%; height:100%; background:rgba(0,0,0,0.7);"><img src="/wordpress/wp-content/plugins/usp-pro/img/usp-loading.svg" width="150" height="150" style="position:absolute; top:50%; margin-top:-75px; left:50%; margin-left:-75px; border:0;"></div>');
$('.usp-form').on('submit', function(e) {
e.preventDefault();
$('#overlay, #spinner').show();
$('.usp-submit').css('cursor', 'wait');
$('.usp-submit').attr('disabled', true);
$('.usp-form :input').attr('disabled', true);
$('.submitting').text('Submitting form...');
});
});
</script>
This code is meant to give you a starting point for further development, so you are encouraged to understand and modify the code as needed for your implementation. Some things to keep in mind as you add and test this code:
- USP Pro version 2.8 and better provides an animated spinner image that you can use (it is located in
/usp-pro/img/usp-loading.svg
) - To make sure the spinner image is loaded properly, change the path (
/wordpress/...
) in the jQuery code above to match the location of your WP installation - You can use a free online service to generate your own spinner image
Important: If Parsley validation is enabled, you will need to add a couple of lines to the jQuery code. The form-submit part of the code should look like this (added lines are highlighted with inline comments):
$('.usp-form').on('submit', function(e) {
if ($(this).parsley().isValid()) { // <-- required when Parsley is enabled
e.preventDefault();
$('#overlay, #spinner').show();
$('.usp-submit').css('cursor', 'wait');
$('.usp-submit').attr('disabled', true);
$('.usp-form :input').attr('disabled', true);
$('.submitting').text('Submitting form...');
} // <-- required when Parsley is enabled
});
These new lines check to make sure that the form has been validated by Parsley before it displays the overlay and spinner image. No other changes are required, but again, this code is provided as a starting point for your own customization and further development.
Hide duplicate error message
When more than form is included on the page (not officially supported), duplicate error messages may be displayed. In order to prevent that, you can add this jQuery snippet to hide the second error message.
<script>
jQuery(document).ready(function($) {
$('.usp-pro-form:nth-of-type(2) .usp-success').hide();
});
</script>
For more than two forms, you can add more lines to the snippet, for example:
<script>
jQuery(document).ready(function($) {
$('.usp-pro-form:nth-of-type(2) .usp-success').hide();
$('.usp-pro-form:nth-of-type(3) .usp-success').hide();
$('.usp-pro-form:nth-of-type(4) .usp-success').hide();
});
</script>
It would be crazy to include 4 forms on the same page, but if you do it, that code will hide all but the first error message. Again, displaying multiple forms on the same page is not something that officially is supported by the plugin.
Combo select + input for taxonomies
This snippet enables you to add a combination of select field and text input for custom taxonomy fields. So if the user doesn’t find the required term in the select field, the text input will display to enable the user to enter their own terms.
Step 1
Add to each select box a custom attribute: custom="data-other=true"
. For example, something like this:
[usp_taxonomy label="City" tax="worker_cities" terms="all_include_empty" type="dropdown" multiple="false" required="false" custom="data-other=true"]
<label for="usp-taxonomy-worker_cities" class="usp-label usp-label-taxonomy">Other Cities (comma separated)</label>
<input name="usp-taxonomy-worker_cities" type="text" value="" data-required="false" maxlength="99" placeholder="Other Cities" class="usp-input usp-input-taxonomy">
This is just an example; you will need to add fields that correspond to your specific form configuration.
Step 2
Add this jQuery snippet via the plugin settings or via any other method:
<script>
jQuery(document).ready(function($) {
$('*[data-other=true]').change(
function(event) {
var index = $(":input").index(this);
var next = $(":input:eq(" + (index + 1) + ")");
if (this.selectedIndex == 0) {
next.prop('disabled', false);
} else {
next.prop('disabled', true);
next.val('');
}
})
});
});
<script>
Depending on the markup used for the fields added in Step 1, you may need to customize this snippet with the correct variables, etc.
Customize the “Please select…” for select fields
One thing that can be tricky to customize is the default text displayed by the browser for the “Please select…” text that appears within the select field itself. To get at it, here is a small snippet of jQuery that you can add directly to the bottom of the form:
<script>
jQuery(document).ready(function($) {
$('.usp-input-category option:contains("Please select..")').text('Pick your poison..');
});
</script>
In that code, you can change “Pick your poison..” to whatever you would like to replace the default “Please select..”. Note that, as written, this snippet works with the category field, which is added to any form using the following shortcode:
[usp_category]
You can adapt the snippet to other select fields by getting the field’s class name and using it to replace .usp-input-category
.
Update!
As of USP Pro version 2.0, you can customize the “Please select…” text for Category, Taxonomy, and Tag fields using the default
attribute. Here is a quick example:
[usp_tags default="Pick your tag.."]
[usp_category default="Pick your category.."]
[usp_taxonomy default="Pick your taxonomy.."]
If you would rather exclude the default “Please select…” string, use default="null"
.
And for Custom Fields, you can customize the default “Please select…” text using the option_default
attribute, like so:
field#select|options#null:Option 1:Option 2:Option 3|option_default#Pick yer poison..|option_select#null|label#Options