skip to Main Content

I added a inline Javascript code to my metabox callback function.

add_action( 'add_meta_boxes', function() {
    add_meta_box( 'catalog-item', 'Gegevens', 'catalog_details_callback', 'catalog', 'advanced' );
});

function catalog_details_callback( $post ) {
    <input type="text" class="price" name="price" id="price"/>
    <script type="text/javascript">
    document.getElementById('price').onfocusout = function() {
        var regex = /^(d+[,]+d{2})$/;
        if (regex.test(this.value) == false ) {
            this.value = this.value.replace(/([^(d|,)]|,{2})/g, "");
        }
        var before = this.value.replace(",", ".");
        var roundoff = parseFloat(before).toFixed(2);
        var after = roundoff.replace(".", ",");
        alert(after);
    }
    </script>
}

If the function is triggered the function fires the alert twice.
Does anybody know how I fix this?

2

Answers


  1. There could be multiple reason for this:

    1. Please check if you have multiple event listeners. If so, try to check your condition. understand about event listeners here: https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event

    2. onfocusout bubbles, means if you have any event written on parent as well as child then both gets called. try to add

     document.getElementById('price').onfocusout = function(event) {
                event.preventDefault();
                event.stopPropagation();
            var regex = /^(d+[,]+d{2})$/;
            if (regex.test(this.value) == false ) {
                this.value = this.value.replace(/([^(d|,)]|,{2})/g, "");
            }
            var before = this.value.replace(",", ".");
            var roundoff = parseFloat(before).toFixed(2);
            var after = roundoff.replace(".", ",");
            alert(after);
        }
    
    
    1. If still issue persists then try to add the debugger in the function can check the call trace in google developers console.
    Login or Signup to reply.
  2. I had the same issue with WordPress.
    This works for me

        const price_field = document.getElementById('price');
        price_field.addEventListener('focusout', (event) => {
            var regex = /^(d+[,]+d{2})$/;
            if (regex.test(price_field.value) == false ) {
                this.value = price_field.value.replace(/([^(d|,)]|,{2})/g, "");
            }
            var before = price_field.value.replace(",", ".");
            var roundoff = parseFloat(before).toFixed(2);
            var after = roundoff.replace(".", ",");
            price_field.value = after;
            alert(after);
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search