jQuery incrementing a cloned elements instead of cloned div - javascript

I had this HTML script which contains a drop list and a text box, and I just need to clone those two instead of the whole div, and then send the data to AJAX, and each drop list with text box will form an array that should be add as a single row in a table, that's what I have now:
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>
And here is the jQuery Script:
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
})
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).closest(".rounded").clone()
.insertAfter(".rounded:last")
.attr("id", "rounded" + (cloneIndex+1))
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = id.split('-')[0] +'-'+(cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parent().parent(".rounded").remove();
}
The problem is that the whole div is being cloned and just the div id is being changed:
Here is the id of each div is being incremented:
I need to clone the 2 elements only not the whole div and buttons
At the end I need t add them to database using Ajax and PHP

Here you can go with the code.
In this code i made changes in clone()
Here the changes
You first find existing child element.
Than clone that element and append it after last element
var cloneIndex = $(".clonedInput").length; this should be in clone() So it will pass proper incremented value of child element as id in your cloned html
the below code just only make clone of clonedInput not a whole div
Edit
I also edit remove function also.
It will only removes last element which was cloned.
Hope this will helps you. :)
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex+1));
}
function remove() {
$(".rounded").find(".clonedInput:last").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity" id="medication_quantity">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
<!-- End class="col-sm-4" -->
</div>

You can add style to your actions class to prevent it from showing on all cloned elements
css
.actions {
display: none;
}
.clonedInput:first-child .actions {
display: block;
}
Also for the removing function you could use .closest() instead of .parent().parent()
$(this).closest(".rounded").remove();

There are a lot of things that could be optimized and replaced but I've edited your code. I believe that this is the easiest way to learn.
The edits are marked as "STACKOVERFLOW EDIT" in the comments.
$(document).ready(function() {
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
$("button.submit").on("click", submit_form); // STACKOVERFLOW EDIT: execute the submit function
});
var regex = /^(.+?)(\d+)$/i;
function clone() {
var cloneIndex = $(".clonedInput").length;
$(".rounded").find("#clonedInput1").clone().insertAfter(".clonedInput:last").attr("id", "clonedInput" + (cloneIndex + 1));
}
function remove() {
if($(".clonedInput").length > 1) { // STACKOVERFLOW EDIT: Make sure that you will not remove the first div (the one thet you clone)
$(".rounded").find(".clonedInput:last").remove();
} // STACKOVERFLOW EDIT
}
// STACKOVERFLOW EDIT: define the submit function to be able to sent the data
function submit_form() {
var ajax_data = $('#submit_form').serialize(); // The data of your form
$.ajax({
type: "POST",
url: 'path_to_your_script.php', // This URL should be accessable by web browser. It will proccess the form data and save it to the database.
data: ajax_data,
success: function(ajax_result){ // The result of your ajax request
alert(ajax_result); // Process the result the way you whant to
},
});
}
The HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<form action="" method="post" id="submit_form"> <!-- STACKOVERFLOW EDIT: generate a form to allow you to get the data in easy way -->
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6 ">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data[]" id="diagnosis_data"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="medication_quantity">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="medication_quantity[]" id="medication_quantity"> <!-- STACKOVERFLOW EDIT: Add [] so that you may receive the values as arrays -->
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
</form> <!-- STACKOVERFLOW EDIT -->
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
<button class="btn btn-danger submit">Submit</button>
</div>
<!-- End class="col-sm-4" -->
</div>

Related

how to push multivalues from many element with same class or id in ajax

I have created a form , that user can append the additional column that need to that form, for example I have column name in the form , if people want to add more column name , they just press the add button , and then select element for the column name and it will be added, so it will have 2 select element with same class, but the problem is , I dont know how to send the data with ajax so django views that can get the data.Every time that I try to print the result , it will print as [] which means: failed to push the data
here's the code
html
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<form class="form-horizontal style-form" action="#">
<div class="form-group">
<label class="control-label col-md-3">Database Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
<!-- <li></li> -->
{% for table in obj2 %}
<option value = "{{table}}" >{{ table }}</option>
{% endfor %}
<!-- <li>Dropdown link</li> -->
</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick="return appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id ="test">
<div class="btn-group">
<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button>
<label class="control-label col-md-3">Filter</label>
<div class="col-md-4" id="filtbox">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select class="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</select>
<select class="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
<option> > </option>
<option> < </option>
<option> ≥ </option>
<option> ≤ </option>
<option> = </option>
</select>
<input class="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</input>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-4" id="showquery">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<button id="result" class="btn btn-theme" type="submit" style="height:30px;width:100px;" onclick="return showQuery()">Show</button>
<button id="export" class="btn btn-theme" type="Export" style="height:30px;width:100px;" onclick="return ExportFile()">Export</button>
</div>
</div>
</div>
</div>
<div id="query_result">
</div>
</form>
script to append the box
<script>
function appendBox()
{
$('#test').append('<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"></select>')
return false
}
</script>
<script>
function appendFilterBox()
{
$('#filtbox').append('<select class="columnselect" style="width:125px;background-color:white;height:30px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:2px"></select><select class="operator" style="width:125px;background-color:white;height:3 0px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:3px"><option> > </option><option> < </option><option> ≥ </option><option> ≤ </option><option> = </option></select><input type="text" class="parameter" style="width:150px;background-color:white;height:30px;font-size:15px;"></input>')
return false
}
</script>
Ajax to send the data
<script>
$(document).ready(function() {
$("#result").click(function () {
var urls = "{% url 'polls:load-query' %}";
var table = $('#dataselect').val();
data = {
'name' : [],
'table': table,
'condition': []
};
$('#column-name .columnselect').each((idx, el) => data.name.push($(el).val()));
$('#filtbox .input-group').each((idx, el) => {
condition = {
'column' : $(el).find('.conditionselect').val(),
'operator' : $(el).find('.operator').val(),
'value' : $(el).find('.parameter').val()
};
data.condition.push(condition);
});
$.ajax({
url: urls,
data: data,
success: function(data) {
$("#query_result").html(data);
},
error: function(data)
{
alert("error occured");
}
});
});
});
</script>
is this the correct way to send multivalues with ajax? it seems the data didnt send properly when django want to get the data..
heres the view if you guys curious
def list_all_data(request):
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('', '', sid='') #ip port and user and password i hide it for privacy
conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
c = conn.cursor()
print(request.GET.getlist('condition'))
data_name = request.GET.get('name',1)
table_name = request.GET.get('table',1)
column = request.GET.get('condition', {}).get('column', 1)
print(column)
operator = request.GET.get('condition', {}).get('operator', 1)
print(operator)
value = request.GET.get('condition', {}).get('value', 1)
print(value)
c.execute("select "+data_name+" from "+table_name+" where "+column + operator+"'"+value+"'")
c.rowfactory = makeDictFactory(c)
columnalldata = []
columnallname = []
for rowDict in c:
columnalldata.append(rowDict[data_name])
columnallname.append(data_name)
context = {
'obj4' : columnalldata,
'column_name' : columnallname
}
return render(request,'query_result.html',context)

How to make jquery.dynamiclist run with newer version of jquery?

I would like to use jquery.dynamiclist library in my procject.
In the demo page that's running smoothly there is a jquery library in version 1.8.2.
In my project I use version 1.11.1 and this makes dynamiclist plugin doesn't work.
With newer version when I process form I get data with names of inputs but without values (I get 'undefined').
Here is the code from demo.
What I have to change to make it run with newer version of jquery?
<form class="form-horizontal">
<h2>Example 1: Basic List</h2>
<div class="control-group">
<label class="control-label">Party</label>
<div class="controls">
<input name="partyName" type="text" placeholder="Party Name">
</div>
</div>
<div class="control-group">
<label class="control-label">Guest List</label>
<div id="example1" class="controls">
<div class="list-item">
<input name="guestList[0].name" type="text" placeholder="Guest Name">
<i class="icon-minus"></i> Remove Guest
</div>
<i class="icon-plus"></i> Add Guest
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-primary btn-large" value="Process Example 1"/>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://github.com/ikelin/jquery.dynamiclist/blob/master/jquery.dynamiclist.min.js"></script>
<script>
(function($) {
$(document).ready(function() {
$("#example1").dynamiclist();
// display form submit data
$("form").submit(function(event) {
event.preventDefault();
var data = "";
$(this).find("input, select").each(function() {
var element = $(this);
if (element.attr("type") != "submit") {
data += element.attr("name");
data += "="
data += element.attr("value");
data += "; "
}
});
alert(data);
location.reload(true);
});
});
})(jQuery);
</script>
Simply change element.attr("value"); to element.val();.
Sorry I had to include the plugin code manually because apparently you cannot include the src directly from github. Also commented the reload for the snippet.
<form class="form-horizontal">
<h2>Example 1: Basic List</h2>
<div class="control-group">
<label class="control-label">Party</label>
<div class="controls">
<input name="partyName" type="text" placeholder="Party Name">
</div>
</div>
<div class="control-group">
<label class="control-label">Guest List</label>
<div id="example1" class="controls">
<div class="list-item">
<input name="guestList[0].name" type="text" placeholder="Guest Name">
<i class="icon-minus"></i> Remove Guest
</div>
<i class="icon-plus"></i> Add Guest
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-primary btn-large" value="Process Example 1"/>
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
/* jQuery Dynamic List v 2.0.1 / Copyright 2012 Ike Lin / http://www.apache.org/licenses/LICENSE-2.0.txt */
(function(a){a.fn.dynamiclist=function(d){if(this.length>1){this.each(function(){a(this).dynamiclist(d)});return this}var g=a.extend({itemClass:"list-item",addClass:"list-add",removeClass:"list-remove",minSize:1,maxSize:10,withEvents:false,addCallbackFn:null,removeCallbackFn:null},d);var f=function(o,n,j){var m=o.find("."+j.itemClass).length;if(m<j.maxSize){var l=o.find("."+j.itemClass+":first").clone(j.withEvents);l.find("."+j.removeClass).show().click(function(p){e(o,a(this),p,j)});b(l,m);i(l);var k=o.find("."+j.itemClass+":last");k.after(l);if(j.addCallbackFn!=null){j.addCallbackFn(l)}}if(n!=null){n.preventDefault()}};var e=function(o,k,n,j){var m=o.find("."+j.itemClass).length;var l=k.parents("."+j.itemClass+":first");if(m==j.minSize){i(l)}else{l.remove()}c(o,j);if(j.removeCallbackFn!=null){j.removeCallbackFn(l)}n.preventDefault()};var b=function(j,k){j.find("label, input, select, textarea").each(function(){var m=["class","name","id","for"];for(var n=0;n<m.length;n++){var l=a(this).attr(m[n]);if(l){l=l.replace(/\d+\./,k+".");l=l.replace(/\[\d+\]\./,"["+k+"].")}a(this).attr(m[n],l)}})};var c=function(k,j){k.find("."+j.itemClass).each(function(){var l=k.find("."+j.itemClass).index(this);b(a(this),l)})};var i=function(j){j.find("input[type=text], textarea").val("");j.find("input[type=radio]").attr({checked:false});j.find("input[type=checkbox]").attr({checked:false})};var h=function(k){k.find("."+g.itemClass+":first ."+g.removeClass).hide();var j=k.find("."+g.itemClass).length;while(g.minSize>j){f(k,null,g);j++}k.find("."+g.addClass).click(function(l){f(k,l,g)});k.find("."+g.removeClass).click(function(l){e(k,a(this),l,g)});return k};return h(this)}})(jQuery);
</script>
<script>
(function($) {
$(document).ready(function() {
$("#example1").dynamiclist();
// display form submit data
$("form").submit(function(event) {
event.preventDefault();
var data = "";
$(this).find("input, select").each(function() {
var element = $(this);
if (element.attr("type") != "submit") {
data += element.attr("name");
data += "="
data += element.val();
data += "; "
}
});
alert(data);
//location.reload(true);
});
});
})(jQuery);
</script>

Cloning a div and changing the id's of all the elements of the cloned divs

I am working with a django project, and part of the requirement is to have a button on the html page which when clicked clones a particular div and appends it to the bottom of the page as shown in the screenshot:
Screenshot of the Page
I was successful in doing this applying the following code:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find('input:text').val('') //Clear the Input fields of the cloned DIV
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:0px;clear:both"></div>
<div style="float:right">
<span class="label label-primary" id="add_cp_button" style="cursor: pointer;" onclick="addVL()">+ Add VL </span>
</div>
<div style="height:0px;clear:both"></div>
<div>
<div id="ext_int_div_1">
<div class="section">
<fieldset class="scheduler-border">
<legend class="scheduler-border">External Interface 1</legend>
<div class="sectionContent" style="border:0px solid grey;width:75%">
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Name</label>
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="vl_name_1" id="vl_name_1" placeholder="Name"/>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connectivity Type</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_connectivity_type_1" id="vl_connectivity_type_1">
<option value="VIRTIO">VIRTIO</option>
<option value="">None</option>
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connection point Ref</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_con_ref_1" id="vl_con_ref_1" />
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
</div>
</fieldset>
<div style="height:2px;clear:both;"></div>
</div>
</div>
</div>
<input type="hidden" name="vl_count" id="vl_count" value="1" />
Now i have a new issue, i need to make sure that the ID's of the elements withing the DIV are unique too, for example the the ID = "vl_name_1" for the first input box must be changed to "vl_name_2" when creating the creating the clone.
I tried the following example and added the snipped within my addVL() function just to see if any changes happen to my div's:
$("#ext_int_div_1").clone(false).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + clone.id); });
However, the above code got me nothing ( i am pretty sure the above piece of code is rubbish since i have no clue what it is doing).
Help appreciated here.
Thank you
I hope the snippet below helps.
$(document).ready(function () {
$sharerCount = 1;
$('#addSharer').click(function() {
if($sharerCount < 5) {
$('#sharer_0').clone().attr('id', 'sharer_' + $sharerCount).insertAfter('.sharers:last').find("*[id]").attr('id', 'input_' + $sharerCount).val("").clone().end();
$sharerCount += 1;
}
else {
$('#addSharer').prop('disabled', 'true');
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form">
<div class="form-group">
<label class="control-label col-sm-3 col-xs-12">Share With<span class="red-text">*</span></label>
<div class="col-sm-9 col-xs-12">
<div id="sharer_0" class="field-group sharers">
<input id="input_0" type="text" class="form-control field-sm">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9 col-xs-12">
<button id="addSharer" type="button" class="btn btn-success">Add Another</button>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
I did the following and solved my problem:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find("*[id]").each(function(){
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength-1], vl_cnt);
$(this).attr('id', newId);
});
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
Thank you #ProblemChild for giving me the pointer in the right direction, I cannot upvote #ProblemChild for providing partial solution.

creating textbox element dynamically and bind different model

I am working in angular js application, where i need to create textbox with buttons dynamically that means
<div class="col-sm-4 type7" style="font-size:14px;">
<div style="margin-bottom:5px;">NDC9</div>
<input type="text" name="ndc9" class="form-control txtBoxEdit" ng-model="ndc9">
</div>
<div class="col-sm-4 type7 " style="font-size:14px;">
<div style="padding-top:20px; display:block">
<span class="red" id="delete" ng-class="{'disabled' : 'true'}">Delete</span> <span>Cancel </span> <span id="addRow" style="cursor:pointer" ng-click="ndcCheck(0)">Add </span>
</div>
</div>
this will create below one
i will enter some value in above textbox and click add ,it needs to be created in next line with same set of controls that means (textbox with above 3 buttons need to be created again with the entered value).
Entering 123 in first textbox and click add will create new textbox with delete,cancel,add button with entered value.
Again am adding new value 243 then again it needs to create new textbox down to next line with the entered value (and also the same controls).
finally i want to get all the entered values. how can i achieve this in angular js
You could use ng-repeat with an associative array. Add Would basically push the model value to an array and and also an empty object in the array.
<div ng-repeat ="ndc in NDCarray">
<div class="col-sm-4 type7" style="font-size:14px;">
<div style="margin-bottom:5px;">NDC9</div>
<input type="text" name="ndc9" class="form-control txtBoxEdit" ng-model="ndc.val">
</div>
</div>
<div class="col-sm-4 type7 " style="font-size:14px;">
<div style="padding-top:20px; display:block">
<span class="red" id="delete" ng-class="{'disabled' : 'true'}" ng-click="NDCdelete($index)">Delete</span>
<span>Cancel </span>
<span id="addRow" style="cursor:pointer" ng-click="NDCadd ()">Add </span>
</div>
</div>
</div>
In the controller:
$scope.NDCarray = [{val: ''}];
$scope.NDCadd = function() {
$scope.NDCarray.unshift(
{val: ''}
);
};
$scope.NDCdelete = function(index) {
$scope.NDCarray.splice(index, 1);
};
Plunker: https://plnkr.co/edit/3lklQ6ADn9gArCDYw2Op?p=preview
Hope this helps!!
<html ng-app="exampleApp">
<head>
<title>Directives</title>
<meta charset="utf-8">
<script src="angular.min.js"></script>
<script type="text/javascript">
angular.module('exampleApp', [])
.controller('defaultCtrl', function () {
vm = this;
vm.numbers = [1, 2, 3];
vm.add = function (number) {
vm.numbers.push(number);
}
vm.remove = function (number) {
var index = vm.numbers.indexOf(number);
if(index>-1){
vm.numbers.splice(index, 1);
}
}
});
</script>
</head>
<body ng-controller="defaultCtrl as vm">
<div ng-repeat="num in vm.numbers">
<span>Number : {{num}}</span>
</div>
<div>
<input type="number" ng-model="vm.newNumber">
<button ng-click="vm.add(vm.newNumber)">Add</button>
<button ng-click="vm.remove(vm.newNumber)">Remove</button>
</div>
</body>
</html>

How to clear angularJS form after submit?

I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.

Categories

Resources