I have this form with some input fields, where upon submitting the form the data gets appended to a table, more like a list. The data gets appended to the table list and also gets sent to the data base using ajax, both action takes place when I click on submit. Below is the form.
<div id ="product_calculator" style="border: 1px solid gray; padding: 10px; display:none;margin-top: 5px;"><br>
<div class="row">
<div class="col-md-2">
<label>Product Name</label>
<input class="form-control" name="productname" type="text" id="productname" value=""><br>
</div>
<div class="col-md-2">
<label>Width</label>
<input class="form-control" name="width" step ="any" type="text" id="width" value=""><br>
</div>
<div class="col-md-2">
<label>Height</label>
<input class="form-control" name="height" step ="any" type="text" id="height" value=""><br>
</div>
<div class="row">
<div class="col-md-1">
<input type="button" class="btn btn-default" name="submit" class="submit" id="submit" class="btn btn-info" value="ADD TO LIST" />
</div>
</div>
This is table where the data gets appended,
<div>
<table class="table table-hover">
<thead>
<tbody class="details">
</tbody>
<tfoot>
</tfoot>
</table>
</div>
This is the jquery and ajax where I append the data to the list and send it to the database as well, you can also I attach a remove button to each of my appended list item
$('#submit').on("click" , function(){
var productname = $('#productname').val();
var width = $('#width').val();
var height = $('#height').val();
$.ajax({
url:"item_list_process.php",
method:"POST",
data:{productname:productname,width:width,height:height},
success:function(data){
$("#list_message").html(data)
}
})
var tr = '<tr>'+
'<td><input type="text" name="product_name[]" required class="form-control product_name" value="'+productname+'"></td>'+
'<td><input type="text" name="width[]" required class="form-control width" value="'+width+'"></td>'+
'<td><input type="text" name="height[]" required class="form-control height" value="'+height+'"></td>'+
'<td><input type="button" name="remove" class="btn btn-danger remove" value="Remove"></td>'+
'</tr>';
$('.details').append(tr);
})
Now you can see I attach a remove button to each of my list item, upon clicking on the button I remove the list item from the table as well as from the data base using ajax and jquery. The code is below, I use the data from the appended list to send it to php for it to recognize which line of item to delete
$('.details').on('click','.remove',function(){
var con = confirm("Do you want to remove it ?");
if(con){
var pro = $('.product_name').val();
var wid = $('.width').val();
var hei = $('.height').val();
$.ajax({
url:"item_list_delete.php",
method:"POST",
data:{pro:pro,wid:wid,hei:hei},
success:function(data){
$("#delete").html(data)
}
})
$(this).parent().parent().remove();
}
});
Now the problem is when I delete the data, ajax seems to be only working once when deleting the data from the data base, after that it dosent work, for example lets say I have 4 items, lets say I clicked on the 3rd item, the item gets deleted from database and also gets removed from the list, but when I click on the first item after deleting the 3rd item, the ajax dosent work anymore, nor does it work on any more of my list items when I click on thier remove button.
Check what is been passed to the id='delete' via this $("#delete").html(data).
Because any data if you are manipulating via ajax thous class will not be consider for next action.
You can check weather action triggers when you click on it by adding alert('test');
for each row you can consider different id's by appending row id's to it. When you are preforming any action on remove button you can remove particular row based on the unique ids.
like
Related
With JS, I populate the form with a group of fields which I then either duplicate or remove.
As I duplicate the fields, my intention is to have the input values stored in an object.
When I click on the plus button, the fields duplicate, but the values entered disappear and the data is not captured.
JS
var html = `<div class="form-inline">
<div class="form-group">
<label class="sr-only" for="field-name">Field Name</label>
<input type="text" class="form-control" id="field-name" placeholder="Field Name" name="field_name">
</div>
<span>-</span>
<div class="form-group">
<label class="sr-only" for="field-name">Field Name</label>
<input type="text" class="form-control" id="field-name" placeholder="Field Type" name="field_type">
</div>
<span>-</span>
<div class="form-group">
<label class="sr-only" for="field-name">Field Name</label>
<input type="text" class="form-control" id="field-name" placeholder="Default value" name="field_default">
</div>
<div class="form-group">
<span class="btn btn-danger" data-role="remove">
<span class="glyphicon glyphicon-remove">-</span>
</span>
<span class="add_button btn btn-primary" data-role="add">
<span class="add_button glyphicon glyphicon-plus">+</span>
</span>
</div>
</div>`;
var crud_name = document.querySelector('.crud_name') // this is the first input box
var field_group = document.querySelector('.form-container')
// load the first group of fields to the DOM
field_group.innerHTML += html
var fields = []; // this will store all the database/crud fields
var plus_button = document.querySelector('.add_button')
/**
* The event is used when the user clicks on the plus button
* The event is on the form itself, but the target is the plus button
*/
plus_button.addEventListener('click', function(e) {
e.preventDefault()
if(e.target.classList.contains('add_button')) {
let inputs = e.target.parentElement.querySelectorAll('input')
var obj = {};
Array.from(inputs).forEach(input => {
obj[input.name]= input.value;
})
fields.push(obj);
console.log(fields);
field_group.innerHTML += html
// field_group.insertAdjacentHTML('beforeend', html)
}
})
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<form action="" method="post" id="crud_form">
<div class="form-group">
<input type="text" name="name" placeholder="Enter CRUD name. Eg: Task" class="crud_name form-control">
</div>
<div class="form-container"></div>
<button type="submit" class="btn btn-primary save_crud">Save</button>
</form>
How can I store the data each time I click to add the new group of inputs?
I tried to mimic this here
I'm not sure if i understand your question. If you don't want the inputs to disappear replace the last field_group.innerHTML += html by field_group.insertAdjacentHTML('beforeend', html).
Your button type is submit, so it submits the form when its clicked and the browser will refresh the page. Change the button type to type="button" and the form wont submit when you click the button. Then you can save the form input values to your javascript objects and add the new extra fields in to the page with javascript as well.
I'm trying to create a function which adds a new row, and values to a table each time a form is submitted:
Appointment booking HTML page:
<div class="contact-form">
<form action="https://formspree.io/MYEMAIL" id="book_appt"
method="POST">
<label>Name: </label><input id="customerName" class ="form-control"
type="text" name="Name of Customer" required></input>
</br>
<label>Email Address: </label><input id="customerEmail" class="form-
control" type="email" name="Email Address" required></input>
</br>
<label>Phone no.: </label><input id="customerPhone" class ="form-
control" type="number" name="Phone No." required></input>
</br>
<label>Date & Time of Test Drive: </label><input id="customerDate"
class ="form-control" type="datetime-local" name="Date & Time of
Test Drive" required></input>
<input type="submit" value="Submit" onclick="addData()">
</form>
</div>
Appointment table html page:
<table id="tblAppts" style="width:60%; border: 1px solid black"
border="1"
align="center">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Date/Time of Appt</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Javascript:
function addData() {
var name = document.getElementById("customerName").value;
var email = document.getElementById("customerEmail").value;
var phone = document.getElementById("customerPhone").value;
var date = document.getElementById("customerDate").value;
var tableRef =
document.getElementById('tblAppts').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var nameCell = newRow.insertCell(0);
var emailCell = newRow.insertCell(1);
var phoneCell = newRow.insertCell(2);
var dateCell = newRow.insertCell(3);
nameCell.innerHTML = name;
emailCell.innerHTML = email;
phoneCell.innerHTML = phone;
dateCell.innerHTML = date;
var newText = document.createTextNode('New row');
}
When I click the Submit button on appt booking page, I am sent a default email (I have not attached this function as it's probably not relevant) but I would like it to also carry out the addData(), which it is not. Can anyone see what the problem may be?
You specified the next URL in your form's action attribute.
<form action="https://formspree.io/MYEMAIL" id="book_appt" method="POST">
input[type="submit"]'s base operation is to pass form-data to the next page (in the action attribute)
So if you don't want to change the page, prevent its default action
like below:
<input type="submit" value="Submit" onclick="addData(); return false;">
To test if your addData function is working, change the input type of 'submit' to 'button'. If everything is right then it should work fine.
The reason you are not able to see the result of addData function call is because it is attached to an onclick handler of a submit input button. It causes the form to submit and take you to new URL.
If I understand correctly what you are trying to do, there are two ways you can go about:
You can try to submit the form as an AJAX request(Send information
without changing the page url) and not the way you are currently
doing. When the request is successful you can call your addData()
function.
Or your submission can create a new row entry in your backend
database (assuming you have one) while also triggering a page
refresh. This page, when loading, should populate the entries that
are there in the backend database.
Assuming your addData() function is working, you can try to change your submit button like so:
<input type="button" value="Submit" onclick="addData()">
I'm facing the problem to replicate input fields onclick of a button
*I have few input fields and i can fill the data in that
*After filling the input fields i have a different data set to add so i need same fields.
*If i press button (addMore) the fields should replicate and it should allow me to add one more set of data.
*There should be one button(remove) that will help me to remonessessaryve those replicated fields if its not necessary.
I have tried this in angular ..and I'm sharing my sample code and plunker plz help me out
template.ts
<div class="card">
<input type="text" id="name" value="" class="form-control">
<label for="form1">Name</label>
<input type="text" id="mobile" value="" class="form-control">
<label for="form1">Mobile</label>
</div>
<button type="button" title="Add"class="btn btn-sm"
(click)="addMore">Add</button>
test.component.ts
export class App {
addMore() {
//function to replicate the form input fields
}
plunker link :- http://plnkr.co/edit/GCCnoMkLynpELwaYX11m?p=preview
You're looking for generating dynamic inputs using ngFor
You can initially create an array with initial value as follows,
inputelements = [{name: '',mobile:''}];
on click of addmore button you can push more elements and those will be rendered using ngFor
Template code will be,
<div class="card" *ngFor="let word of inputelements; let in=index" class="col-sm-3">
<div class="form-group">
<label for="form1">Name</label>
<input type="text" [(ngModel)]="inputelements[in].name" class="form-control" required>
<label for="form1">Mobile</label>
<input type="text" [(ngModel)]="inputelements[in].mobile" class="form-control" required>
</div>
</div>
<br>
<button type="button" title="Add"class="btn btn-sm pull-right"
(click)="addMore()">Add</button>
WORKING DEMO
Keep the track of the inputs with an array and add/remove with js :
inputs = [];
add() {
this.inputs.splice(0,0,this.inputs.length+1);
}
DEMO
I am creating form in angularjs. In that, I am creating add more fields functionality by clicking on "Add more" button. I've implemented add more functionality using javascript.
Below is the code for HTML:
<form method="POST" name="form" ng-submit="insert(user)" role="form">
<div class="top_gets" id="innerdivs">
<input ng-model="user.amount" type="text"/>
<input ng-model="user.description" type="text"/>
<input type="submit" onclick="addMore();" value="Add more"/>
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
Below is Javascript Code:
<script>
var counter = 0;
function addMore() {
counter += 1;
var div = document.getElementById('innerdivs');
var innerdiv = '<div id="innerdivs"><!-- Same Form Field Elements---></div>';
$('#innerdivs').append(innerdiv);
}
</script>
My problem is, whenever I add more fields by clicking on "Add more" button and submit the form, then only first loaded input fields posts/sends the data means newly appended field input does not posts the data. Whatever the fields are appended using javascritpt that won't works that is form does not sends/posts the inputs. This works with core PHP but it does not works in angularjs. Is there any way to fix this in angularjs?
You are doing it absolutely wrong. You shall not add dom elements manually. Instead, you shall have array in controller and push new object in it:
<form name="form" ng-submit="save(users)" role="form" ng-controller="addUserCtrl">
<div class="top_gets" ng-repeat="user in users">
<input ng-model="user.amount" type="text" />
<input ng-model="user.description" type="text"/>
<input type="button" ng-click="addMore();" value="Add more" />
<input type="submit" value="Save & Continue" class="save_gets" />
</div>
</form>
In controller:
angular.module(<module_name>).controller('addUserCtrl', ['$scope', function (scope) {
scope.users = [{}];
scope.addMore = function () {
scope.users.push({});
};
scope.save = function () {
// send `scope.users` to server with $http or $resource
};
}]);
I'm dealing with a awful issue, I developed a form with multi fields set (using normal div)
and when I test the submit action I got in the URL the one input not filled, also hidden in
the markup as showed bellow.
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234&user_reg=
And here is the code for the form:
<form id="exform">
<div class="fields" id="login">
<div class="txt">
<label for="user"></label>
<input id="user" type="text" name="user"/>
</div>
<div class="txt">
<label for="pwd"</label>
<input id="pwd" type="password" name="pwd" />
</div>
<input type="submit" value="test" id="test"/>
</div>
<div class="fields" id="register">
<div class="txt">
<label for="user_reg"></label>
<input id="user_reg" name="user_reg" type="text"/>
</div>
<div class="txt">
<label for="pwd2"></label>
<input id="pwd2" type="password" />
</div>
<div class="txt">
<label for="pwdc"></label>
<input id="pwdc" type="password"/>
</div>
<div class="buttons">
<input type="submit" value="OK" id="ok"/>
</div>
</div>
</form>
The strange is that the second field set isn't available in the screen, because in the css
there is a rule to only show the first group with the class "fields"
/*Hide all except first div with class div*/
#exform .fields:not(:first-of-type) {
display: none;
}
So I really want to know why the form is submitting fields out of the scope.
For example, if the second group fieldset is used, when the button submit with value OK is clicked the result produced is similar. In the URL, only the user_reg field parameter is showed filled with the two another fields for the first group without values:
http://127.0.0.1:8000/exform.html?user=&pwd=&user_reg=test
The following code is for submit test:
$(function() {
$('#test').click(function() {
$('#exform').submit(function(event) {
console.log("form Submited:" + document.forms['exform'] + "test");
});
});
$('#ok').click(function() {
$('#exform').submit(function(event) {
console.log("form Submited:" + document.forms['exform'] + "ok");
});
});
});
Doesn't matter I'm got the same URL results
This
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234&user_reg=
or
http://127.0.0.1:8000/exform.html?user=&pwd=&user_reg=test
Instead I'm receiving:
// on #test click
http://127.0.0.1:8000/exform.html?user=test&pwd=QWERT1234
// on #ok click
http://127.0.0.1:8000/exform.html?user_reg=test&pwd2=QWERT1234&pwdc=QWERT123
I can't retrieve the values for pwd2 and pwdc fields in the URL as parameters obtained after submitting.
This got me crazy.
If you do not specify the method method of the form, the default is GET while submitting it. This is the reason to see all form elements in your URL.
Try this:
<form id="exform" method="post">
<!-- form contents -->
See here for details.
When you submit form you submit all it's input fields at ones.
Even if you hide something with css it still exists in html.
When you processed the form you can add a hidden field "input type="hidden"" and give that field a value that tells your script witch fields you want processed in witch case.
And i also fink that post method is better (more secure) especially if you send password.