0

I came across a problem while trying to select a DOM element inside a callback function using Jquery, I always get undefined value, note that there is nothing wrong with the key variable, the only problem is that Jquery can't seem to select the input element and get its value.

 $(".mybutton").on('click', function(){
     var key = $(this).attr('key');
     __CANVAS.mousemove(function(evt){
       var mousePos = getMousePos(__CANVAS2, evt);
       $("#x[" + key + "]").val(); // undefined
       $("#y[" + key + "]").val(); // undefined
   });
});

This is the html

 <input id="x['.$key.']" name="x'.$key.'" type="text"  value="x'.$key.'" width="50px">
                                     x
 <input id="y['.$key.']" name="y'.$key.'" type="text"  value="y'.$key.'" width="50px">
                                     y
 <button type="button" key="'.$key.'" class="mybutton">Create/Edit</button>

Thanks in advance.

Berzerkfar
  • 45
  • 5
  • 1
    That is not a valid `id` attribute (brackets aren't allowed). spec: https://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-name Additionally, brackets are special characters in jQuery selectors so your selector is not being treated a literal string. You may be able to escape the brackets so the string is treated literally though: https://stackoverflow.com/questions/2364982/jquery-selector-for-inputs-with-square-brackets-in-the-name-attribute – Rob M. May 22 '17 at 22:00
  • 1
    As a side note: it is a bad idea to attach an event listener inside a click handler, as you will accumulate event handlers. – trincot May 22 '17 at 22:10
  • @RobM. HTML5 has relaxed the character restrictions on IDs. – Barmar May 22 '17 at 22:20
  • When you `console.log(key)` after assigning it's value to `$(this).attr('key')`, what do you get? – wlh May 22 '17 at 22:36
  • Rob M. I changed the id to `id="x'.$key.'"` but still have the same problem undefined, – Berzerkfar May 22 '17 at 22:50
  • trincot I delete the event listener after the user clicks on the canvas – Berzerkfar May 22 '17 at 22:51
  • wlh with every input I get the its key number, there's nothing wrong with it. – Berzerkfar May 22 '17 at 22:53

0 Answers0