Home > Software design >  Javascript: Is there a way to name submit functions?
Javascript: Is there a way to name submit functions?

Time:12-29

I am trying to return the "value" variable to use on another function but it says that the "getData" is not defined

$('form').submit(function getForm(e){
        e.preventDefault();
        var value = $(this).data('test');
        return value;
    });

    fromForm = getForm();

    function alertForm(){
        alert(fromForm);
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form data-test="1">
    <input type="text"/>
    <input type="submit" />
</form>
<form data-test="2">
    <input type="text"/>
    <input type="submit" />
</form>

CodePudding user response:

I think this is what you want

$('form').submit(function(e){
    e.preventDefault();
    var value = $(this).data('test');
    alertForm(value);
});


function alertForm(fromForm){
    alert(fromForm);
}

CodePudding user response:

What you are trying to do is to get data-test attirbute value and us it in your alertForm Function. You can use a variable to having a greater scop to get this value from the handler of the the submit function but it is not clean. The best way is to get the value directly from the dom as follow.

    function alertForm(){
    var fromForm =$("form").data('test');
        alert(fromForm);
    }
  • Related