I spent a few hours tonight with ChatGPT and figured out how to…
- Change Opacity on Form Submit: The form’s opacity is changed upon submission to visually indicate that it’s “disabled,” although it technically remains active.
- Enter Key as Form Submit: The script recognizes the Enter key press in a single textarea as a trigger to submit the form.
- Loading GIF Display: A “loading” GIF from my media folder is displayed when the form is submitted, enhancing the user experience during the processing time.
- Form Submission Handling: The form is submitted while incorporating the above features.
Note: The form has a page redirection setting that refreshes the same page upon submission, which updates the CPT grid. This method was chosen for simplicity, though alternative AJAX-based methods could be explored for a more seamless experience. Go to your form settings - default confirmation to adjust accordingly.
Below is the complete code with comments. If you need to adjust it for your needs, just copy this entire message into ChatGPT and have a friendly convo
Related discussion that made me post this here as this forum post has been locked: Disable Submit button after submit
How to use:
- Install WPCode plugin
- You will figure out the rest… easy peasy
Code below with comments:
<script>
jQuery(document).ready(function($) {
// Set focus to the textarea on page load
$('#input_2_1').focus();
// Handle Enter keypress and click on submit button
$('#input_2_1').keypress(handleSubmit);
$("#gform_2 [type=submit]").on("click", handleSubmit);
function handleSubmit(e) {
// Check if Enter key or submit button is pressed
if (e.type === 'keypress' && (e.which !== 13 || e.shiftKey)) {
return; // Ignore other keypresses
}
e.preventDefault(); // Prevent default form submission
// Change opacity of the textarea and submit button
var textarea = $('#input_2_1');
var submitButton = $("#gform_2 [type=submit]");
textarea.css("opacity", 0.2);
submitButton.css("opacity", 0.2);
// Position and display the GIF animation
positionAndShowGif();
// Submit the form after making changes
$(this).closest("form").submit();
}
function positionAndShowGif() {
// Create and display the GIF animation
var gif = $('<img>', {
id: 'loading-gif',
src: 'https://littlewinsapp.com/wp-content/uploads/2023/12/bouncy-top-hat.gif',
css: {
position: 'absolute',
display: 'none'
}
}).appendTo('body');
// Calculate GIF position over the textarea
var offset = $('#input_2_1').offset();
var width = $('#input_2_1').outerWidth();
var height = $('#input_2_1').outerHeight();
gif.css({
top: offset.top + (height / 2) - (gif.height() / 2), // Center vertically
left: offset.left + (width / 2) - (gif.width() / 2) // Center horizontally
}).show();
}
});
</script>