Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a form submit on div click using jquery?

I already tried this in single php file but doesn't work out, so i tried now in two separate php file one for form and another one for process.

How to submit the form on a div or link click?

Code i tried

$(document).ready(function(){
    jQuery('.web').click(function () {
        $("#g_form").submit();
        alert('alert');
    });
});

FORM

<form action="p.php" id="g_form" method="POST">
    <input type="text" name="f1" value="">
    <input type="submit" value="submit!" name="submit"/>
</form>

<div class="web">click</div>

Here is the process file code p.php

<?php
if(isset($_POST['f1'])){
    echo $_POST['f1'];
} ?>

When i click the submit button the form is submitting but when i click the .web div it is not submitting the form even i get the alert message but not submitting.

What wrong am doing here? It'll be helpful if i get a idea.

like image 720
rram Avatar asked Feb 03 '14 17:02

rram


2 Answers

.submit() docs

Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.

You give your submit button a name of submit, which the above passage tells you will cause "confusing failures"

So if you accessed the dom element and looked at the .submit property you would see that since you name the button submit instead of .submitbeing a function its a reference to the buttons dom element

HTML

<form action="p.php" id="g_form" method="POST">
    <input type="text" name="f1" value="">
    <input type="submit" value="submit!" name="submit"/>
</form>

<div class="web">click</div>

JS

//Get the form element
var form = $("#g_form")[0];
console.log(form.submit);
//prints: <input type="submit" value="submit!" name="submit"/>

And when you change the submit name

<form action="p.php" id="g_form" method="POST">
    <input type="text" name="f1" value="">
    <input type="submit" value="submit!" name="psubmit"/>
</form>

<div class="web">click</div>

JS

var form = $("#g_form")[0];
console.log(form.submit);
//prints: function submit() { [native code] } 

so simply give your submit button a different name that does not conflict with a form's properties.

like image 163
Patrick Evans Avatar answered Sep 21 '22 23:09

Patrick Evans


You can trigger submit button click.

<form action="p.php" id="g_form" method="POST">
<input type="text" name="f1" value="">
<input type="submit" value="submit!" id="f_submit" name="submit"/>
</form>

<div class="web">click</div>



 $(document).ready(function(){
       jQuery('.web').click(function () {
        $("#f_submit").trigger( "click" );
          alert('alert');
    });
  });

DEMO : http://jsfiddle.net/awladnas/a6NJk/610/

like image 42
Awlad Liton Avatar answered Sep 19 '22 23:09

Awlad Liton