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?
There could be multiple reason for this:
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
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);
}
If still issue persists then try to add the debugger in the function can check the call trace in google developers console.
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);
});
Related
I need help in javascript, my code in woocomerce (checkout) is:
<script type="text/javascript">
document.getElementById("billing_city").onkeyup = function validarDistrito(event){
// do stuff
var billinginfo = document.getElementsByName("billing_city")[0].value;
var distritoArray= ["Barranco","Breña","Jesús María","La Victoria","Lince","Miraflores","Pueblo Libre","San Borja","San Isidro","San Luis","San Miguel","Surco","Surquillo","Callao","La Molina","Lima Cercado","Magdalena", "Rimac", "Lima Metropolitana"];
console.log(billinginfo);
for (i = 0; i < distritoArray.length; i++) {
if(distritoArray[i].toUpperCase() == billinginfo.toUpperCase()){
document.getElementById('payment_method_bacs').disabled = false;
alert('igual');
}else{
document.getElementById('payment_method_bacs').disabled = true;
}
}
event.preventDefault();
}
</script>
The code work very good, but then a few seconds later it updated and returns to a previous state. And I use the method preventDefault (); but it does not work in wordpress.
PD: the same holds true using jquery.
Thanks!
You are using e.preventDefault(); when it must be event.preventDefault();
take a look at validarDistrito(event), you named event the variable
try this code
<script>
document.getElementById("billing_city").onkeyup = function validarDistrito(event){
// do stuff
var billinginfo = document.getElementsByName("billing_city")[0].value;
var distritoArray= ["Barranco","Breña","Jesús María","La Victoria","Lince","Miraflores","Pueblo Libre","San Borja","San Isidro","San Luis","San Miguel","Surco","Surquillo","Callao","La Molina","Lima Cercado","Magdalena", "Rimac", "Lima Metropolitana"];
console.log(billinginfo);
for (i = 0; i < distritoArray.length; i++) {
if(distritoArray[i].toUpperCase() == billinginfo.toUpperCase()){
document.getElementById('payment_method_bacs').disabled = false;
return;
}else{
document.getElementById('payment_method_bacs').disabled = true;
}
}
event.preventDefault();
}
</script>
the thing is that distroArray will keep validating the rest of it, so if the input value is equal to one of the values of the array, you need to stop validating
Let me start off by saying that this is my second day learning jQuery so I'm very much a beginner.
I've written a document ready function and all components are working except the countryField.change function I wrote. I'm pretty sure the web application already has a change function for this field and I'm not sure if there can be two of the same event on a field. When I say it's not working, I set a breakpoint in the Chrome debugger and it never enters the function.
Maybe I have to temporarily pause the existing event, run my code, then re-enable the default event?
Any help would be appreciated. Thanks.
$(document).ready(function(){
var submitReady = true;
var phoneField = $("p.phone").find("input");
var phoneExt = $("p.Ext").find("input");
var countryField = $("p.country").find("input");
var stateField = $("p.state").find("input");
var provinceField = $("p.Province").find("input");
var regex = /^\([2-9][0-9]{2}\)\s+[2-9][0-9]{2}\-[0-9]{4}$/;
phoneField.mask('(000) 000-0000', {placeholder: "(###) ###-####"});
phoneExt.mask('00000', {placeholder: "#####"});
$('#pardot-form').submit(function() {
// DO STUFF
if (submitReady) {
if (phoneExt.val() != "") {
phoneField.val(phoneField.val() + ' x' + phoneExt.val());
return true;
}
}
else {
return false;
}
});
phoneField.focusout(function() {
if (regex.test($(this).val())) {
submitReady = true;
return true;
}
else {
$(".form-field.phone").after( "<p class='tempError error no-label'>Please Enter a valid phone number: (###) ###-####</p>");
submitReady = false;
}
});
phoneField.focus(function() {
$(".tempError").remove();
});
countryField.change(function() {
phoneField.val("");
provinceField.val("");
stateField.val("");
submitReady = true;
});
});
You can try
$( "p.country" ).change(function() {
phoneField.val("");
provinceField.val("");
stateField.val("");
submitReady = true;
});
Am getting key Combination from the server. Based on that am assigning key Combination to function dynamically. The below code is working for last iteration in loop. how below code is work for all iterations.
In my page i have two buttons save and cancel the below code is working for last iteration in for loop, It means btnCanel button triggers if i press key for save function.Any suggestions. hope understand my question.
$(document).ready(function fn() {
var keyCombination = new Object();
keyCombination['btnAdd'] = "Alt+S";
keyCombination['btnCancel'] = "Alt+C";
for (var k in keyCombination) {
if (keyCombination.hasOwnProperty(k)) {
shortcut.add(String(keyCombination[k]), function () {
var btnAdd = document.getElementById(String(k));
btnAdd.focus();
btnAdd.click();
});
}
}
});
if i give like this means it is working
shortcut.add("Alt+S", function () {
var btnAdd = document.getElementById('btnAdd ');
btnAdd .focus();
btnAdd .click();
});
shortcut.add("Alt+C", function () {
var btnCancel = document.getElementById('btnCancel');
btnCancel.focus();
btnCancel.click();
});
but if i try to add dynamically its overriding help me this issue.
Thanks in Advance.
I created a separate function outside the document.ready function like this now its working fine.
$(document).ready(function fn() {
var keyCombination = new Object();
keyCombination['btnAdd'] = "Alt+S";
keyCombination['btnCancel'] = "Alt+C";
for (var k in keyCombination) {
if (keyCombination.hasOwnProperty(k)) {
Set_KeyCombinations(k, keyCombination);
}
}
});
function Set_KeyCombinations(k, keyCombination) {
shortcut.add(String(keyCombination[k]), function () {
var eleId = document.getElementById(String(k));
if (eleId) {
if ($('#' + String(k).trim()).css('display') !== 'none' && eleId.getAttribute("disabled") !== "disabled") {
eleId.click();
eleId.focus();
}
}
});
}
Try this:
var keyCombinations = [ "Ctrl+Shift+X" , "Ctrl+Shift+Y" ];
for(var i=0; i<keyCombinations.length; i++){
(function(shorcutCombination){
shortcut.add(shorcutCombination,function() {
alert("i am " + shorcutCombination);
});
})(keyCombinations[i]);
}
The idea is that you need to preserve the value of keyCombinations[i]
as i increases in the loop. Tested this here: Openjs
Ok, I have been trying to make it work past 30 minutes.
Everything works fine in this jsfiddle :- http://jsfiddle.net/6KT4R/1/
But when I run this on my local wamp server..nothing seems to happen!.
Code :-
<script src="js/jquery-1.8.2.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
</script>
<input type="text" name="ltc" id="input-ltc">
<input type="text" name="btc" id="input-btc" readonly>
What is possibly wrong here?
Thanks.
The script is executing before the DOM is loaded. Try:
window.onload = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
As m59 suggested there is an improved method of executing the event onload. The following code snippet is preferred:
var funct = function(){
var inputLtc = document.getElementById('input-ltc'),
inputBtc = document.getElementById('input-btc');
var constantNumber = 0.022632;
inputLtc.onkeyup = function () {
var result = parseFloat(inputLtc.value) * constantNumber;
inputBtc.value = !isNaN(result) ? result : '';
};
}
if (window.attachEvent){
window.attachEvent('onload', funct);
}else{
element.addEventListener('load', funct, false);
}
You're getting your element references before the elements exist on the page. In the jsfiddle, the javascript is executed after the html. You could reproduce this by moving your script tag below the related html. It is best practice to put all script tags just before the end of the body like this:
<script></script>
</body>
Otherwise, you'll need to register an event listener to watch for page load and execute your javascript code then.
window.addEventListener('load', function() {
console.log('loaded!');
});
with jQuery:
$(document).ready(function() {
console.log('loaded!');
});
//this is the jQuery shorthand for the same function above
$(function() {
console.log( "loaded!" );
});
I have some jQuery plugin that changes some elements, i need some event or jQuery plugin that trigger an event when some text input value changed.
I've downloaded jquery.textchange plugin, it is a good plugin but doesn't detect changes via external source.
#MSS -- Alright, this is a kludge but it works:
When I call boxWatcher() I set the value to 3,000 but you'd need to do it much more often, like maybe 100 or 300.
http://jsfiddle.net/N9zBA/8/
var theOldContent = $('#theID').val().trim();
var theNewContent = "";
function boxWatcher(milSecondsBetweenChecks) {
var theLoop = setInterval(function() {
theNewContent = $('#theID').val().trim();
if (theOldContent == theNewContent) {
return; //no change
}
clearInterval(theLoop);//stop looping
handleContentChange();
}, milSecondsBetweenChecks);
};
function handleContentChange() {
alert('content has changed');
//restart boxWatcher
theOldContent = theNewContent;//reset theOldContent
boxWatcher(3000);//3000 is about 3 seconds
}
function buttonClick() {
$('#theID').value = 'asd;lfikjasd;fkj';
}
$(document).ready(function() {
boxWatcher(3000);
})
try to set the old value into a global variable then fire onkeypress event on your text input and compare between old and new values of it. some thing like that
var oldvlaue = $('#myInput').val();
$('#myInput').keyup(function(){
if(oldvlaue!=$('#myInput').val().trim())
{
alert('text has been changed');
}
});
you test this example here
Edit
try to add an EventListner to your text input, I don't know more about it but you can check this Post it may help
Thanks to #Darin because of his/her solution I've marked as the answer, but i have made some small jQuery plugin to achieve the same work named 'txtChgMon'.
(function ($) {
$.fn.txtChgMon = function (func) {
var res = this.each(function () {
txts[0] = { t: this, f: func, oldT: $(this).val(), newT: '' };
});
if (!watchStarted) {
boxWatcher(200);
}
return res;
};
})(jQuery);
var txts = [];
var watchStarted = false;
function boxWatcher(milSecondsBetweenChecks) {
watchStarted = true;
var theLoop = setInterval(function () {
for (var i = 0; i < txts.length; i++) {
txts[i].newT = $(txts[i].t).val();
if (txts[i].newT == txts[i].oldT) {
return; //no change
}
clearInterval(theLoop); //stop looping
txts[i].f(txts[i], txts[i].oldT, txts[i].newT);
txts[i].oldT = $(txts[i].t).val();
boxWatcher(milSecondsBetweenChecks);
return;
}
}, milSecondsBetweenChecks);
}