Tutorial :HTML + Javascript form submission question



Question:

I have authored a html + javascript form which displays a set of images along with a submit button. The user can select the images he or she is interested in and when the user clicks the image, I change the image border to indicate image selection.

And when the user clicks on the submit button, I would like my server side script to receive the image uris associated with the selected images for further processing.

I am a JS newbie. I would like to know how best to do this. Will I need a global javascript array which gets populated with the selected image URIs? And this array can then be submitted as part of HTTP POST?

Any tips/pointers will be helpful.


Solution:1

If I were you, I’d make sure it works without JavaScript too. E.g.

<form action="" method="POST">      <label for="image_1">          <img src="image_1_uri" alt="Image 1" />          <input type="checkbox" name="images" id="image_1" value="image_1_uri" />      </label>        <label for="image_2">          <img src="image_2_uri" alt="Image 2" />          <input type="checkbox" name="images" id="image_2" value="image_2_uri" />      </label>        <input type="submit" />  </form>  

Then adapt your border-adding JavaScript to work when the label is clicked on, rather than the image.

Hide the checkboxes via CSS if you’re not keen on them being there. (You’ll need to add a class to the checkboxes to do this in older versions of Internet Explorer.)


Solution:2

Try this:

 //...let's suppose this is the image you change the border of on click..   <img src="whatever" onclick="createHidden(this);" />    <script type="text/javascript">    function createHidden(field)    {      var hdn = document.createElement("input");      hdn.setAttribute('type', 'hidden');      hdn.setAttribute('name', 'hdn[]');      hdn.setAttribute('value', field.src); // populate images src now        var frm = document.getElementsByTagName("form")[0];      frm.appendChild(hdn);    }  </script>  

Now you can access the images' paths in the hdn array in your server-side script.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »