I've run into a strange problem: I'm trying to get a <form>
element from javascript but I'm unable to.
my html code is created dynamically by php:
<form id="form_color_{$color->id}" action="?com=saveColor" method="POST">
<!--some input elements-->
<a href="javascript:saveColor({$color->id})">
<img src="{$webSiteUrl}assets/img/admin/floppy_disk_24.png" />
<span> Save</span>
</a>
</form>
so the page will contain various form_color_
forms like form_color_1 form_color_2
etc...
when the image is clicked this javascript function is called:
function saveColor(id){
$("#form_color_"+id).submit();
}
the funtion correctly receive the id param but it doesn't submit the form.
if I try to get the form element I get null
function saveColor(id){
form = 'form_color_'+id;
var doc = document.getElementById(form);
alert(doc);
$("#form_color_1").submit();
}
the function works perfectly with other forms.
here's an example of the code produced by php:
<form id="form_color_1" action="?com=saveColor" method="POST">
<!--some input elements-->
<a href="javascript:saveColor(1)">
<img imgc="http://10.10.10.46/c5liveOnLine/assets/img/admin/floppy_disk_24.png" />
<span> Save</span>
</a>
</form>
what am I missing?
What you have should work, unless of course there's another form on the page with the same id
(which would be bad).
But note that you don't need id
s for this at all, and so if id
s are the problem the solution is not to use them. Just give your triggering element a class:
<form action="?com=saveColor" method="POST">
<!--some input elements-->
<a class="submit-form">
<img src="{$webSiteUrl}assets/img/admin/floppy_disk_24.png" />
<span> Save</span>
</a>
</form>
...and then use a handler to submit the form containing the element:
$(document).on("click", ".submit-form", function() {
$(this).closest("form").submit();
});
I used a delegated handler because I didn't see any reason not to, and it means you can add and remove forms dynamically if you need to.
But note that you don't need JavaScript for this at all, unless you're doing more than just submitting the form. button
elements can be styled to look any way you want them to look, and their default action is to submit the form they're in. So:
<form action="?com=saveColor" method="POST">
<!--some input elements-->
<button>
<img src="{$webSiteUrl}assets/img/admin/floppy_disk_24.png" />
<span> Save</span>
</button>
</form>
Just use CSS to make the button look the way you want it to look.
Here's an example styling button
to look like a link:
button {
border: none;
background-color: transparent;
color: blue;
}
button:hover {
text-decoration: underline;
}
<form action="?com=saveColor" method="POST">
<!--some input elements-->
<button>
<img src="{$webSiteUrl}assets/img/admin/floppy_disk_24.png" />
<span> Save</span>
</button>
</form>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments