Tayyab Vohra
Tayyab Vohra

Reputation: 1662

jQuery $(this).addClass not working

I have a list of textboxes in which a user can drop a letter but when a wrong letter is dropped inside the textbox I want to addClass("danger") I want to addClass only on the wrong letter textbox I have also attached a screenshot to illustrate the problem.

demo

The textbox has a class with the name of box assigned.

Now my drop function is given below.

function dropabc(event) {

    if ($(objBox).attr("correct1") != event.target.id) {

        $(".imageError").fadeIn('slow').delay(1000).hide(0);
        console.log("error");
        $(this).addClass('danger');

    } else {

        console.log(event.target.id);
        console.log("ok");
    }
}

$(this).addClass("danger")

However, this is not working, I only want to add the danger class to the box on which a wrong value is dropped.

//makes all the textbox red
$(".box").addClass("danger")

Any help would be very appreciated!

This is the jQuery UI drag and droppable function which is working fine:

        var objBox;
    $('.drag').draggable({

 revert: true,
        helper: 'clone',
        cursor: 'pointer',

       start: function(event, ui) {

            $(this).fadeTo('fast', 0.5);
                objBox=$(this);
        },
        stop: function(event, ui) {
            $(this).fadeTo(0, 1);
     }
});

$("#textbox, .box").droppable({
     hoverClass: "hoverPath",
    drop: function(event, ui) {

              var $this = $(this);
                        if ($this.val() == '') {
                            $this.val(ui.draggable.text());
                             $(this).addClass("checkDiv");
                             $(this).each(function(i, el){
                        $(el).addClass(myid[3]);
                                        });

                        }

        var empty = $(this).parent().find("input").filter(function() {
            return this.value === "";
        });
        if(empty.length) {
        console.log(empty.length);
        }
        else{
            console.log("done");
        }

                    }
});

This is the PHP code which is echo the number of textbox:

for($x = 0 ; $x < count($code_words); $x++){

    echo "<input id='".$code_words[$x]."' ondrop='dropabc(event)' class='box' type='textbox'/>";

        }

Upvotes: 0

Views: 3002

Answers (1)

Evochrome
Evochrome

Reputation: 1215

You're just running a function when you embed the ondrop event inside your input tag.

So instead of embedding it try using the jQuery on("drop").

$(document).on("drop", ".box", function(event){
      if ($(objBox).attr("correct1") != event.target.id) {

        $(".imageError").fadeIn('slow').delay(1000).hide(0);
        console.log("error");
        $(this).addClass('danger');

    } else {

        console.log(event.target.id);
        console.log("ok");
    }
})

Great it helped you :)

Cheers,

Upvotes: 1

Related Questions