ki9
ki9

Reputation: 5575

.click() won't work on children

I have some HTML like:

<html>
<body>
    <div id="parent">
         <input id="child1" onclick="clickedInline();" style="z-index:999" disabled readonly>Child One</input>
         <input id="child2">Child Two</input>
    </div>
</body>
</html>

And some jquery like this:

// Wait for page to load
$(function(){

    // Log clicked item
    $('*').click(function(){
        console.log($(this).prop("tagName")+'#'+$(this).attr('id'));
    });

    // I want this to happen
    $('#child1').click(function(){
        alert("It worked!");
    });

    // I've tried this too
    $('#child1').on("click", function(){
        alert("It worked!");
    });

    // And even this
    $('#parent').on("click", '#child1', function (){
        alert("It worked!");
    });

});

// This doesn't work either
function clickedInline(){
    alert("It worked!");
}

When I click on #child1, no alert pops up, and this gets logged:

DIV#parent
BODY#undefined
HTML#undefined

The .click() event seems to be firing only on the parent element, and not the child. I don't want it to fire when #child2 is clicked.

Upvotes: 1

Views: 85

Answers (2)

Dave Norm
Dave Norm

Reputation: 185

Hi your code seems to work with the alert box's, you do seem to have your closing body and html tags the wrong way round though.

// Wait for page to load
$(function(){

    // Log clicked item
    $('*').click(function(){
        console.log($(this).prop("tagName")+'#'+$(this).attr('id'));
    });

    // I want this to happen
    $('#child1').click(function(){
        alert("It worked!");
    });

    // I've tried this too
    $('#child1').on("click", function(){
        alert("It worked!");
    });

    // And even this
    $('#parent').on("click", '#child1', function (){
        alert("It worked!");
    });

});

// This doesn't work either
function clickedInline(){
    alert("It worked!");
}
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
</head>
<body>
    <div id="parent">
         <input id="child1" onclick="clickedInline();" style="z-index:999">Child One</input>
         <input id="child2">Child Two</input>
    </div>
</body>
</html>

Upvotes: 1

ki9
ki9

Reputation: 5575

I figured it out... none of the click events work if the <input> tag has the disabled attribute.

Upvotes: 0

Related Questions