this.form.submit() not working after clicking div element in form
Asked Answered
W

5

10

I was trying to test form submission using mouse clicks but the form doesn't seem to submit with vanilla javascript.

I'm using this simple markup and code:

<form name="form" id="price" action="" method="post">
<div class="category" name="price" value="50 dollars" 
onClick="this.form.submit();"
>price</div>

</form>

<?php
echo $_POST['price'];

?>

I can submit the form with Jquery, but I don't understand why this.form.submit() is not working with vanilla javascript? I'm using Chrome to test this.

Wsan answered 5/12, 2011 at 7:30 Comment(2)
Div tag can't containt attribute "value"Perot
My answer should work with all major browsers. Please select it as the correct answer.Cooncan
S
20

A div is not a form element. There is no this.form for it.

You can still do document.forms.form.submit() (.form since you have name="form")

Site answered 5/12, 2011 at 7:31 Comment(4)
Ah, that makes sense. I was trying to see if I could reduce the markup for forms using div instead of inputWsan
If that's all you're trying to accomplish, I'd recommend that you go with an input anyway, as it is built to be a form element.Site
There is a simpler a way to do this. See my answer belowCooncan
@monarch: A matter of taste, perhaps, but relying on parentNode will mean your code will break if the markup changes. If you're doing something trivial like wrapping the submit button in another div, you might check whether the presentation is broken, but you wouldn't expect that change to break functionality. This solution will only break if the name of the form changes, and I'd argue its name is more inherently tied to its functionality. You wouldn't change that without thorough functionality tests.Site
A
4

Your code might work if you tried something like this:

onClick="document.forms["price"].submit();"

this in your case actually refers to the div tag, not the document object which contains the reference to the form itself.

Ader answered 5/12, 2011 at 7:35 Comment(0)
O
1

Use following code if your form name is "filter-form"

onclick="return document.forms.filter-form.submit();"
Oldcastle answered 29/7, 2013 at 9:0 Comment(1)
That works, but a better way would be to use the parentNode attribute, as per my answerCooncan
R
0

A div isn't a form element (thus no .form property) nor has it a value. I think you wanted <input> instead of <div>.

Refugia answered 5/12, 2011 at 7:32 Comment(1)
sometimes you do want/need to use a div.Cooncan
C
0

This is an older question, but this should work

onclick="this.parentNode.form.submit()"
Cooncan answered 8/11, 2014 at 6:39 Comment(1)
Not my down-vote, but I suspect it was because this only works if there are no nesting markup between the form and the element with this attribute. You could need this.parentNode.parentNode.form.submit() or worse.Midyear

© 2022 - 2024 — McMap. All rights reserved.