JSFiddle - React, Tailwind, and code Playground

by klaascuvelier

HTML

<form action="/" method="post" id="test1">
    <input type="hidden" name="test" id="node-type" value="test" />
    <button type="submit">Submit</button>
    
    <a href="javascript:void(0)" class="test">Click me</a>    
</form>

<form action="/" method="post" id="test2">
    <input type="hidden" name="test" id="nodeType" value="test" />
    <button type="submit">Submit</button>

    <a href="javascript:void(0)" class="test">Click me</a>
</form>

CSS

form {
    display: block;
    border: 1px dotted #222;
    text-align: center;
    margin: 20px 20px;
    padding: 20px 20px
}

a {
    
}

JavaScript

/**
 * jQuery seems to have problems selecting elements in a form when 
 * there is an (input) element with ID="nodeType" in that form
 * 
 * Test 1: 
 * create a form with an input element with an id not equal to "nodeType"
 * in the form submit, count the buttons in the form in 2 ways
 * first via jQuery, then via native selecting method
 *
 * Test 2:
 * create a form with an input element with an id "nodeType"
 * in the form submit, count the buttons in the form in 2 ways
 * first via jQuery, then via native selecting method
 *
 * Expected result, in both cases the count for native and jQuery 
 * should be 1.
 *
 * Result from test 1 is twice 1 -> ok
 * Result from test 2 is 1 for native, 0 for jquery -> not ok
 */


$('form').live('submit', function (evt) {
    evt.preventDefault();     

    var form = $(this),
        buttonsJQuery = form.find('button'),
        buttonsNative = document.getElementById(form.attr('id'))
            .getElementsByTagName('button');
    
    
    alert('jQuery found '  + buttonsJQuery.length + ' buttons' + "\n"
         + 'Native found ' + buttonsNative.length + ' buttons');
    
});



/**
 * Just some more testing, check if I can select the button(s)
 */
$(document).ready(function () {
    console.log($('button').length === 2); // true
    console.log($('#node-type').length === 1); // true
    console.log($('#nodeType').length === 1); // true
    
    $('.test') // and this fails again:
        .show()
        .click(function (evt) {
            evt.preventDefault();
            
            var form = $(this).parent(),
                buttonsJQuery = form.find('button'),
                buttonsNative = document.getElementById(form.attr('id'))
                    .getElementsByTagName('button');
    
    
            alert('jQuery found '  + buttonsJQuery.length + ' buttons' + "\n"
                 + 'Native found ' + buttonsNative.length + ' buttons');
        });
        
});