How to remove an input value before submitting it in Wordpress with the Ultimate member plugin

600 views Asked by At

I want to know how to remove an input value before submitting a profile form in Wordpress with Ultimate Member plugin. I've been stuck with this for a whole week.

The thing is that I have conditional fields in the profile form that if the user does not select, they still save their values ​​when the form is submitted. The plugin does not remove the values ​​from the hidden fields conditionally, which is a problem if you want to send these fields elsewhere with REST API.

I couldn't do it with PHP so I added a script inside the principal function to try and clear the values. This work when user refresh the form, but not when user submit the form with the hook um_after_user_updated

function remove_before_send () {
        ?>
            <script>
                var elements = document.querySelectorAll('.um-is-conditional');
                for (var i = 0; i < elements.length; i++) {
                elements[i].childNodes[1].childNodes[0].value = "";
                }
            </script>
        <?php
}
add_action('um_profile_content_main', 'remove_before_send');

EDIT: Thanks to the comment of @JB_DELR. You really gave me all the clues. This is my final code (im not proud, because i wanted to use php, but this is the best i could do)

function remove_before_send () {
        ?>
            <script>
                var boton = document.querySelector("div.um-left.um-half > input");
                boton.addEventListener("click", function(){
                var elements = document.querySelectorAll('.um-is-conditional');
                for (var i = 0; i < elements.length; i++) {
                if (elements[i].style.display == "none") {
                elements[i].childNodes[1].childNodes[0].value = "";
                }
                }
                });
            </script>
        <?php
}
add_filter( 'um_profile_content_main', 'remove_before_send');
1

There are 1 answers

1
JB_DELR On BEST ANSWER

Your js script need to handle the form submit event, prevent default submiting, remove unnecessary fields an submit the form itself.

Something like this:

<script>
var form = document.querySelector(<select the form>);
form.onsubmit = function(e) {
   e.preventDefault(); // don't submit the form right now;
   var elements = document.querySelectorAll('.um-is-conditional');
   for (var i = 0; i < elements.length; i++) {
     elements[i].childNodes[1].childNodes[0].value = "";
   }
   // to remove element, this remove the input field, so field is no more in the request
   // elements[i].childNodes[1].removeChild(elements[i].childNodes[1].childNodes[0]);
}
form.submit();
</script>