2015-06-12 5 views
0

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

моя форма тег в HTML:

<form class="text-left" method="post" action="" onsubmit="return myFunction();"> 

ниже скрипт (этот скрипт в моей голове секции):

$(document).ready(function() { 

    //the number generators and sum of the two numbers 
    var numberOne = Math.floor((Math.random() * 10) + 1); 
    var numberTwo = Math.floor((Math.random() * 10) + 1); 
    var sum = numberOne + numberTwo; 

    //write the math question to the div 
    document.getElementById("captchaOutput").innerHTML = numberOne+ " og " +numberTwo; 
    //alert(sum); 

    function myFunction(){ 
     var humanInput = $('#captchaInput').val(); 

     if(humanInput == sum){ 

      $("#captcha_service_err").css("display", "inline") 
      $("#captchaInput").css("border-color", "red"); 
      return false; 
     } 
      $("#captcha_service_err").css("display", "none") 
     $("#captchaInput").css("border-color", ""); 
     return true;  
    } 
}); 
+0

почему вы смешивание JavaScript и jquery? – Mivaweb

+0

Используйте глобальный объект, чтобы его объявить! –

+0

Просто добавьте окно.myFunction = function() {'вместо' function myFunction() {', и он должен работать! –

ответ

7

Это потому, что я поместил свою функцию внутри функции готовности документа?

Да. Объявление функций (например, var операторов), охваченных функцией, объявленной внутри.


Если вы хотите использовать myFunction как глобальный затем переместить его, а переменные зависит от того, из анонимной функции вы объявляете его в.


В качестве альтернативы, вы могли бы явно создать глобальный, который ссылается на это:

window.myFunction = myFunction 

лучшее решение, однако, является не использовать глобальное в первую очередь.

Удалите атрибут onsubmit и вместо этого привяжите обработчики событий с помощью JavaScript.

$('form').on('submit', myFunction); 

Убедитесь, что вы захватить объект события:

function myFunction(e){ 

Затем предотвратить поведение по умолчанию формы представления, если вы не хотите, чтобы представить:

$("#captchaInput").css("border-color", "red"); 
e.preventDefault(); 
1

Это происходит потому, что myFunction определяется в пределах объема $(document).ready и есть не видно наружный. Определить его вне вместе со своими зависимыми переменными

//the number generators and sum of the two numbers 
var numberOne = Math.floor((Math.random() * 10) + 1); 
var numberTwo = Math.floor((Math.random() * 10) + 1); 
var sum = numberOne + numberTwo; 
$(document).ready(function() { 
    //write the math question to the div 
    document.getElementById("captchaOutput").innerHTML = numberOne + " og " + numberTwo; 
    //alert(sum); 
}); 

function myFunction() { 
    var humanInput = $('#captchaInput').val(); 

    if (humanInput == sum) { 

     $("#captcha_service_err").css("display", "inline") 
     $("#captchaInput").css("border-color", "red"); 
     return false; 
    } 
    $("#captcha_service_err").css("display", "none") 
    $("#captchaInput").css("border-color", ""); 
    return true; 
} 

Update

Снимите встроенный onsbumit для формы и использовать on(), как показано ниже

$(document).ready(function() { 

    //the number generators and sum of the two numbers 
    var numberOne = Math.floor((Math.random() * 10) + 1); 
    var numberTwo = Math.floor((Math.random() * 10) + 1); 
    var sum = numberOne + numberTwo; 

    //write the math question to the div 
    document.getElementById("captchaOutput").innerHTML = numberOne+ " og " +numberTwo; 
    //alert(sum); 

    $('form').on('submit', function(){ 
     var humanInput = $('#captchaInput').val(); 

     if(humanInput == sum){ 

      $("#captcha_service_err").css("display", "inline") 
      $("#captchaInput").css("border-color", "red"); 
      return false; 
     } 
      $("#captcha_service_err").css("display", "none") 
     $("#captchaInput").css("border-color", ""); 
     return true;  
    }); 
}); 
+0

Спасибо, очень помогли, и ЭТО РАБОТАЛО! –

+0

@MartinNielsen, рад, что он это сделал. Но я предлагаю вам следовать ответам Квентина и связываться с jquery '.on ('submit')' вместо – AmmarCSE

+0

@MartinNielsen, если вы не знаете, как, позвольте мне или Квентину узнать, что мы можем предоставить более подробную информацию – AmmarCSE

1

Попробуйте использовать window объект здесь:

$(document).ready(function() { 
    //the number generators and sum of the two numbers 
    var numberOne = Math.floor((Math.random() * 10) + 1); 
    var numberTwo = Math.floor((Math.random() * 10) + 1); 
    var sum = numberOne + numberTwo; 

    //write the math question to the div 
    document.getElementById("captchaOutput").innerHTML = numberOne+ " og " +numberTwo; 
    //alert(sum); 

    window.myFunction = function() { 
     var humanInput = $('#captchaInput').val(); 

     if(humanInput == sum){ 

      $("#captcha_service_err").css("display", "inline") 
      $("#captchaInput").css("border-color", "red"); 
      return false; 
     } 
      $("#captcha_service_err").css("display", "none") 
     $("#captchaInput").css("border-color", ""); 
     return true;  
    } 
}); 
-1
var sum = 0; 
    $(document).ready(function() { 

      //the number generators and sum of the two numbers 
      var numberOne = Math.floor((Math.random() * 10) + 1); 
      var numberTwo = Math.floor((Math.random() * 10) + 1); 
      sum = numberOne + numberTwo; 

      //write the math question to the div 
      document.getElementById("captchaOutput").innerHTML = numberOne+ " og " +numberTwo; 
      //alert(sum); 


     }); 

     function myFunction(){ 
       var humanInput = $('#captchaInput').val(); 

       if(humanInput == sum){ 

        $("#captcha_service_err").css("display", "inline") 
        $("#captchaInput").css("border-color", "red"); 
        return false; 
       } 
        $("#captcha_service_err").css("display", "none") 
       $("#captchaInput").css("border-color", ""); 
       return true;  
      } 
+1

Это не сработает, потому что 'myFunction()' все еще пытается использовать 'sum'. – nnnnnn