Created
November 26, 2022 20:52
-
-
Save FrancoStino/e07147c05c6287b697844f46557dffc7 to your computer and use it in GitHub Desktop.
Allow percentage and only type number input field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter('wp_footer', 'allow_percentage_and_only_type_number_input_field'); | |
function allow_percentage_and_only_type_number_input_field(){ | |
// Only on the product page. | |
if ( ! is_product() ) { | |
return; | |
} | |
?> | |
<script> | |
jQuery(function($) { | |
function setInputFilter(textbox, inputFilter, errMsg) { | |
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) { | |
textbox.addEventListener(event, function(e) { | |
if (inputFilter(this.value)) { | |
// Accepted value | |
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){ | |
this.classList.remove("input-error"); | |
this.setCustomValidity(""); | |
} | |
this.oldValue = this.value; | |
this.oldSelectionStart = this.selectionStart; | |
this.oldSelectionEnd = this.selectionEnd; | |
} else if (this.hasOwnProperty("oldValue")) { | |
// Rejected value - restore the previous one | |
this.classList.add("input-error"); | |
this.setCustomValidity(errMsg); | |
this.reportValidity(); | |
this.value = this.oldValue; | |
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); | |
} else { | |
// Rejected value - nothing to restore | |
this.value = ""; | |
} | |
}); | |
}); | |
} | |
setInputFilter(document.getElementById("uni_cpo_sfrido_manuale-field"), function(value) { | |
return /^\d*(\.\d+)?%?$/.test(value); }, "Inserire una percentuale valida"); | |
}); | |
document.getElementById('uni_cpo_sfrido_manuale-field').addEventListener('input', function() { | |
this.value = this.value.replace('%','')+'%'; //remove existing % and add again | |
}); | |
</script> | |
<?php | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment