tags:

views:

33

answers:

2
+1  Q: 

jquery, run form

Hi, how to activate the button. If the condition is true, I want to send data through a method (POST).

<script>
$(document).ready(function(){                   
    var count = 0;
    if(count == 2)
    {
        //run form
    }
});
</script>
</head>                                                                 
<body>
<form action = "" method = "post">
<input type = "text" name = "name" />
<input type = "submit" id = "ok"/>
</form>
+1  A: 

Try

$("#ok").trigger("click");
rahul
I think this is an elegant solution. Is there any difference compared to $("myform").submit(); ?
Tx3
yup, The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Its a shortcut for $("#myform").trigger("submit");. Where as click event can be binded to any element in the DOM.
Ayaz Alavi
+3  A: 
$(document).ready(function(){                   
    var count = 0;
    if(count == 2)
    {
        $("myform").submit(function(e){
             //This function is called before form is posted
             if(mycondition == true)
                return true;   //that will post the form
             else
                 return false; // that will stop posting form 

               //Here you can also change values of input fields and also do  
               // validation on them.
               // instead of return false you can also use e.preventDefault() 
               //  that will stop this event to do what it usually does that
                // is submit the form.
           }).trigger("submit"); //if you want it to submit immediatly
        }
    });

OR if you dont wanna use form id then

 $(document).ready(function(){                   
        var count = 0;
        if(count == 2)
        {
            $("body form").find(":input[type=submit][id=ok]").trigger("click");
        }
    });

    <form action = ""  method = "post">
    <input type = "text" name = "name" />
    <input type = "submit" id = "ok"/>
    </form>
Ayaz Alavi
If you are using id selector then no need for any additional selectors to be combined.
rahul
just for filtering more precisely since amateurs usually assign same id to more than one element.
Ayaz Alavi
Its not valid to assign same id to more than one element.
rahul
well it is not valid but it is possible and browser wont complain about that.
Ayaz Alavi