views:

50

answers:

2

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.

A: 

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("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.

Sarfraz
Correct me if I'm wrong, but shouldn't the newly created field by part of the Form element ? Now's it's part of the body (which doesn't get submitted when invoking submit.
Edelcom
@Edelcom: You are right, i was wonderting about that but forgot to write it the time i answered this question. thanks for infoming :)
Sarfraz
A: 

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.)

Paul D. Waite
Thanks guys. This was helpful :-)