Home > other >  How to select element id in droppable method?
How to select element id in droppable method?

Time:02-24

I am learning jQuery and doing small project . I have big box and 4 smaller boxes, when I grab small box and drop it to big box , I want to see what id has small box. alert method show me undefined . Do you know how to fix this ? thanks

 <span  id="b">blue</span>  // this is one small box

const quizData = [
   {
     question : '1. Who created JS?',
     a: 'Musk',
     b: 'Eich',
     c: 'Mask',
     d: 'Pask',
     correct: 'b'
   }, ...
]

loadquiz()



function loadquiz() {

  const currentQdata= quizData[currentQuiz]
   $('.question').html(`<h5>${currentQdata.question}</h5>`)
   $('#a').html(`${currentQdata.a}`)
   $('#b').html(`${currentQdata.b}`)
   $('#c').html(`${currentQdata.c}`)
   $('#d').html(`${currentQdata.d}`)


   let box = $('.box10')
   box.draggable()
  
   $('.question').droppable({
    drop: function(e,ui) {
     const a = e.target.dataset.id
     alert(a)               // this is showing me undefined
     }
    })
  } 


CodePudding user response:

Consider the following.

$(function() {
  var quizData = [{
    question: '1. Who created JS?',
    a: 'Musk',
    b: 'Eich',
    c: 'Mask',
    d: 'Pask',
    correct: 'b'
  }];

  function loadquiz() {

    var currentQdata = quizData[0];
    $('.question').html("<h5>"   currentQdata.question   "</h5>");
    $('#a').html(currentQdata.a);
    $('#b').html(currentQdata.b);
    $('#c').html(currentQdata.c);
    $('#d').html(currentQdata.d);

    $('.box10').draggable();

    $('.question').droppable({
      drop: function(e, ui) {
        var dropId = ui.draggable.attr("id");
        console.log(dropId);
      }
    });
  }

  loadquiz();
});
.question {
  border: 1px solid #ccc;
  padding-bottom: 2em;
}

.box10 {
  padding: .4em;
  border: 1px solid black;
  width: 10em;
  margin: 3px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>

<div ></div>
<div id="a" ></div>
<div id="b" ></div>
<div id="c" ></div>
<div id="d" ></div>

Droppable passes an Event and UI Object to the callback. See: https://api.jqueryui.com/droppable/#event-drop

drop( event, ui ) Triggered when an accepted draggable is dropped on the droppable (based on thetolerance option).

  • ui
    • draggable - A jQuery object representing the draggable element.
  • Related