запуск одной функции javascript вызывает другую непреднамеренную функцию - PullRequest
0 голосов
/ 04 декабря 2011

При проверке формы при размытии запускается проверка данных.В этой форме у меня есть 3 различных возможных триггера.Но если один срабатывает, я получаю два окна с предупреждениями, что означает, что сработали две функции.

Форма (html-код):

<form id="processpayment" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<table class="paypal">
<tbody>
<tr>
<td class="etiqueta" width="50%"><label>Nombre</label></td>
</tr>
<tr>
<td><input id="nombre" class="requerido" type="text" name="nombre" value="" /></td>
</tr>
<tr>
<td class="etiqueta"><label>Forma de comunicación</label></td>
</tr>
<tr>
<td><span id="medio" class="requerido">Skype</span></td>
</tr>
<tr>
<td class="etiqueta"><label id="label_medio_id">Usuario de Skype</label></td>
</tr>
<tr>
<td><input id="medio_id" class="requerido" type="text" name="medio_id" value="" /></td>
</tr>
<tr>
<td class="etiqueta"><label id="confirm:label_medio_id">Verifica usuario de Skype </label></td>
</tr>
<tr>
<td><input id="confirm:medio_id" class="requerido" onblur="confirm_data(this.id);" type="text" name="confirm:medio_id" value="" /></td>
</tr>
<tr>
<td class="checkbox" colspan="2"><input id="warningpaypalverified" class="requerido" type="checkbox" name="warningpaypalverified" value="payment constraints acknowledged" /><label class="alerta">Pagos de tarjeta de crédito son procesados inmediatamente.<br /><br /> En caso de que use su cuenta PayPal, es necesario ser verificado por PayPal con anterioridad.<br /><a id="explain" class="explain" onclick="explain('La conversación inmediata tiene como característica el comunicarse con alguien inmediatamente.\n\nCuando PayPal no ha verificado su cuenta estos pagos toman mas de 24 horas.\n\nSi desea una conversación inmediata, pague con tarjeta de crédito.')">Por que es esto necesario</a></label></td>
</tr>
<tr>
<td id="paypal" colspan="2"><input type="hidden" name="notify_url" value="http://root.com/process/listener.php" /> <input type="hidden" name="locale.x" value="es_XC" /> <input class="alldata" type="hidden" name="custom" value="" /> <input type="hidden" name="cmd" value="_s-xclick" /> <input type="hidden" name="image_url" value="http://root.com/images/root_logo.png" /> <input type="hidden" name="hosted_button_id" value="THISANDTHAT" /> <input class="paypal" type="image" name="submit" src="https://www.paymentobjects.com/es_XC/i/btn/btn_buynowCC_LG.gif" alt="PayPal, la forma más segura y rápida de pagar en línea." /> <img src="https://www.paymentobjects.com/es_XC/i/scr/pixel.gif" border="0" alt="" width="1" height="1" /></td>
</tr>
</tbody>
</table>
</form>

У меня следующий код JavaScript:

function clear_fields(fieldid, confirm_fieldid){
        document.getElementById(fieldid).value = "";
        if (typeof(confirm_fieldid) !== 'undefined'){ document.getElementById(confirm_fieldid).value = ""; }
        document.getElementById(fieldid).focus();
        return false; 
    }

function validate_email(email_field_id){

        email = typeof(email_field_id) != 'undefined' ? document.getElementById(email_field_id) : function(){alert('Parameter error when calling Validate Email. Check your form'); return;}();

        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

        if( reg.test(email.value) == false ) {

            alert('El email que ingresaste no es correcto. Por favor, intenta nuevamente siguiendo este formato tucorreo@ejemplo.com');

            return clear_fields(email_field_id);

        } else { return true; }

    }

function confirm_email( confirm_email_field_id ){

        var confirmemail = typeof(confirm_email_field_id) != 'undefined' ? document.getElementById(confirm_email_field_id) : function(){alert('Parameter error when calling javascript function confirm_email(). Check your form, and make sure input field for confirm email calls the function confirm_email("confirm:email_id");'); return;}();

        var confirmemailarray = confirmemail.id.split(':'); 

        var email = document.getElementById(confirmemailarray[1]);

        if( email.value === confirmemail.value ) {    

            return true;

        } else { 

            alert("ERROR: \"Email\" no coincide con \"Confirmar Email\". \n Agrega tu \"Email\" y CONFIRMA este Email")

            return clear_fields(email.id, confirmemail.id);

        }

    }

function confirm_data(confirm_data_field_id){

        if( typeof(confirm_data_field_id) == 'undefined'){

            alert('Parameter error when calling javascript function confirm_data. Check your form, and make sure input field to confirm data calls the function confirm_data("confirm:data_field_id");'); 

            return;

        } else {

            var confirmidarray = confirm_data_field_id.split(':'); 

            thedata = document.getElementById(confirmidarray[1]);

            confirmthedata = document.getElementById(confirm_data_field_id);

            if( thedata.value == confirmthedata.value ) return true;
            else {

                thedatalabel = document.getElementById('label_' + thedata.id);
                confirmthedatalabel = document.getElementById('confirm:label_' + thedata.id);

                alert('ERROR: Los datos que ha ingresado en los campos de informacion \n\n' + thedatalabel.innerHTML + '\n' + confirmthedatalabel.innerHTML + '\n\n NO COINCIDEN. \n\n Para proceder con su pago agregue la informacion correcta.' );

                return clear_fields( confirmidarray[1], confirmidarray[0] + ':' + confirmidarray[1] );

            }

        }

    }

Почему это происходит?

Какие изменения мне нужно сделать?

Спасибо

1 Ответ

1 голос
/ 04 декабря 2011

В некоторых браузерах alert() может вызывать события фокуса (потому что фокус переходит к окну предупреждения, а затем возвращается к странице).При отладке такого рода проблем лучше использовать console.log(), который не мешает сосредоточиться, чтобы записать, что происходит, и вы можете просто просмотреть журнал, чтобы увидеть, что на самом деле произошло, не изменив поведения.

...