I'm trying to push input value into an array based on input fields. But the problem I'm facing here is that the last input field will replace all the objects in my array like this:
[
{
"label":"4",
"type":"",
"process":"",
"name":"5",
"col":"6"
},
{
"label":"4",
"type":"",
"process":"",
"name":"5",
"col":"6"
}
]
What I'm expecting it to return is the value of each input in each field separately. This means that instead of seeing the object above, it should be label: 1, name: 2, col: 3 etc etc in the correct order. I'm not sure what I'm missing here because my code makes sense to me. What am I doing wrong?
$(document).ready(() => {
$('.add-field').click(e => {
e.preventDefault();
generateField();
});
$('.form-maker').submit(e => {
e.preventDefault();
const temp = {},
payload = [];
$('.dynamic-group').each((i, group) => {
$(group)
.find('input, select')
.each((ii, field) => {
temp[field.name] = field.value;
});
payload.push(temp);
});
console.log(payload);
});
const generateField = () => {
$('.dynamic-fields').append(
`
<div class="form-inline dynamic-group">
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Input Label</div>
</div>
<input type="text" class="form-control" placeholder="Input Label" name="label">
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Input Type</div>
</div>
<select name="type" name="type">
<option value="">Something in here</option>
</select>
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Process</div>
</div>
<select name="process" name="process">
<option value="">Something in here</option>
</select>
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Input Name</div>
</div>
<input type="text" class="form-control" placeholder="Input Name" name="name">
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">DB. Col Name</div>
</div>
<input type="text" class="form-control" placeholder="DB. Col Name" name="col">
</div>
</div>
<hr />
`
);
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-fields"></div>
<button class="add-field">
Add Field
</button>
<button type="submit">
Make Form
</button>
It's because you're referencing the same object every time, so the last thing to get updated wins. You'd want a copy of the object pushed into the array:
$('.dynamic-group').each((i, group) => {
$(group)
.find('input, select')
.each((ii, field) => {
temp[field.name] = field.value;
});
payload.push($.extend(true,{},temp));
});
There are a number of ways to make object copies - in this case I'm using JQuery's extend method to make a true copy of the object, https://api.jquery.com/jquery.extend/
$.extend(true,{},temp)
The temp variable must be placed within the inner loop of each group:
$(document).ready(() => {
$(".add-field").click(e => {
e.preventDefault();
generateField();
});
$(".form-maker").click(e => {
e.preventDefault();
const payload = [];
$(".dynamic-group").each((i, group) => {
const temp = {};
$(group)
.find("input, select")
.each((ii, field) => {
temp[field.name] = field.value;
});
payload.push(temp);
});
console.log(payload);
});
const generateField = () => {
$(".dynamic-fields").append(
`
<div class="form-inline dynamic-group">
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Input Label</div>
</div>
<input type="text" class="form-control" placeholder="Input Label" name="label">
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Input Type</div>
</div>
<select name="type" name="type">
<option value="">Something in here</option>
</select>
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Process</div>
</div>
<select name="process" name="process">
<option value="">Something in here</option>
</select>
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">Input Name</div>
</div>
<input type="text" class="form-control" placeholder="Input Name" name="name">
</div>
<div class="input-group mb-2 mr-sm-2">
<div class="input-group-prepend">
<div class="input-group-text">DB. Col Name</div>
</div>
<input type="text" class="form-control" placeholder="DB. Col Name" name="col">
</div>
</div>
<hr />
`
);
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-fields"></div>
<button class="add-field">
Add Field
</button>
<button class="form-maker" type="submit">
Make Form
</button>
Related
I apply the CKEditor to textarea to my project but the form doesn't submit
like I didn't even press the button
though if I remove the required from textarea it does submit
but I need to check required
let elements = document.querySelectorAll('.editor')
for (let element of elements) {
ClassicEditor.create(element, {})
.then(editor => {
element.ckEditor = editor;
})
.catch(err => {
console.error(err.stack);
});
}
<form method="POST" action="../forms/add-services.php">
<div class="service-fields mb-3">
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label class="h6">Title <span class="text-danger">*</span></label>
<input class="form-control" type="text" name="service_title" id="service_title" required>
</div>
</div>
</div>
</div>
<div class="service-fields mb-3">
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label class="h6">details <span class="text-danger">*</span></label>
<textarea name="details" id="editor1" class="editor form-control " required></textarea>
</div>
</div>
</div>
</div>
<div class="submit-section d-flex justify-content-between">
<button class="btn btn-primary submit-btn" type="submit" name="save">Save</button>
</div>
</form>
I'm building an input form project for my job and I'm running into a problem with persisting a certain input value. When the user creates a new project, they have to give that project a project ID. I have 5 forms that the user goes through and I want them to be able to enter the project ID in once on the first form, and then have it persist to the other 4 forms without them having to type it in again.
This is the html form where I want to pull the project ID and persist it to the rest of my forms.
I want to pull the value using the id "pid" and then when the button at the bottom is clicked with id of 'data' I want the value to be pushed into a variable.
<form action="/metadata" method="POST">
<div class="row">
<div class="col-md-4">
<div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Project ID:</span>
</div>
<input name="project_id" type="text" id="pid" class="form-control">
</div>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Building:</label>
<select name="building" class="form-select" id="inputGroupSelect01">
<option disabled selected>Choose...</option>
{{#each bldgs}}
<option>{{acronym}}</option>
{{/each}}
</select>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Measure Type:</label>
<select name="measure_type" class="form-select" id="inputGroupSelect01">
<option disabled selected>Choose...</option>
<option>AHU DDC</option>
<option>AHU DDC & Scheduling</option>
<option>Data Center</option>
<option>EBCx</option>
<option>EMOCx</option>
<option>Exhaust System Optimization</option>
<option>Holiday Scheduling</option>
<option>Lighting</option>
<option>Optimum Energy</option>
<option>Scheduling</option>
<option>Valves</option>
<option>VFD Supply Fan</option>
<option>Water</option>
<option>Other</option>
</select>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupSelect01">Status:</label>
<select name="status" class="form-select" id="inputGroupSelect01">
<option disabled selected>Choose...</option>
<option>0-Cancelled</option>
<option>1-Planning</option>
<option>2-In Progress</option>
<option>3-In Reporting Period</option>
<option>5-Completed</option>
</select>
</div>
</div>
<div class="col-md-4 mt-5">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Start Date:</span>
</div>
<input placeholder="mm/dd/yy" name="baseline_start_date" type="text" class="form-control" />
<input placeholder="mm/dd/yy" name="reporting_period_start_date" type="text"
class="form-control" />
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default"># of Days:</span>
</div>
<input placeholder="mm/dd/yy" name="length_baseline_period_days" type="text"
class="form-control" />
<input placeholder="mm/dd/yy" name="length_reporting_period_days" type="text"
class="form-control" />
</div>
</div>
<div class="col-md-4 mt-5">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Staff Lead:</span>
</div>
<select name="staff_lead" class="form-select" id="inputGroupSelect01">
<option disbaled selected>Choose...</option>
<option>Adam Keeling</option>
<option>Amanda Berens</option>
<option>Buddy Bishop</option>
<option>Dave Cooper</option>
<option>Grace Hsieh</option>
<option>John Milton</option>
<option>Matt Stevens</option>
<option>Meagan Jones</option>
<option>Pat Mazur</option>
<option>Richard Shearman</option>
<option>Travis Isakson</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Staff Support:</span>
</div>
<select name="staff_colead" class="form-select" id="inputGroupSelect01">
<option disbaled selected>Choose...</option>
<option>Adam Keeling</option>
<option>Amanda Berens</option>
<option>Buddy Bishop</option>
<option>Dave Cooper</option>
<option>Grace Hsieh</option>
<option>John Milton</option>
<option>Matt Stevens</option>
<option>Meagan Jones</option>
<option>Pat Mazur</option>
<option>Richard Shearman</option>
<option>Travis Isakson</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Analyst:</span>
</div>
<select name="analyst" class="form-select" id="inputGroupSelect01">
<option disabled selected>Choose...</option>
<option>Jeff McComas</option>
<option>Josh Butler</option>
<option>Laura Chiasson</option>
<option>Terrell McRee</option>
</select>
</div>
</div>
</div>
<div class="input-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text">Project Description:</span>
</div>
<textarea rows='5' name="project_description" class="form-control"
aria-label="With textarea"></textarea>
</div>
<div class="input-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text">Nonenergy Benefits:</span>
</div>
<textarea rows='2' name="nonenergy_benefits" class="form-control"
aria-label="With textarea"></textarea>
</div>
<div class="text-end">
<button type="submit" id="data" style="background-color: #bf5700;"
class="btn text-light btn-warning mt-3">Next</button>
</div>
</form>
This is my js file. Each on click is a different page. However each form has the same input of project ID with a class of "project_id". So I try to $(".project_id").val(projectId) but when I move on the next form nothing happens. Each form has an input value with a class of "project_id" and thats where I try to set it based on the input from the first form.
This is a link to the repo if it helps to see all the code.
https://github.com/oballematt/ecm_input_forms
Any advice on how to achieve this is greatly appreciated! Thanks!
const projectId = []
$("#data").on('submit', () => {
projectId.push($('#pid').val())
})
$('.project_id').val(projectId)
$('#tableData').on('click', 'button.addRow', function(e) {
const cloneRow = $('#tableData tbody tr').first();
e.preventDefault();
let data = {
project_id: $(".project_id").last().val(),
imp_or_ann: $(".imp_or_ann").last().val(),
category: $(".category").last().val(),
cost: $(".cost").last().val(),
hours: $(".hours").last().val()
}
$.ajax({
url: '/costs_hours',
type: 'POST',
data: data
}).then(
cloneRow.clone().appendTo('#tableData tbody').find(".cost, .hours").val(''),
$("#next").removeAttr('disabled'),
$("#link").attr('href', '/fundings'),
)
})
$('#tableData').on('click', 'button.addRowF', function(e) {
const cloneRow = $('#tableData tbody tr').first();
e.preventDefault();
let data = {
project_id: $(".project_id").last().val(),
source: $(".source").last().val(),
implementation: $(".implementation").last().val(),
annual: $(".annual").last().val(),
}
$.ajax({
url: '/fundings',
type: 'POST',
data: data
}).then(
cloneRow.clone().appendTo('#tableData tbody').find(".implementation, .annual").val(''),
$("#next").removeAttr('disabled'),
$("#link").attr('href', '/baseline')
)
})
$('#tableData').on('click', 'button.addRowB', function(e) {
const cloneRow = $('#tableData tbody tr').first();
e.preventDefault();
let data = {
project_id: $(".project_id").last().val(),
commodity: $(".commodity").last().val(),
unit: $(".unit").last().val(),
value: $(".value").last().val(),
}
$.ajax({
url: '/baseline',
type: 'POST',
data: data
}).then(
cloneRow.clone().appendTo('#tableData tbody').find(".value").val(''),
$("#next").removeAttr('disabled'),
$("#link").attr('href', '/savings')
)
})
$('#tableData').on('click', 'button.addRowS', function(e) {
const cloneRow = $('#tableData tbody tr').first();
e.preventDefault();
let data = {
project_id: $(".project_id").last().val(),
phase: $(".phase").last().val(),
commodity: $(".commodity").last().val(),
unit: $(".unit").last().val(),
value: $(".value").last().val()
}
$.ajax({
url: '/savings',
type: 'POST',
data: data
}).then(
cloneRow.clone().appendTo('#tableData tbody').find(".value").val(''),
$("#next").removeAttr('disabled'),
$("#link").attr('href', '/')
)
})
To persist values across pages, several solutions can be used : localStorage, queryString, State machines.
Here the problem comes from that val(projectId) is not defined since you reload a new page.
Depending on your constraint for your app, I would advice you to use queryString since it is very straightforward (just add the query in the URL and you can retrieve it with JS).
https://en.wikipedia.org/wiki/Query_string
function add_variant(){
var thickness=document.forms["create_product"]["thickness"].value;
var thickness_unit=document.forms["create_product"]["thickness_unit"].value;
var product_qty=document.forms["create_product"]["product_qty"].value;
var product_cost_price=document.forms["create_product"]["product_cost_price"].value;
var product_unit=document.forms["create_product"]["product_unit"].value;
var product_color=document.forms["create_product"]["product_color"].value;
var thickness_dim =document.forms["create_product"]["thickness"].value;
console.log("thick"+thickness);
console.log("thick dim"+thickness_dim);
if(thickness == null || thickness == "", thickness_dim ==""|| thickness_dim==null)
{
alert('you must filled previous data');
return false;
}
var temp = document.getElementById("product_dimension").content;
var copy = document.importNode(temp,true);
document.getElementById("product_description").appendChild(copy);
}
<div class="col-md-2">
<label>Product Variants</label>
<a class="btn btn-primary" id="add_variant" onclick="add_variant()"><i class="fa fa-plus"></i> add Variant</a>
</div>
<div id="product_description">
<div class="row" >
<div class="col-sm-1">
<div class="form-group">
<label>Actions</label><br>
<button class="btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label>Thickness</label>
<input type="number" class="form-control" name="thickness" id="thickness">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Thickness Unit</label>
<select class="form-control"name="thickness_unit" id="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Steel Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Qty.</label>
<input type="number" class="form-control" name="product_qty" id="product_qty">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" id="product_cost_price">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Unit</label>
<select class="form-control" name="product_unit" id="product_unit">
<option>Sheet</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Color</label>
<input type="text" class="form-control" name="product_color" id="product_color">
</div>
</div>
</div>
</div>
<div>
<template id="product_dimension">
<div class="row">
<div class="col-md-1">
<div class="form-group">
<label>Actions</label><br>
<button class="btn btn-danger btnDelete"><i class="fa fa-trash"></i></button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label>Thickness</label>
<input type="number" class="form-control" name="thickness" id="thickness">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Thickness Unit</label>
<select class="form-control"name="thickness_unit" id="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Qty.</label>
<input type="number" class="form-control" name="product_qty" id="product_qty">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" id="product_cost_price">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Unit</label>
<select class="form-control" name="product_unit" id="product_unit">
<option>Sheet</option>
<option>Nos</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Product Color</label>
<input type="text" class="form-control" name="product_color" id="product_color">
</div>
</div>
</div>
</template>
</div>
i am new to java script i am trying to add some validations on my add product form in which i am trying to perform some append function in whixh i want to append a div but if the previous row is empty then it should not add/append new row but while doing so it just check validation for the 1st row when i add 2 nd add try to add 3rd it shows error
will please anybody help me to solve this,here is my code
JS:
function add_variant(){
var thickness=document.forms["create_product"]["thickness"].value;
var thickness_unit=document.forms["create_product"]["thickness_unit"].value;
var product_qty=document.forms["create_product"]["product_qty"].value;
var product_cost_price=document.forms["create_product"]["product_cost_price"].value;
var product_unit=document.forms["create_product"]["product_unit"].value;
var product_color=document.forms["create_product"]["product_color"].value;
var thickness_dim =document.forms["create_product"]["thickness"].value;
console.log("thick"+thickness);
console.log("thick dim"+thickness_dim);
if(thickness == null || thickness == "", thickness_dim ==""|| thickness_dim==null)
{
alert('you must filled previous data');
return false;
}
var temp = document.getElementById("product_dimension").content;
var copy = document.importNode(temp,true);
document.getElementById("product_description").appendChild(copy);
}
<div id="product_description">
<div class="row" >
<div class="col-sm-1">
<button class="btn btn-danger"><i class="fa fa-
trash"></i></button>
</div>
<!--further fields-->
</div>
<template id="product_dimension">
<div class="row">
<div class="col-md-1">
<div class="form-group">
<button class="btn btn-danger btnDelete"><i class="fa fa-trash"></i>
</button>
<!--further fields->
</div>
</div>
</template>
`
Here is the code:
const addVariant = document.getElementById("add_variant");
const productDescription = document.getElementById("product_description");
const errorAlert = document.querySelector(".alert");
const template = `<div class="row my-4 p-3 rounded productTemp">
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Actions</label>
<br />
<button class="btn btn-danger btnDelete">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Thickness</label>
<input type="number" class="form-control" name="thickness" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Thickness Unit</label>
<select class="form-control" name="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Qty.</label>
<input type="number" class="form-control" name="product_qty" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Unit</label>
<select class="form-control" name="product_unit">
<option>Sheet</option>
<option>Nos</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Color</label>
<input type="text" class="form-control" name="product_color" />
</div>
</div>
</div>
`;
function addAlert(message) {
errorAlert.classList.add("show");
errorAlert.innerHTML = message;
setTimeout(() => {
errorAlert.classList.remove("show");
}, 3000);
}
addVariant.addEventListener("click", function() {
const productTemp = document.querySelectorAll(".productTemp");
const lastElement = productTemp[productTemp.length - 1];
const thickness = lastElement.querySelector('[name="thickness"]');
const thicknessUnit = lastElement.querySelector('[name="thickness_unit"]');
const productQty = lastElement.querySelector('[name="product_qty"]');
const productPrice = lastElement.querySelector('[name="product_cost_price"]');
const productUnit = lastElement.querySelector('[name="product_unit"]');
const productColor = lastElement.querySelector('[name="product_color"]');
if (
thickness.value !== "" &&
thicknessUnit.value !== "" &&
productQty.value !== "" &&
productPrice.value !== "" &&
productUnit.value !== "" &&
productColor.value !== ""
) {
productDescription.insertAdjacentHTML("beforeend", template);
} else {
addAlert("Fields can not be empty! 😑");
}
});
.productTemp {
background-color: #2c3035;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
<body class="bg-dark text-white">
<div class="container mt-5 bg-dark text-white">
<div class="alert alert-danger alert-dismissible fade mb-5" role="alert"></div>
<div class="col-md-2 mb-4">
<label class="mb-2">Product Variants</label>
<a class="btn btn-primary" id="add_variant">
<i class="fa fa-plus"></i> add Variant
</a>
</div>
<div id="product_description">
<div class="row my-4 p-3 rounded productTemp">
<div class="col-sm-1">
<div class="form-group">
<label class="mb-2">Actions</label>
<br />
<button class="btn btn-danger">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<label class="mb-2">Thickness</label>
<input type="number" class="form-control" name="thickness" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Thickness Unit</label>
<select class="form-control" name="thickness_unit">
<option>mm</option>
<option>feet</option>
<option>Square feet</option>
<option>meter</option>
<option>mm square</option>
<option>Steel Gauge</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Qty.</label>
<input type="number" class="form-control" name="product_qty" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Cost Price</label>
<input type="number" class="form-control" name="product_cost_price" />
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Unit</label>
<select class="form-control" name="product_unit">
<option>Sheet</option>
<option>No</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="mb-2">Product Color</label>
<input type="text" class="form-control" name="product_color" />
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
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.
I want to auto populate a form consisting of different input types (select boxes and text areas) dynamically. I am able to get input boxes working just fine, here is an example:
function autofill(){
var data = [{visible_retail: "0", brand: "cool!", description: "hello there!"}];
console.log(data);
data.map(function(item) {
for (var key in item)
$('input[id=product-'+key+']').val(item[key]);
}).join();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="product-form">
<div class="form-group row">
<label for="product-visible_retail" class="col-4 col-form-label">Visibility (Retail)</label>
<div class="col-8">
<select class="form-control" id="product-visible_retail" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="product-brand" maxlength="50" required>
</div>
</div>
<div class="form-group row">
<label for="product-description" class="col-4 col-form-label">Description</label>
<div class="col-8">
<textarea class="form-control" id="product-description" rows="4" cols="50" maxlength="65535" required></textarea>
</div>
</div>
</form>
<button onclick="autofill()">auto fill</button>
Edit: the form I posted is just an example. In reality I have hundreds of fields that need to be auto propagated. Hence defining them individually really isn't an optimal.
The issue is that a textarea control is NOT an input. And also, you should use .html() or .text() to set a value in it.
I did a little modification to your code:
function autofill(){
var data = [{visible_retail: "0", brand: "cool!", description: "hello there!"}];
console.log(data);
data.map(function(item) {
for (var key in item)
if(key == "description")
$('#product-' + key).text(item[key]);
else if(key == "visible_retail")
$('#product-' + key).val(item[key]);
else
$('input[id=product-'+key+']').val(item[key]);
}).join();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="product-form">
<div class="form-group row">
<label for="product-visible_retail" class="col-4 col-form-label">Visibility (Retail)</label>
<div class="col-8">
<select class="form-control" id="product-visible_retail" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="product-brand" maxlength="50" required>
</div>
</div>
<div class="form-group row">
<label for="product-description" class="col-4 col-form-label">Description</label>
<div class="col-8">
<textarea class="form-control" id="product-description" rows="4" cols="50" maxlength="65535" required></textarea>
</div>
</div>
</form>
<button onclick="autofill()">auto fill</button>
You can do something like this with JQuery to add rows/columns dynamically. I saw your question in the comments. CSS class of your table row should be something like this. <tr class="item-row"></tr>
$("#addrow").click(function(){
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><textarea class="item_name">Item Name</textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td class="description"><textarea class="description_val">Description</textarea></td><td><textarea class="cost">N0</textarea></td><td><textarea class="qty">0</textarea></td><td><span class="price">N0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
});
bind();
$(".delete").live('click',function(){
$(this).parents('.item-row').remove();
if ($(".delete").length < 2) $(".delete").hide();
});
we were way off. Here is the super simple solution...
function autofill(){
var data = [{visible_retail: "0", brand: "cool!", description: "hello there!"}];
console.log(data);
data.map(function(item) {
for (var key in item)
$('#product-'+key).val(item[key]);
}).join();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="product-form">
<div class="form-group row">
<label for="product-visible_retail" class="col-4 col-form-label">Visibility (Retail)</label>
<div class="col-8">
<select class="form-control" id="product-visible_retail" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="product-brand" maxlength="50" required>
</div>
</div>
<div class="form-group row">
<label for="product-description" class="col-4 col-form-label">Description</label>
<div class="col-8">
<textarea class="form-control" id="product-description" rows="4" cols="50" maxlength="65535" required></textarea>
</div>
</div>
</form>
<button onclick="autofill()">auto fill</button>