Reddy
Reddy

Reputation: 1385

preventDefault() is not working

My Goal is to remove the action of checkbox checking by clicking on its label Below is my code..

   $('TABLE TBODY TR TD').each(function()
   {
     $(this).find('input').each(function()
                            {
                                $('label for='+$(this)+'').preventDefault();
                            });
    });

Below is the associated HTML..

  <table>
        <tr><input type="checkbox" id="a1"><div><label for="a1">ClickMe</lable></div></tr>
  </table>

Please someone help me.

Upvotes: 4

Views: 1840

Answers (2)

Domenic
Domenic

Reputation: 112817

preventDefault is not a method on the jQuery object itself. It is a method on the event that gets passed to a given event handler.

In addition, your label selector syntax is wrong (you forgot brackets and tried to concatenate a jQuery object with a string), and you have unnecessarily nested two eaches.

Better:

$("table tbody tr td input").each(function () {
    $("label[for='" + this.id + "']").click(function (event) {
        event.preventDefault();
    });
});

Sample JSFiddle: http://jsfiddle.net/s9D4n/

Possibly even simpler, but admittedly not functionally equivalent:

$("label").click(function (event) {
    event.preventDefault();
});

Upvotes: 4

rahul
rahul

Reputation: 187020

You just need to remove for attribute from the label.

<label>ClickMe</label>

Upvotes: 1

Related Questions