Dynamically create checkbox with JQuery from text input

后端 未结 3 593
执念已碎
执念已碎 2020-12-02 15:34

In my cms I have a checkbox group for categories. I would like to have a text input below that where the user can input the name of a new category and it will dynamically ad

相关标签:
3条回答
  • 2020-12-02 16:05
    <div id="cblist">
        <input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
    </div>
    
    <input type="text" id="txtName" />
    <input type="button" value="ok" id="btnSave" />
    
    <script type="text/javascript">
    $(document).ready(function() {
        $('#btnSave').click(function() {
            addCheckbox($('#txtName').val());
        });
    });
    
    function addCheckbox(name) {
       var container = $('#cblist');
       var inputs = container.find('input');
       var id = inputs.length+1;
    
       $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
       $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
    }
    </script>
    
    0 讨论(0)
  • 2020-12-02 16:16

    Put a global variable to generate the ids.

    <script>
        $(function(){
            // Variable to get ids for the checkboxes
            var idCounter=1;
            $("#btn1").click(function(){
                var val = $("#txtAdd").val();
                $("#divContainer").append ( "<label for='chk_" + idCounter + "'>" + val + "</label><input id='chk_" + idCounter + "' type='checkbox' value='" + val + "' />" );
                idCounter ++;
            });
        });
    </script>
    <div id='divContainer'></div>
    <input type="text" id="txtAdd" /> 
    <button id="btn1">Click</button>
    
    0 讨论(0)
  • 2020-12-02 16:30

    One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

    Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

    <div id="checkboxes">
        <input type="checkbox" /> Some label<br />
        <input type="checkbox" /> Some other label<br />
    </div>
    
    <input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>
    

    Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

    $('#addCheckbox').click(function() {
        var text = $('#newCheckText').val();
        $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
    });
    
    0 讨论(0)
提交回复
热议问题