JSFiddle - React, Tailwind, and code Playground

by marko

HTML

<div>
    <span style="font-weight: bold">Are .toggle-class inputs editable?</span><br />
    Yes <input type="radio" name="editable" value="Yes"/><br />
    No <input type="radio" name="editable" value="No" checked="checked" />    
    
    <p>Let's use a class name "toggle-state" for the elements that we want
        to disable using the radio buttons above. We'll set a red border around all elements that use the toggle-state class so we can easily distinguish them and show that the others are unafected. .</p>
    <input type="text" /><br />
    <input type="text" class="toggle-state" /><br />
    <input type="text" /><br />
    <input type="text" class="toggle-state" /><br />
    <input type="text" class="toggle-state" /><br />
</div>

CSS

.toggle-state {
    border: 1px solid red;
}

JavaScript

$(document).ready(function() {
    
    // store all .toggle-state objects in a variable (this improves performanc
    var $elements = $(".toggle-state");
    
    // create a function to be used onload and onclick
    function isEditable() {
    
        // get the value of the selected radio button
        var editable = $("input[name=editable]:checked").val();
        
        // test the value
        if(editable == 'No') {
            // set readonly if editable is set to 'No'
            $elements.attr("readonly", true);
        }
        else {
            // Otherwise remove readonly attribute
            $elements.removeAttr("readonly");
        }
    }

    // Run function on page load
    isEditable();
    
    // Run function on click
    $("input[name=editable]").click(isEditable);
});