Help using draggable positions!

I have a webpage which the user can drag a marker around inside a div and the script then shows the standard js alert box with the final positions of the marker once the user has stopped dragging it about. What I need to do is get the script to add these values to two hidden input elements in the page. Can anyone tell me how I can do this please?

The script I’m using is below, any help with this would be greatly appreciated.

$( init );

function init() {
  $('#makeMeDraggable').draggable( {
    cursor: 'move',
    containment: 'content',
    stop: handleDragStop
  } );
}

function handleDragStop( event, ui ) {
  var offsetXPos = parseInt( ui.position.left );
  var offsetYPos = parseInt( ui.position.top );
  alert( "Drag stopped!\
\
Offset: (" + offsetXPos + ", " + offsetYPos + ")\
");
}

Thanks in advance.

You could just use something like this, assuming that your form has an identifier on the form tag itself:


$('#myForm [name="xpos"]').val(offsetXPos);

Please don’t be tempted to place identifier elements on all of your form controls. That’s just a waste. Just the form tag itself is enough to be identified. From the form element you can easily get to all of the form controls within it from there, without needing to add any more fluff to your form.

Thanks for the help with this Paul. I’m not sure where I need to put the code you suggested as I’ve tried it and its not working for me. I think I’m missing something. The code I now have is below. Would you mind having a look and pointing out where I’m going wrong with this please?

<script type="text/javascript">

$( init );

function init() {
  $('#makeMeDraggable').draggable( {
    cursor: 'move',
    containment: 'content',
    stop: handleDragStop
  } );
}

function handleDragStop( event, ui ) {
  var offsetXPos = parseInt( ui.position.left );
  var offsetYPos = parseInt( ui.position.top );
  //alert( "Drag stopped!\
\
Offset: (" + offsetXPos + ", " + offsetYPos + ")\
");
  $('#myForm [name="xpos"]').val(offsetXPos);
}

</script>

<form name=“myForm” method=“post” action=“process.php”>
<input name=“xpos” type=“hidden” value=“”>
</form>

<div id=“content”>
<div id=“makeMeDraggable”> </div>
</div>

There doesn’t seem to be anything at first glance that would interfere with things, so a closer look at a test page the demonstrates the problem will allow me to investigate the issue on a much deeper level.

Hi Paul would you be able to have a look at this if I send you a link to the page where I’m having problems please?
this part is now holding up the whole project and I just can’t figure it out.

any help much appreciated. Thanks

The form should have an identifier, such as:


<form id="addjob" ...>

That way you can easily access your hidden form field with:


$('#addjob [name="xpos"]').val(offsetXPos);