Submitting data from an input of type “image” via Ajax rather than form submit

StackOverflow https://stackoverflow.com/questions/4539599

  •  13-10-2019
  •  | 
  •  

سؤال

Basically, I want to use an image input, but I don't want to have to submit form to get the result, I want to get the X and Y coordinates from the click on the image input, then submit them via ajax.

Now, I realize I can just put the image input in its own form, then submit to a hidden iframe and check for a result on an interval (I'm doing that for an ajax uploader right now), but it seems a little hokey. I also realize I can get my mouse position via javascript from any click, that's not really what I'm asking

Can I use the input of type image like this? Is there a way to have the click on the image input just set it's value then call some JavaScript to execute my ajax call?

هل كانت مفيدة؟

المحلول

I was going through my old questions and I saw that this one was never answered adequately. I don't remember if I figured this out "way back when", but I do know how to do it now.

Just check the offsetX and offsetY of the click event of an image input. It should be offset to the image input you clicked on.

$('input[type=image]').click(function(e) {
     //alert the clicked position.
     alert(e.offsetX + ',' + e.offsetY);
});

نصائح أخرى

Take a look here: http://jsfiddle.net/pfLtm/

As you see, that code can be easily modified to something like this:

$("#MyInput").click(function(event) {
    var oPos = $(this).position();
    $(this).attr("mouse_x", (event.pageX - oPos.left));
    $(this).attr("mouse_y", (event.pageY - oPos.top));
    return false;
});

This will store the X and Y position of the click as attributes of the element itself. Test case: http://jsfiddle.net/pfLtm/1/

Instead of returning false you can invoke the AJAX call for example.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top