Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create checkbox with JQuery from text input

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?

like image 621
Martin Reeves Avatar asked Jan 13 '10 08:01

Martin Reeves


2 Answers

<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> 
like image 190
David Hedlund Avatar answered Sep 16 '22 14:09

David Hedlund


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 />'); }); 
like image 33
T. Stone Avatar answered Sep 16 '22 14:09

T. Stone