How to create a JSON based on HTML inputs in JavaScript? - javascript

I am having some trouble creating a multi dimension json based on multiple html form inputs:
the html inputs:
<div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="form-input-group">
<label for="title">title</label>
<input type="text" name="title" value="some title" class="form-control">
</div>
</div>
</div>
<div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-image"></i> </div>
<div class="form-input-group">
<label for="image">Image URL</label>
<input type="text" name="image" value="some image url" class="form-control">
</div>
</div>
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-link"></i> </div>
<div class="form-input-group">
<label for="link">Link URL</label>
<input type="text" name="link" value="http://www.google.com" class="form-control">
</div>
</div>
</div>
Here is the javascript code:
var frmData = {};
$(':input').each(function(){
frmData[$(this).attr('name')] = $(this).val();
});
alert(JSON.stringify(frmData));
Here is the json what I am getting:
{"title":"some title","image":"some image url","link":"http://www.google.com"}
What I need instead is after 'title', I would like to create a data object and add everything else as an sub level of 'data' like so:
{"title":"some title","data":{"image":"some image url","link":"http://www.google.com"}}
any help is appreciated.
thank,

Here is the way I would solve it:
var inputToJson = function() {
var formData = {};
formData.data = {};
$('input').each(function( index ) {
if($( this ).attr('name')=="title") {
formData[$( this ).attr('name')] = $( this ).val();
}
else {
formData["data"][$(this).attr('name')] = $( this ).val();
}
});
return formData;
}
console.log(inputToJson());
<script src="https://code.jquery.com/jquery-3.1.0.js"></script><div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="form-input-group">
<label for="title">title</label>
<input type="text" name="title" value="some title" class="form-control">
</div>
</div>
</div>
<div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-image"></i> </div>
<div class="form-input-group">
<label for="image">Image URL</label>
<input type="text" name="image" value="some image url" class="form-control">
</div>
</div>
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-link"></i> </div>
<div class="form-input-group">
<label for="link">Link URL</label>
<input type="text" name="link" value="http://www.google.com" class="form-control">
</div>
</div>
</div>
It's important to note that the proper way to access data from a form is using .serialize() on the actual element but given the special requirement of augmenting parts of the form within a custom "data" object that approach would also require additional manipulation.
JSBIN DEMO

var arr = [];
var frmData = {};
var Title;
var Image;
var Link;
$(':input').each(function() {
if ($(this).attr('name') == 'image')
Image = $(this).val();
else if ($(this).attr('name') == 'link') {
Link = $(this).val();
frmData = {
"title": Title,
"Data": {
"Image": Image,
"Link": Link
}
};
arr.push(frmData)
} else
Title = $(this).val();
});
console.log(JSON.stringify(frmData));//json format
console.log(arr);//arr fomat
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="form-input-group">
<label for="title">title</label>
<input type="text" name="title" value="some title" class="form-control">
</div>
</div>
</div>
<div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-image"></i> </div>
<div class="form-input-group">
<label for="image">Image URL</label>
<input type="text" name="image" value="some image url" class="form-control">
</div>
</div>
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-link"></i> </div>
<div class="form-input-group">
<label for="link">Link URL</label>
<input type="text" name="link" value="http://www.google.com" class="form-control">
</div>
</div>
</div>
<button id="generateJson">Generate Json</button>

The code below gives the output that you want. Just go through that.
var frmData = {};
var frmDataImageArray = [];
var frmDataTitle;
var frmDataImage;
var frmDataLink;
$(':input').each(function(){
if($(this).attr('name')=='image')
frmDataImage=$(this).val();
else if($(this).attr('name')=='link')
{
//Here i assume that link is the last control in this form that's why i put this code here. So that title and image is fetched before entering into this statement
frmDataLink=$(this).val();
frmDataImageArray.push({"Image":frmDataImage,"Link":frmDataLink});
//frmData={"title":frmDataTitle,"Data":{"Image":frmDataImage,"Link":frmDataLink}};
}
else
frmDataTitle=$(this).val();
//frmData[$(this).attr('name')] = $(this).val();
});
frmData={"title":frmDataTitle,"Data":frmDataImageArray};
console.log(JSON.stringify(frmData));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="form-input-group">
<label for="title">title</label>
<input type="text" name="title" value="some title" class="form-control">
</div>
</div>
</div>
<div class="form-group-attached m-b-10">
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-image"></i> </div>
<div class="form-input-group">
<label for="image">Image URL</label>
<input type="text" name="image" value="some image url" class="form-control">
</div>
</div>
<div class="form-group form-group-default input-group required">
<div class="tile-icon input-group-addon d-flex">
<i class="fa-2x fa-color far fa-link"></i> </div>
<div class="form-input-group">
<label for="link">Link URL</label>
<input type="text" name="link" value="http://www.google.com" class="form-control">
</div>
</div>
</div>

Maybe the solution is already in one of the previous answers, but as I am sitting in a train with nothing else to do I put together the following minimal solution:
var jsn={data:{}};
$('input','form:first').each(function(i,o){
var na=$(o).attr('name');
(na=='title'?jsn:jsn.data)[na]=o.value;
});
This can go into the $(function( ... )} section or be triggered by some click event. I am currently treating all inputs within the first <form> element on the page. You can change that to suit your needs.

Related

how to add validation in javascript on form so that it should not append form when last row is empty (should not create another row untill all fields)

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>

Auto propagate form consisting of different input types from json data dynamically

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>

Create Repeated Fields in jQuery

$(documnet).ready(function(){
$('#more_finance').click(function(){
var add_new ='<div class="form-group finance-contact" id="finance_3"><div class="col-sm-9"><label for="firstName" class="control-label">Finance Contact#</label></div><div class="col-sm-9"><input type="text" id="finance" name="finance[]"placeholder="Finance Contact" class="form-control" autofocus></div>\n\
<img src="/img/deleted-box.png"></div>';
$(add_new).insertAfter( "#finance_1");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group finance-contact" id="finance_1">
<div class="col-sm-12">
<label for="firstName" class="control-label">Finance Contact</label>
</div>
<div class="col-sm-12">
<input type="text" id="finance1" name="finance[]" placeholder="Finance Contact" class="form-control" autofocus>
</div>
</div>
<div class="col-sm-12">
<input type="button" id="more_finance" value="Add More">
</div>
I want This Code insert multiple when click Add More Button And Also remove repeated fields
I Find Answer
jQuery(document).ready(function(){
jQuery('#more_senior').click(function(){
var finance_cont1=jQuery('.senior-contact').length;
var finance_cont=finance_cont1+1;
var add_new ='<div class="form-group senior-contact" id="senior_'+finance_cont+'"><div class="col-sm-9"><label for="firstName" class="control-label">Senior Mgmt. Contact#</label></div><div class="col-sm-9"><input type="text" id="seniormgmt'+finance_cont+'" name="seniormgmt[]"placeholder="Senior Mgmt. Contact" class="form-control" autofocus></div>\n\
Remove</div>';
jQuery(add_new).insertAfter( "#senior_"+finance_cont1 );
delete_fields();
});
function delete_fields(){
$('.delete_png').on("click",function(){
var class_name=jQuery(this).parent().attr('class');
class_name=class_name.split(' ');
var id_name=jQuery(this).parent().attr('id');
var finance_cont2=jQuery('.'+class_name[1]).length;
var finance_cont3=finance_cont2-1;
var id_first=id_name.split('_');
$('#'+id_name).remove();
delete_fields();
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4">
<h4><strong>Senior Mgmt. Contacts</strong></h4>
<div class="form-group senior-contact" id="senior_1">
<div class="col-sm-12">
<label for="firstName" class="control-label">Senior Mgmt. Contact</label>
</div>
<div class="col-sm-12">
<input type="text" id="seniormgmt1" value="" name="seniormgm[]" placeholder="Senior Mgmt. Contact" class="form-control" autofocus>
</div>
</div>
<div class="col-sm-12">
<input type="button" id="more_senior" value="Add More">
</div>
</div>

Unable to dynamically add name attribute to form element

I wish to dynamically add the name attribute as 'pickup_city2' and 'pickup_address2' to select elements with ids, pickup_cityExtend and pickup_addressExtend.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="cityPick form-horizontal form-label-right" action="" method="POST" novalidate>{% csrf_token %}
<div class="form-group">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="city" name="pick_up_city">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="address" name="pick_up_address">
</div>
</div>
</div>
<div class="multiCheck col-md-4 col-sm-4 col-xs-12">
<input type="checkbox" value="Yes" id="multiCheck">Have more than one pickup point?
<br>
</div>
</div>
<div class="form-group hide" id="cityPickExtend">
<div class="city col-md-4 col-sm-4 col-xs-10">
<div class="item form-group">
<label class="control-label" for="city">City<span class="required">*</span>
</label>
<div class="">
<select class="form-control" id="pickup_cityExtend" name="">
<option>Select City</option>
<option>Mumbai</option>
<option>Delhi</option>
<option>Jaipur</option>
</select>
</div>
</div>
</div>
<div class="address col-md-7 col-sm-7 col-xs-10">
<div class="item form-group">
<label class="control-label" for="address">Address<span class="required">*</span>
</label>
<div class="">
<input type="text" class="form-control" id="pickup_addressExtend" name="">
</div>
</div>
</div>
<div class="removeBtn col-md-1 col-sm-1 col-xs-2">
<button type="button" id="removeBtn">Remove</button>
</div>
<div class="addBtn">
<button type="button" id="addBtn">Add another pickup location</button>
</div>
</div>
<div class="item form-group">
<label for="shipment_datetime" class="control-label dateTime">Pickup Date & time
<span class="required">*</span>
</label>
<div class="input-group date form_datetime col-md-4 col-sm-4 col-xs-12" data-date="" data-date-format="dd MM yyyy - HH:ii p" data-link-field="dtp_input1">
<input class="form-control" size="16" name="shipment_datetime" type="text" value="" readonly style="background-color: #fff;">
<span class="input-group-addon">
<span class="glyphicon glyphicon-remove"></span>
</span>
<span class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</span>
</div>
</div>
</form>
Below is my jquery code.
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id').insertAfter($pick);
var city = document.getElementById('pickup_cityExtend');
city.setAttribute('name', 'pickup_city2');
var address = document.getElementById('pickup_addressExtend');
address.setAttribute('name', 'pickup_address2');
}
if (!this.checked) {
$clone.remove();
}
})
Within the part that you clone, there are four elements that have an id attribute. As id values must be unique, the DOM API will always return the first match when you query for a certain id, such as in these lines:
var city = document.getElementById('pickup_cityExtend');
var address = document.getElementById('pickup_addressExtend');
The results do not match the elements in the part you added to the document.
In order to make it work, you need to replace the id values with something that is unique (by adding a 2 for instance).
As a side note: you are mixing jQuery syntax with native DOM methods to retrieve elements. It would be more consistent if you would not use document.getElementById, but the jQuery $('#...') equivalent.
Here is some adjusted code:
var $clone;
$('#multiCheck').change(function() {
if (this.checked) {
var $pick = $('#cityPickExtend');
$clone = $pick.clone().removeClass('hide').removeAttr('id');
// Add '2' to all ID values, and set name value to the same.
$clone.find('[id]').each(function () {
var id = $(this).attr('id') + '2';
$(this).attr('id', id).attr('name', id);
});
// Now that the id value are unique, it is OK to add the clone:
$clone.insertAfter($pick);
} else if ($clone) { // Check whether we actually have a clone
$clone.remove();
}
});

Form.Serialize with checkbox array

I'm submitting a form through JQuery by using the form.serialize method. But that same form has an array of checkboxes, which is dynamically genetrated by a PHP function
This is the form:
<form class="form" id="formNewClient" role="form">
<ul class="nav nav-tabs">
<li class="active"><i class="fa fa-user"></i> Dados Cliente</li>
<li><i class="fa fa-phone"></i> Dados Phonepark</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="clientdata">
<div class="row">
<div class="col-md-12">
<div class="page-header"><h3>Dados Pessoais</h3></div>
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="name">Nome Completo:*</label>
<input type="text" name="clientName" class="form-control" placeholder="Nome Completo do Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="email">Email:</label>
<input type="text" name="clientEmail" class="form-control" placeholder="Email Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-8">
<label for="addressone">Morada:</label>
<input type="text" name="clientAddressone" class="form-control" placeholder="Morada do Utilizador">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="address2">Morada (cont.):</label>
<input type="text" name="clientAddresstwo" class="form-control" placeholder="Morada do Utilizador (cont.)">
</div>
<div class="form-group col-md-3">
<label for="postalcode">Código Postal:</label>
<input type="text" name="clientCPostal" class="form-control" placeholder="Código Postal">
</div>
<div class="form-group col-md-3">
<label for="city">Localidade:</label>
<input type="text" name="clientCity" class="form-control" placeholder="Localidade">
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label for="clientNif">NIF</label>
<input type="text" name="clientNif" class="form-control " placeholder="NIF">
</div>
<div class="form-group col-md-4">
<label for="clientBirthdate">Data de Nascimento</label>
<div class="form-group">
<div class='input-group date' id='inputendDate' data-date-format="YYYY/MM/DD">
<input type='text' name="clientBirthdate" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
<div class="form-group col-md-4">
<label for="sex">Sexo:</label>
<br>
<label class="radio-inline">
<input type="radio" name="optionsRadioSex" value="M">
Masculino
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadioSex" value="F">
Feminino
</label>
</div>
</div>
</div>
<!--END CLIENTDATA-->
<div class="tab-pane" id="phoneparkdata">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h3>Dados Phonepark</h3>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12"><h4>Documentos:</h4></div>
<div class="form-group col-md-4">
<label for="document">Tipo de Documento:</label>
<select name="documenttype" class="form-control">
<?php selectListDocuments();?>
</select>
</div>
<div class="form-group col-md-4">
<label for="documentNumber">Número do Documento:*</label>
<input type="text" name="documentNumber" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="documentNumber">Número do Documento (Secundário):</label>
<input type="text" name="documentNumberSec" class="form-control">
</div>
</div>
<div class="row">
<div class="col-md-12"><h4>Comunicações:</h4></div>
<div class="form-group col-md-4">
<label for="phone1">Telemóvel:*</label>
<input type="text" name="clientPhonePri" class="form-control">
</div>
<div class="form-group col-md-4">
<label for="phone2">Telemóvel Secundário:</label>
<input type="text" name="clientPhoneSec" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<h4>Perfil:</h4>
<label for="profile">Perfil(s) a utilizar:*</label>
<?php
profileCheckBoxes();
?>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="activationDate">Data de Activação:</label>
<div class="form-group">
<div class='input-group date' id='inputactivationDate' data-date-format="YYYY/MM/DD hh:mm">
<input type='text' name="clientActivationTime" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
<div class="form-group col-md-6">
<label for="limitDate">Data de Limite:</label>
<div class="form-group">
<div class='input-group date' id='inputendDate' data-date-format="YYYY/MM/DD hh:mm">
<input type='text' name="clientDeactivationTime" class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</div>
</div>
</div>
</div>
</div>
<!--END PHONEPARKDATA-->
</div>
<!--END TAB-CONTENT-->
<div class="row">
<div class="col-md-4 col-lg-4 pull-right">
<button type="submit" class="btn btn-success" name="submitNewClient" id="submitNewClient"><i class="fa fa-plus"></i> Adicionar Cliente</button>
<button type="button" class="btn btn-danger" data-dismiss="modal"><i class="fa fa-times"></i> Cancelar</button>
</div>
</div>
</form>
And this is the php function that generates the checkboxes:
function profileCheckBoxes(){
$queryListProfiles = "SELECT * FROM perfil";
$listProfiles = mysqli_query($GLOBALS['dbc'],$queryListProfiles);
$numProfiles = mysqli_num_rows($listProfiles);
if($numProfiles !=""){
while($row = mysqli_fetch_array($listProfiles)){
?>
<label class="checkbox-inline">
<input type="checkbox" value="<?php echo $row['id']?>" name="profiles[]">
<?php echo $row['Nome']; ?>
</label>
<?php
}
}
}
How can I submit the form with form.serialize in Jquery and in the PHP side process the checkbox so I can extract the values from the checkbox array?
This jQuery documentation page explains how to use the serialize function:
http://api.jquery.com/serialize/
If you then pass the output to your php page using POST, in the PHP script the checked values will be stored in $_POST['profiles'] as an array. So to loop through the values of the checked boxes you could use:
foreach ($_POST['profiles'] as $profile) {
//process code here
}
jQuery's form.serialize only pass checksboxes that are checked.
if you want all your checkboxes to get passed to your server consider to generate also hidden inputs to store those values.
I would also change the checkboxes name to "profiles"

Categories

Resources