How to submit the dynamical input field into the database? - javascript

I am displaying the input field dynamically which is working for me.
The issue is,
I have to submit the form. I have tried some code as below but it's not working.
I am using Codeigniter.
Controler code
public function register(){
$save = array(
'pp_fileStatus' => $this->input->post('pp_fileStatus');
'reasonDate' => $this->input->post('reasonDate');
'reasonAmt' => $this->input->post('reasonAmt');
);
$afterxss=$this->security->xss_clean($save);
if ($afterxss)
{
$this->db->insert('tbl_register',$afterxss);
$response['error'] = "true";
$response['msg'] = "Successfully";
}else{
$response['error'] = "false";
$response['msg'] = "Sometning wrong! please check the internet connection and try again";
}
echo json_encode($response);
}
I am adding the field dynamically and incrementing the name. Please let me know what name I have to use here
$save = array(
'pp_fileStatus' => $this->input->post('pp_fileStatus');
'reasonDate' => $this->input->post('reasonDate');
'reasonAmt' => $this->input->post('reasonAmt');
);
Below is the code for adding the input field dynamically.
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
var count = 2;
var numberIncr = 1; // used to increment the name for the inputs
var addrm = '';
//Once add button is clicked
$(document).on('click', '#clicktoadd', function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
numberIncr++;
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>');
}
count++;
});
$(document).on('change', '.pp_fileStatus', function(event) {
if (($(this).val() == '1') || ($(this).val() == '3')) {
$(".medication_info").append('<div class="addbankField input-wrapper padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="reasonAmt' + numberIncr + '" class="form-control commnumber dynamicVal" placeholder="amt"></div></div><input type="hidden" name="remark' + numberIncr + '" class="form-control" placeholder="Remark">');
} else {
$(".medication_info").append('<div class="addbankField input-wrapper lbpflex padding0"><div class="form-group"> <input type="text" name="reasonDate' + numberIncr + '" class="form-control datetimepicker dynamicVal" placeholder="Date"></div></div><div class="addbankField input-wrapper"><div class="form-group"> <input type="text" name="remark' + numberIncr + '" class="form-control dynamicVal" placeholder="Remark"></div></div><input type="hidden" name="reasonAmt' + numberIncr + '" class="form-control" placeholder="amt">');
}
});
});
$('#register').on('submit', function(event) {
event.preventDefault();
// adding rules for inputs with class 'comment'
$('.dynamicVal').each(function() {
$(this).rules("add", {
required: true
})
});
// test if form is valid
if ($('#register').validate().form()) {
$.ajax({
//url:"process.php",
url: baseUrl + "/Customer_control/register",
type: "POST",
dataType: "json",
data: $('#register').serialize(),
success: function(data) {
alert("success");
},
}); // AJAX Get Jquery statment
}
//alert('hellow');
});
$('#register').validate({
errorPlacement: function(error, element) {
if (element.is("select")) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
<div id="clicktoadd">Add More</div>
<form action="#" method="post" id="register" name="register">
<div class="row">
<div class="medication_info">
</div>
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
Can anyone here to help me out with this issue?

You can use arrays for multiple names in HTML form and then get the values using Foreach Loop in PHP (CodeIgniter).
Here is how you should change your code: Change your this line:
$(".medication_info").append('<select name="pp_fileStatus' + numberIncr + '" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')
To:
$(".medication_info").append('<select name="pp_fileStatus[]" class="form-control multipleselect pp_fileStatus dynamicVal"><option value="" disabled selected>Status</option><option value="1">Open</option><option value="2">Close</option><option value="3">Pending</option></select>')
Note: I just changed select field name to "pp_fileStatus[]" and remove numberIncr variable
Now you can access this field name values in your controller like this.
$pp_fileStatus = $this->input->post('pp_fileStatus');
Here $pp_fileStatus is an array and contains all the values of pp_fileStatus.
You can do same for your other form fields too.
So you get rid of giving names to fields by incrementing one to a variable.
Hope this solves your problem.
You can update your register function like this:
public function register(){
$insert_array = [];
$pp_fileStatus = $this->input->post('pp_fileStatus');
$reasonDate = $this->input->post('reasonDate');
$reasonAmt = $this->input->post('reasonAmt');
$remark = $this->input->post('remark');
foreach ($pp_fileStatus as $key => $value) {
$insert_array[] = array(
'pp_fileStatus' => $value,
'reasonDate' => $reasonDate[$key],
'reasonAmt' => $reasonAmt[$key],
'remark' => $remark[$key]
);
}
$this->db->insert_batch('tbl_register',$insert_array);
}
Update this function according to your needs

you need to create a function for your submit actions, which you call (make available) on document load and also with your change event, after having appended the DOM.
simplified example:
$(document).ready(function() {
my_submit(); // enables your submit calls
$(document).on('change', '.pp_fileStatus', function(event) {
// your append code
my_submit(); // again, enables your submit calls
})
}
function my_submit(){
$('#register').on('submit', function(event) {
// your code
})
$('#register').validate({
// your code
})
}

Related

Find sum of automatically generated input fields value

I have a button that when you click it appends an input fields in a div,
this values comes from ajax request.
var i = 0;
$(document).on('click', '#add-btn', function() {
++i;
var user = $('#productName').attr('value');
var price = $('#price').attr('value');
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "getPrice.php",
data: {user:user, price:price},
dataType: "html", //expect html to be returned
success: function(response){
$("#dynamicAddRemove").append('<tr style="height:5em;" id="tr"><td><input name="productName['+i+']" readonly class="form-control" type="text" value="'+user+'"/></td><td><div class="quantit buttons_added"><input class="form-control quantity" id="number" type="number" name="qty[' + i + ']" value="1"/></div></td><td><input class="form-control amount" type="text" readonly value="'+price+'" name="price[' +i +']"/></td><td class="td"><input type="text" value="'+price+'" name="subTotal['+i+']" placeholder="Subtotal" class="form-control subtotal" id="grandTotal" readonly/><td><button type="button" name="add" class="btn btn-danger remove-tr">-</button></td>');
}
});
});
after appending the input fields now i want to add every value of the subTotal to get grandTotal.
var iSum = 0;
$(document).on('mouseout', '.amount , .quantity, #addvalue', function() {
iSum = 0;
$('input[name="subTotal[]"]').each(function(){
var LiSum =parseInt($('input[name="subTotal[]"]').val());
if(LiSum != undefined || LiSum != ''){
iSum+=LiSum;
}
});
$('#sum').html(iSum);
alert(iSum);
});
after successfully appending values, i keep on getting 0 as grandTotal
Replace $('input[name="subTotal[]"]') by $('input[name^="subTotal"]'). This will find all input fields with names starting with "subTotal". The name "subTotal[]" you were originally looking for does not appear anywhere in your markup.

Delete required on input before submitted in ajax

I tried to validate by submitting a form by using ajax on codeigniter, when I want to insert data but only a few input fields only and input field that I do not use I try to hide, but attr required still running on the input field that I have hidden, how to solve this. so delete the required input field when hidden.
Views
<form id="fr" method="post" class="form-horizontal form-label-left">
<div class="form-group">
<label for="fullname">Section * :</label>
<select name="section" class="form-control" required="required">
<option value="">Select section</option>
<option value="manager">Manager</option>
<option value="head manager">Head Manager</option>
</select>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Kitchen * :</label>
<input type="text" name="name_kitchen" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="nama">Resto * :</label>
<input type="text" name="name_resto" class="form-control" required="required" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="fullname"> </label><br>
<button type="button" id="submit" class="btn btn-primary"><i class="fa fa-save"></i> Simpan</button>
</div>
</form>
<script>
$("[name='section']").change(function(){
var value=$(this).val();
if(value == "manager"){
$("[name='name_kitchen']").hide();
$("[name='name_resto']").show();
}else{
$("[name='name_kitchen']").show();
$("[name='name_resto']").hide();
}
});
$("#submit").click(function() {
$.ajax({
type: "POST",
url: base_url+"add",
dataType: 'json',
data: $('#fr').serialize(),
success: function(data) {
if(data.status) {
$(".add-from-staff").toggle("slow");
$("#fr").load(location.href + " #fr");
$('form#fr input[type="text"],texatrea, select').val('');
}else {
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
},
error: function (request, jqXHR, textStatus, errorThrown) {
alert('Error');
console.log(request.responseText);
}
});
});
</script>
Controllers
public function add() {
$this->_validate();
$insert = $this->My_models->_add();
echo json_encode(array("status" => TRUE));
}
function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('name_kitchen') == '')
{
$data['inputerror'][] = 'name_kitchen';
$data['error_string'][] = 'Kitchen is required';
$data['status'] = FALSE;
}
if($this->input->post('name_resto') == '')
{
$data['inputerror'][] = 'name_resto';
$data['error_string'][] = 'Resto is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
so how when I choose one of the select options that hide disabled required?
when u are hiding any div u can get the element and remove its required attribute using jquery
$("[name='name_kitchen']").removeAttr('required');
e.g:
$("#elementID").removeAttr('required');
In this example I would not use the required attribute. It is causing more headaches than it is worth. Instead, rely on the server-side validation.
To determine which "section" is in use it seems to me that passing another piece of info to the controller would be the easiest way to solve the problem. This could be done many different ways. Adding another hidden field is one option.
Somewhere inside the <form> add
<input type="hidden" id="use-section" name="use_section" value="">
It is not clear that you have a "default" section shown when you first show the page. If there is one then use that for the "value" in the above field.
During the handler
$("[name='section']").change(function(){ ...
set the value of the "use_section" field.
var value=$(this).val();
$("#use-section").val(value);
You can evaluate the "use_section" in your controller, or in your case, in the model which is where I assume you are capturing the data posted.
if($this->input->post('use_section') === "manager")
{
//get the fields you want
}
else
{
//get the other fields
}
I have a suggestion regarding _validate(). Instead of calling exit() to short-circuit add() return a value - TRUE if it works, or $data if it doesn't. The last few lines of _validate() become
if($data['status'] === FALSE)
{
return $data;
}
return TRUE;
Then use this add() method
public function add()
{
if(TRUE === ($status = $this->_validate()))
{
$insert = $this->My_models->_add();
$status = array("status" => TRUE);
}
echo json_encode($status);
}
Use of exit or die in CodeIgniter is, IMO, not appropriate because it short-circuits the framework's designed execution flow.

How to save user input to local storage

I am creating a score keeping app and need to save the name of the players and the game name in local storage, have no idea how to apply it to the code I have
$(document).ready(function() {
$("#add-playername").click(function(e) {
e.preventDefault();
var numberOfPlayernames = $("#form1").find("input[name^='data[playername]']").length;
var label = '<label for="data[playername][' + numberOfPlayernames + ']">Playername ' + (numberOfPlayernames + 1) + '</label> ';
var input = '<input type="text" name="data[playername][' + numberOfPlayernames + ']" id="data[playername][' + numberOfPlayernames + ']" />';
var removeButton = '<button class="remove-playername">Remove</button>';
var html = "<div class='playername'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-playername").before(html);
});
});
$(document).on("click", ".remove-playername", function(e) {
e.preventDefault();
$(this).parents(".playername").remove(); //remove playername is connected to this
$("#form1").find("label[for^='data[playername]']").each(function() {
$(this).html("Playername " + ($(this).parents('.playername').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form2" method="post">
<div class="gamename">
<label><b>Enter Game Name</b></label>
<input type="text" name="game name" placeholder="Game Name" id="user_input">
</div>
</form>
<form id="form1" method="post">
<div class="playername">
<label for="data[playername][0]">Add Player Name</label>
<input type="text" name="data[playername][0]" placeholder="Enter player's name" id="data[playername][0]" />
</div>
<button id="add-playername">Add Player</button>
<br>
<br>
<input type="submit" value="Submit" />
</form>
Grab game and players using the jquery selector on form submit by preventing the form using jquery
Prepare object for the game and players
Convert the object to a string using the JSON.stringify( your_data_object) function
Save to localStorage using localStorage.setItem( 'key' , 'value' ) function
<script>
$('#form1').submit(function(){
var game_name = $("#form2 #user_input").val();
var players = [];
var players_inputs = $("#form1").find("input[name^='data[playername]']");
$.each(players_inputs, function(){
var player = $(this).val();
players.push(player);
});
var data = {
game_name : game_name,
players: players
}
console.log(data);
// save to localstorage
localStorage.setItem('game_players', JSON.stringify(data) );
event.preventDefault();
});
</script>
late to answer but something like this
<input type="submit" value="Submit" id="btn_submit" />
<script type="text/javascript">
$(document).ready(function(){
$("#btn_submit").click(function(e){
e.preventDefault();
var jsonObj = [];
players = {}
count = 0;
$('input[type=text]').each(function(){
if($.trim($(this).val()) && ($(this).attr('name').indexOf("playername") >= 0)){
players[count++] = $(this).val()
}
});
players['game_name'] = $("#user_input").val();
jsonObj.push(players);
console.log(jsonObj);
var jsonString= JSON.stringify(jsonObj);
localStorage.setItem("jsonString", jsonString);
/* remove localstorage */
// localStorage.removeItem("jsonString");
/* get localstorage */
// console.log(localStorage.getItem("jsonString"));
});
</script>

AJAX jquery not responding and showing divs

I have code a simple form in which I retrieve data dynamically and then sending it to another page. Using that data i want some divs to be displayed on my page. It is returning divs when I check it simply without using AJAX. But now I have applied some AJAX and it is not working. Any suggestions please.
AJAX
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
$.post("keyword_search.php?query="+encodeURIComponent($("#keyword").val())+"category="+encodeURIComponent($("#category").val())+"store="+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
form
<form class="form-horizontal select-search" id="search_keyword" method="post">
<label class="control-label ">Keyword</label>
<input class="form-control" id="keyword" name="keyword" type="text">
<!-- Select Category -->
<label class="control-label " for="category">Select category</label>
<select class="category" id="category" name="category">
<?php
$sm=mysqli_query($con,"select * from categories ");
while ($row1 = mysqli_fetch_array($sm,MYSQLI_ASSOC)){
$cat_id = $row1['cat_id'];
$name = $row1['cat_name'];
echo '<option value="' . $cat_id . '">' . $name . '</option>';
}
?>
</select>
<label class="control-label " for="store">Select a store</label>
<select class="storesname" id="store" name="store">
<option selected="selected">Select Stores</option>
</select>
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
</form>
<div id="search_result"> </div>
You need to change from button to submit type so that it can actually submit.
So change:-
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
To:-
<input type="submit" id="search_btn" name="search_btn" class="btn btn-danger" value="Search coupons"/>
Note:- Make sure that jQuery library added before your script code so that it will work.
Change your code like below:-
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
var data = {'query':encodeURIComponent($("#keyword").val()),'category':encodeURIComponent($("#category").val()),'store':encodeURIComponent($("#store").val())};
$.post("keyword_search.php",data, function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
And in your keyword_search.php check like this:-
<?php
echo "<pre/>";print_r($_POST); //check that how post data are coming
// rest do code accordingly
?>
Also remove method="post" from your current <form>
You just to change some thing in jQuery.
I have just changed "submit" to "click" and "#search_keyword" to "#search_btn"
$("document").ready(function() {
$("#search_btn").on("click", function (e) {
e.preventDefault();
$.post("keyword_search.php?query=" + encodeURIComponent($("#keyword").val())+encodeURIComponent($("#category").val())+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
It might help you

jquery post undefined in firebug

On 2 of my elements in a form, I am receiving 'undefined' in firebug. I have tried to trace the error, but keep hitting a brick wall, hence the post. One of the areas with the error is in the divId block and the other is the #company in the form. I would be grateful if someone could check my code and point out my error. Thanks
// Function to add box
function addbox() {
$("#boxform").dialog({
autoOpen: false,
resizable: true,
modal: true,
title: 'Submit a box intake request',
width: 470,
beforeclose: function (event, ui) {
$("#addbox").html("");
$("#divId").html("");
}
});
$('#boxsubmit').click(function () {
var company = $('.company').val();
var box = $('.box').val();
var service = $('#service').val();
var authorised = $('.authorised').val();
var address = $('.address').val();
var data = 'company=' + company + '&box=' + box + '&authorised=' + authorised + '&service=' + service + '&address=' + address;
$.ajax({
type: "POST",
url: "boxesadd.php",
data: data,
success: function (data) {
$("#boxform").get(0).reset();
$('#addbox').html(data);
//$("#form").dialog('close');
$("#flex1").flexReload();
}
});
return false;
});
$("#boxform").dialog('open');
}
html
<script language="javascript" type="text/javascript">
$(function() {
$("#company").live('change', function() { if ($(this).val()!="")
$.get("../../getOptions.php?customer=" + $(this).val(), function(data) {
$("#divId").html(data); }); });
});
</script
<form id="boxform" method="post" class="webform" name="boxform" />
<label for="company">Select a Company:</label>
<select name="company" id="company" />
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
<!--- displays the address from the change function -->
<div id="divId"></div>
Try changing
<form id="boxform" method="post" class="webform" name="boxform" />
to
<form id="boxform" method="post" class="webform" name="boxform">
and
<select name="company" id="company" />
to
<select name="company" id="company">
and
var company = $('.company').val();
to
var company = $('#company').val();
<select name="company" id="company" /> should be <select name="company" id="company">
Then form tag is also not closed correctly.
In your #boxsubmit click handler, you use dot instead of hash for #company.
Change
var company = $('.company').val();
to
var company = $('#company').val();
and remove the self close / on non-empty elements.

Categories

Resources