Skip to content

Instantly share code, notes, and snippets.

@tokhi
Last active June 21, 2016 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokhi/ee20ad529074d38d7b7c2fe43bf44513 to your computer and use it in GitHub Desktop.
Save tokhi/ee20ad529074d38d7b7c2fe43bf44513 to your computer and use it in GitHub Desktop.
Adding and removing bootstrap custom fields like wordpress.

Adding/removing custom fields

Add and remove bootstrap custom fields by single clicks

index.html file:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" 
<link rel="stylesheet" href="scripts/main.js" 
<form id="surveyForm" method="post" class="form-horizontal">
    
    <div class="form-group">
        <label class="col-xs-3 control-label">Options</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="option[]" />
        </div>
        <div class="col-xs-4">
            <button type="button" id="addBttn" class="btn btn-default addButton">+</button>
        </div>
    </div>

    <!-- The option field template containing an option field and a Remove button -->
    <div class="form-group hide" id="optionTemplate">
        <div class="col-xs-offset-3 col-xs-5">
            <input class="form-control" type="text" name="option[]" />
        </div>
        <div class="col-xs-4">
            <button type="button"  class="btn btn-default deleteButton" onClick="removeElem(this);">-</button>
        </div>
    </div>

   
</form>

<script type="text/javascript">
    // this will remove a custom filed on click
    function removeElem(elem) {
        console.log("element clicked ", elem);
        $(elem).parents("div")[1].remove();
    }
</script>

main.js file:

$(document).ready(function(){
  var i = 0;
	$('#addBttn').click(function(){
	   orf = $('#optionTemplate')[0];
	   cf =  orf.cloneNode(true);
	   cf.id = "custom_field" + ++i;
	   cf.className = "form-group";
	   orf.parentNode.appendChild(cf);

	  
	 });
});

JSFiddle demo here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment