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 add a new checkbox with the provided name used for both the value and the label.
How can I do this?
<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>
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 />'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With