Codeigniter form serialize not working - javascript

i'm triying to pass data from form to controller in codeigniter...but when I want to print a table with the results...i'm getting null on every row of the table. Here is my code:
FORM
<form class="col s12" id="update_form" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación</span>
<input type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
Jquery
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
alert(chango);
$.post(baseurl + 'admin/update_politic', {
data: chango
},
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
Controller
public function update_politic(){
if ($this->input->is_ajax_request()) {
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $this->input->post("animation");
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
$this->load->model("politic");
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
//"animation" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->update("politics",$values);
$this->db->where("POLITIC_ID",$id);
}
HELP!!! I don't understan why i'm getting null values once I want print results!!

Your where condition should come first like,
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
//"animation" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
And show us your list_politic(); code if it is not working.
I think you are passing data in incorrect way if you are using serialize() then use it directly in $.post like,
$.post(baseurl + 'admin/update_politic',chango,function(data) {
console.log(data);
list_politic();
});

Related

How to show data when do you click button

When I input data in text input and then click button "Save Task" data will show is list in bottom descend. Now i console.log I want to show data when after click button. I don't know how to get data show when after click button "Save Tasks" so I did console.log
app.html
<div class="form-group" *ngIf="saveTask">
<div class="form-row">
<div class="form-group col-md-12">
<label for="subjectTask" class="control-label">Subject Task</label>
<input formControlName="subjectTask" type="text" class="form-control" id="subjectTask"
placeholder="Subject Task">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="assignDev" class="control-label">Assign Dev</label>
<select formControlName="assignTasks" name="assignTasks" class="form-control" id="assignTasks">
<option value="">choose dev...</option>
<option *ngFor="let staff of Staff" [ngValue]="staff.fullName">
{{staff.firstName}} {{staff.lastName}}
</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="deadline" class="control-label">Deadline</label>
<input formControlName="deadlineDate" type="number" class="form-control" id="deadlineDate"
placeholder="Deadline">
</div>
</div>
<div class="form-row">
<div class="form-group mr-5">
<button type="button" class="btn btn-light btn-cancel">Cancel</button>
</div>
<div class="form-group">
<button type="button" class="btn btn-success" (click)="onTasksSubmit()">Save Tasks</button>
</div>
</div>
</div>
app.ts
onTasksSubmit() {
const subject = this.editTicket.controls.subjectTask.value
const assignTasks = this.editTicket.controls.assignTasks.value
const deadlineDate = this.editTicket.controls.deadlineDate.value
this.newTask = {
subject, assignTasks, deadlineDate
}
this.depositTasks.push(this.newTask)
this.clearTask()
console.log(this.newTask);
// this.saveTask = false;
}
clearTask() {
this.editTicket.patchValue({
subjectTask: '',
assignTasks: '',
deadlineDate: ''
})
}
saveTasks() {
if (this.depositTasks.length != 0) {
console.log('do');
for (let i = 0; this.depositTasks.length > i; i++) {
console.log(this.depositTasks);
this.ticketService.setAddTasks(
this.id,
this.depositTasks[i]
)
}
}
}
<p *ngFor="let task of depositTasks">{{task?.subject}}</p>
try to use the depositTasks array in template as shown above.

Codeigniter image upload with Javascript

Problem: Working on a save product information page here I wanted to upload images using Codeigniter and Javascript. Other text boxes and select box data save function working fine. Tried following code but it shows error: You did not select a file to upload.
Please help me to solve this error and upload an image file.
Code:
View: addProduct.php
<div class="tz-2 tz-2-admin">
<div class="tz-2-com tz-2-main">
<h4>Add New Product</h4>
<div class="split-row">
<div class="col-md-12">
<div class="box-inn-sp ad-inn-page">
<div class="tab-inn ad-tab-inn">
<div class="hom-cre-acc-left hom-cre-acc-right">
<div class="">
<form class="">
<span id="statusBar"></span>
<div class="row">
<div class="input-field col s12">
<input id="prod_id" type="text" class="validate" disabled>
<label id="lblProdId" for="prod_id">Product ID</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_name" type="text" class="validate">
<label for="prod_name">Product Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_short_name" type="text" class="validate">
<label for="prod_short_name">Short Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_cat" class="validate">
<option value="">-- Select Category --</option>
<?php foreach($categories as $Category):?>
<option value="<?php echo $Category->Cat_ID;?>"><?php echo $Category->Cat_Name;?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12" >
<select id="prod_brand" class="validate">
<option value="">-- Select Brand--</option>
<?php foreach($brands as $brand):?>
<option value="<?php echo $brand->Brand_ID;?>"><?php echo $brand->Brand_Name;?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_mrp" type="text" class="validate">
<label for="prod_mrp">MRP</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_p_price" type="text" class="validate">
<label for="prod_p_price">Purchase Price</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_s_price" type="text" class="validate">
<label for="prod_s_price">Min. Selling Price</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_uom" class="validate">
<option>-- Seletct Unit of Measure --</option>
<option value="Kilos">Kilos</option>
<option value="Liters">Liters</option>
<option value="Meters">Meters</option>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_size" type="text" class="validate">
<label for="prod_size">Size</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_per_unit" type="text" class="validate">
<label for="prod_per_unit">Products per unit</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_SGST" type="text" class="validate">
<label for="prod_SGST">SGST</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_CGST" type="text" class="validate">
<label for="prod_CGST">CGST</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="prod_IGST" type="text" class="validate">
<label for="prod_IGST">IGST</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_GST_inc" class="validate">
<option value=""selected>Is Inclusive GST</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="prod_status" class="validate">
<option>-- Select Status </option>
<option value="Enabled">Enabled</option>
<option value="Enabled">Disabled</option>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="prod_description" class="materialize-textarea validate"></textarea>
<label for="prod_description">Descriptions</label>
</div>
</div>
<div class="row tz-file-upload">
<div class="file-field input-field">
<div class="tz-up-btn"> <span>File</span>
<input type="file" id="prod_image" > </div>
<div class="file-path-wrapper db-v2-pg-inp">
<input class="file-path validate" id="prod_image" type="text">
<label for="prod_image" style="padding-left:12%;" >Product Image</label>
</div>
</div>
</div>
<div class="row">
<div class="input-field col s12" id="btnSaveProd"> <a class="waves-effect waves-light btn-large full-btn" href="#!" onclick="ajax_addProduct();">Save Product</a> </div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function ajax_addProduct(){
event.preventDefault();
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "<?php echo base_url();?>products/save";
var prod_name = document.getElementById("prod_name").value;
var prod_short_name = document.getElementById("prod_short_name").value;
var prod_cat = document.getElementById("prod_cat").value;
var prod_brand = document.getElementById("prod_brand").value;
var prod_mrp = document.getElementById("prod_mrp").value;
var prod_p_price = document.getElementById("prod_p_price").value;
var prod_s_price = document.getElementById("prod_s_price").value;
var prod_uom = document.getElementById("prod_uom").value;
var prod_size = document.getElementById("prod_size").value;
var prod_per_unit = document.getElementById("prod_per_unit").value;
var prod_SGST = document.getElementById("prod_SGST").value;
var prod_CGST = document.getElementById("prod_CGST").value;
var prod_IGST = document.getElementById("prod_IGST").value;
var prod_GST_inc = document.getElementById("prod_GST_inc").value;
var prod_status = document.getElementById("prod_status").value;
var prod_description = document.getElementById("prod_description").value;
var prod_image = document.getElementById("prod_image").files[0].name;
var vars = "prod_name="+prod_name+"&prod_short_name="+prod_short_name+"&prod_cat="+prod_cat+"&prod_brand="+prod_brand+"&prod_mrp="+prod_mrp+"&prod_p_price="+prod_p_price+"&prod_s_price="+prod_s_price+"&prod_uom="+prod_uom+"&prod_size="+prod_size+"&prod_per_unit="+prod_per_unit+"&prod_SGST="+prod_SGST+"&prod_CGST="+prod_CGST+"&prod_IGST="+prod_IGST+"&prod_GST_inc="+prod_GST_inc+"&prod_status="+prod_status+"&prod_description="+prod_description+"&prod_image="+prod_image;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
if (return_data > 0) {
document.getElementById("statusBar").className = "";
document.getElementById("statusBar").innerHTML = "<p class='alert alert-success' style='font-size:16px; padding-top:2%; text-align:center;'> <strong>Success...!</strong> New category added.</p>";
//var elem = document.getElementById("btnSaveProd");
//elem.parentNode.removeChild(elem);
var elem = document.getElementById("lblProdId");
elem.parentNode.removeChild(elem);
document.getElementById("prod_id").value = return_data;
}
else{
document.getElementById("statusBar").className = "";
document.getElementById("statusBar").innerHTML = return_data;
}
}
else {
document.getElementById("statusBar").innerHTML = return_data;
}
}
if (prod_name != "" && prod_short_name != "") {
hr.send(vars);
document.getElementById("statusBar").className = "alert alert-info";
document.getElementById("statusBar").innerHTML = "processing...";
}
else if(prod_name == ""){
document.getElementById("prod_name").className = "validate invalid";
var elmnt = document.getElementById("statusBar");
elmnt.scrollIntoView();
}
else if(prod_short_name == ""){
document.getElementById("prod_short_name").className = "validate invalid";
var elmnt = document.getElementById("prod_name");
elmnt.scrollIntoView();
}
}
</script>
Controller: Products.php
public function save()
{
$data['Prod_Name'] = $this->input->post('prod_name', TRUE);
$data['Prod_Short_Name'] = $this->input->post('prod_short_name', TRUE);
$data['Cat_ID'] = $this->input->post('prod_cat', TRUE);
$data['Brand_ID'] = $this->input->post('prod_brand', TRUE);
$data['Prod_MRP'] = $this->input->post('prod_mrp', TRUE);
$data['Prod_P_Price'] = $this->input->post('prod_p_price', TRUE);
$data['Prod_S_Price'] = $this->input->post('prod_s_price', TRUE);
$data['Prod_UOM'] = $this->input->post('prod_uom', TRUE);
$data['Prod_Size'] = $this->input->post('prod_size', TRUE);
$data['Prod_Per_Unit'] = $this->input->post('prod_per_unit', TRUE);
$data['Prod_SGST'] = $this->input->post('prod_SGST', TRUE);
$data['Prod_CGST'] = $this->input->post('prod_CGST', TRUE);
$data['Prod_IGST'] = $this->input->post('prod_IGST', TRUE);
$data['Prod_GST_Inclusive'] = $this->input->post('prod_GST_inc', TRUE);
$data['Prod_Status'] = $this->input->post('prod_status', TRUE);
$data['Prod_Description'] = $this->input->post('prod_description', TRUE);
$data['Prod_Image'] = $this->input->post('prod_image', TRUE);
$this->do_upload();
if ($pid = $this->Products_Model->saveProduct($data))
{
echo $pid;
}
else
{
echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong> Unable to add category.</p>";
}
}
public function do_upload()
{
$config['upload_path'] = base_url(). "uploads/";
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('Prod_Image'))
{
$error = array('error' => $this->upload->display_errors());
echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong>".$error['error'].".</p>";
}
else
{
$data = array('upload_data' => $this->upload->data());
echo "<p class='alert alert-warning' style='font-size:17px; padding-top:2%; text-align:center;'><strong>Ooops!</strong>".$data['upload_data'].".</p>";
}
}
Please help me to upload and save filename to the database.
NOTE: Don't want to use Jquery. Please suggest an answer with traditional Javascript.
To submit the form with image and other data, use the below code
<?php echo form_open_multipart('', 'id="your_form_id"'); ?>
<?php echo form_close(); ?>
And script
$("#your_form_id").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "<?php echo base_url();?>products/save",
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
// your code here
},
success: function(json)
{
// your code here
}
});
});

removing child elements if api returns null array

i am calling my local API which returns the list of products while onchange event is triggered.
i am also creating new option element for each array and setting name and value to it. the created element is appended on select element.
but the problem is. for example 1st call returns 1 array and the second call to api returns 2 arrays.
so on second call 3 option elements will be rendered on form while it should be only 2 option elements.
<form class="form-horizontal" id="productForm"
th:action="#{/addProduct}" method="post">
<div class="form-group">
<div th:if="${productAdded}">
<div class="alert alert-success">
<p>Product added successfully</p>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Category:</label>
<div class="col-sm-10">
<select class="form-control" id="category" name="category">
<option th:name="category" th:each="cat : ${categories}"
th:value="${catth:text="${cat.category}"></option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="productName">Name:</label>
<div class="col-sm-10" >
<select class="form-control" id="productName"></select>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Price:</label>
<div class="col-sm-10">
<input type="number" class="form-control"
placeholder="Product Price" name="price" id="price">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Quantity:</label>
<div class="col-sm-10">
<input type="number" class="form-control"
placeholder="Quantity" name="quantity">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Vendor:</label>
<div class="col-sm-10">
<input type="text" class="form-control"
placeholder="Product Vendor" name="vendor" id="vendor">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
AddProduct.js
//adding event listener to category select box
document.getElementById("category")
.addEventListener('change',getProductDetails);
let products = document.getElementById("productName");
let prodPrice = document.getElementById("price");
let prodVendor = document.querySelector("#vendor");
let productForm = document.querySelector('#productForm');
console.log(productForm);
function getProductDetails() {
let category = document.getElementById("category").value;
fetch("
http://localhost:6080/getProductDetailsByCategory?category="+category)
.then((res) => res.json())
.then((data) => {
console.log(data)
if(data ==null || data.length ==0){
refresh();
}
data.forEach(function (t) {
let optionBox = document.createElement("option");
console.log(t.productName);
optionBox.text=t.productName;
optionBox.value= t.productName;
products.appendChild(optionBox);
});
})
}
function refresh(){
window.location.reload(true);
}
Clear the select element then insert all those options came as the result of the api call. I guess you are not getting only the new records as the response but getting all the records, hence remove every option and then insert all. In the .then section of code, write this.
.then((data) => {
console.log(data)
if(data ==null || data.length ==0){
refresh(); // Instead of refreshing the page
}
// clear the select element first
products.innerHTML = "";
data.forEach(function (t) {
let optionBox = document.createElement("option");
console.log(t.productName);
optionBox.text=t.productName;
optionBox.value= t.productName;
products.appendChild(optionBox);
});
})

javascript illegal invocation in $.ajax

I want to upload an image using ajax in Laravel. Sending formData is giving me
Uncaught TypeError: Illegal invocation
at e (jquery-2.1.4.js:4)
at Ab (jquery-2.1.4.js:4)
at Function.n.param (jquery-2.1.4.js:4)
at Function.ajax (jquery-2.1.4.js:4)
at HTMLFormElement.<anonymous> (products:153)
at HTMLFormElement.dispatch (jquery-2.1.4.js:3)
at HTMLFormElement.r.handle (jquery-2.1.4.js:3)
in the console. I checked the networks and found that formData is fine.
Here is my ajax call
$('#product_form').on('submit', function (e) {
e.preventDefault();
var form_data = new FormData( $('#product_form')[0]);
$.ajax({
type: 'POST',
url: '/admin/insert/products',
data : form_data,
success: function (result) {
if(result.success == 1){
$('#product_message').html('product Successfully Added!!');
}
},
error: function(result){
$('#product_message').html('Something went wrong!! Login Again!!');
$('#product_submit').prop("disabled" ,false);
$('#product_submit').html("Add product");
}
});
});
And this is my form in the view
<form class="col s12" method="post" enctype="multipart/form-data" id="product_form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="input-field col s12 m4 offset-m4">
<input id="name" type="text" class="validate" name="name">
<label for="name">Item Name</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<input id="tagline" type="text" class="validate" name="tagline">
<label for="tagline">Tagline</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<div class="file-field input-field">
<div class="btn red">
<span>Item Pic</span>
<input type="file" id="pic" name="item">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div class="input-field col s12 m4 offset-m4">
<input id="brand" type="text" class="validate" name="brand" style="text-transform:uppercase;">
<label for="brand">Brand Name</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<select name="category">
<option value="" selected>Choose Category</option>
#foreach($categories as $category)
<option value="{{$category->name}}">{{$category->name}}</option>
#endforeach
</select>
<label>Select Item Category</label>
</div>
<div class="input-field col s12 m4 offset-m4">
<button type="submit" class="btn col s12 red" id="product_submit">Add Product</button>
</div>
</div>
</form>
Add the following parameters to the passed object to $.ajax:
contentType: false,
// The following is necessary so jQuery won't try to convert the object into a string
processData: false

how can i capture multiple form inputs and save in an array

<template name="uploadTicket">
<div class="row">
<h3> Upload Ticket</h3>
<form class="ticket-form col s12" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12">
<input id="name" type="text" class="validate">
<label for="name">Event Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="location" type="text" class="validate">
<label for="location">Location</label>
</div>
</div>
<div class="row">
<div class="input-field col s4">
<input id="date" type="date" class="validate">
<label for="date"></label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<textarea id="description" class="materialize-textarea"></textarea>
<label for="Description">Description</label>
</div>
</div>
<div class="row">
<div class="col s6">
<h5>More Price Fields</h5>
</div>
<div class="col s6">
<a class="btn-floating btn-large waves-effect waves-light red" id="addField"><i class="mdi mdi-plus"></i></a>
</div>
</div>
<div class="wrapper">
<div class="row">
<div class="input-field col s4">
<input name="priceClass[]" type="text" class="validate">
<label for="priceClass[]">Class</label>
</div>
<div class="input-field col s4">
<input name="priceAmount[]" type="text" class="validate">
<label for="priceAmount[]">Price</label>
</div>
<div class="input-field col s4">
<h6>Input Price Classes and Amounts.</h6>
</div>
</div>
<br>
</div>
<br>
<div class="row">
<div >
<button class="waves-effect waves-light btn" type="submit">Upload</button>
</div>
</div>
</form>
</div>
</template>
This is my Template
Template.uploadTicket.events({
'click #addField': function (event) {
event.preventDefault();
var max_fields = 10;
var wrapper = $(".wrapper");
var add_button = $(".addField");
var x = 1;
if (x < max_fields)
{
x++; //text box increment
$(wrapper).append(' <div class="row"> <div class="input-field col s4"> <input name="priceClass[]" type="text" class="validate"> <label for="priceClass[]">Class</label> </div> <div class="input-field col s4"> <input name="priceAmount[]" type="text" class="validate"> <label for="priceAmount[]">Price</label> </div> <a class="btn-floating btn-large waves-effect waves-light red" id="removeField"><i class="mdi mdi-minus"></i></a></div> <br>'); //add input box
}
$(wrapper).on("click","#removeField", function(e)
{ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
}
});
This is my JavaScript for that template. I am giving the user option to add multiple fields so that they can have different classes for prices. Like gold class for a certain amount, VIP for another amount ,regular for another amount and so on. I am having a problem with how to get those input values when submitting the values and saving them into an array.
You would use jquery to loop through your inputs and send their values into an empty array. Then take the array with data and send it to your collection.
let valueStore = [];
console.log(valueStore) // an empty array
$('.input-field input').each(function(){
if (this.value != ''){
valueStore.push(this.value)
}
})
console.log(valueStore) // will have your values.
You can use JQuery-Selectors to get all Input Fields. You allready gave them a class. After that you can extract all necessary information into your array.
The JQuery-Selector should look something like:
$('.input-field')
Use a forEach loop to get every selected element.

Categories

Resources