简体   繁体   中英

How to populate a form field using jQuery

I've the following jQuery that I've used which allows you to click anywhere within an image (which is a picture of a map) and when you click, it places a marker on the map:-

<img src="images/marker.png" id="marker" style="display: none; position: absolute;" />
<img src="images/square.png" id="map"/>

$('#map').click(function(e)
{
   $('#marker').css('left', e.pageX).css('top', e.pageY).show();
   // Position of the marker is now e.pageX, e.pageY 
   // ... which corresponds to where the click was.
 });

The idea is that when you've clicked on the map, a co-ordinate is populated into a form field so you can submit the form with that information of where you clicked.

What do I need to change within my jQuery to add this functionality? Also, will this work accurately within IE?

Thanks

You can use hidden input for form fields to save co-ordinates. Please see below code :

Assuming xValue and yValue are your form fields, then create two hidden inputs inside form tag like :

<form action="...">
    <input type="hidden" id="xValue" name="xValue">
    <input type="hidden" id="yValue" name="yValue">
</form>

Modify your jQuery like :

$('#map').click(function(e)
{
   $('#marker').css('left', e.pageX).css('top', e.pageY).show();
   // Position of the marker is now e.pageX, e.pageY 
   // ... which corresponds to where the click was.

   $('#xValue').val(e.pageX);
   $('#yValue').val(e.pageY);
 });

And when you submit form, you can read xValue and yValue.

Is this what you are looking for?

<img src="images/marker.png" id="marker" style="display: none; position: absolute;" />
<img src="images/square.png" id="map"/>
<form action="...">
    <input type="hidden" name="coord[x]" id="coordX" />
    <input type="hidden" name="coord[y]" id="coordY" />
    <input type="submit" value="submit" />
</form>

$('#map').click(function(e)
{
    $('#marker').css('left', e.pageX).css('top', e.pageY).show();
    $('#coordX').val(e.pageX);
    $('#coordY').val(e.pageY);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM