Unable to dynamically add name attribute to form element - javascript

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();
}
});

Related

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>

cannot get data from a div

I have problem with getting data from a div tag. This is my div
<div id="log">
<div class="form-group" style="border-bottom:1px solid black;">
<div class="form-group">
<label class="col-sm-2 control-label"> Log Name <sup style="color:red">(*)</sup></label>
<div class="col-sm-2">
<input type="text" class="form-control text banner_value" id="banner_value" />
<div class="help-block with-errors"></div>
</div>
<label class="col-sm-2 control-label"> Start Day <sup style="color:red">(*)</sup></label>
<div class="col-sm-2">
<input type="date" class="form-control text" id="start_day" />
<div class="help-block with-errors"></div>
</div>
<label class="col-sm-2 control-label"> End Day <sup style="color:red">(*)</sup></label>
<div class="col-sm-2">
<input type="date" class="form-control text" id="end_day" />
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Filter Condition <sup style="color:red">(*)</sup></label>
</div>
<div id="banner_input" class="form-group">
<label class="col-sm-2 control-label"> Banner </label>
<div class="col-sm-3">
<input type="text" class="form-control text" id="banner_value" />
<div class="help-block with-errors"></div>
</div>
<div class="col-sm-3">
<input type="checkbox" class="control-label" id="banner_split"> <lable> split </lable><br>
</div>
</div>
<div id="domain_input" class="form-group">
<label class="col-sm-2 control-label"> Domain </label>
<div class="col-sm-3">
<input type="text" class="form-control text" id="domain_value" />
<div class="help-block with-errors"></div>
</div>
<div class="col-sm-3">
<input type="checkbox" class="control-label" id="domain_split"> <lable> split </lable><br>
</div>
</div>
</div>
</div>
and here it's on browser :
after i click Add :
I'm using document.getElementById("log").textContent to get data that i filled to this div, but it didn't work. How can I get my data ??? Please help. Thanks for reading my question.
function getValues() {
var inputs = document.getElementById("log").getElementsByTagName("input");
var values = [];
for (i in inputs) {
values.push(inputs[i].value);
}
console.log(values);
}
<div id="log">
<div class="form-group" style="border-bottom: 1px solid black;">
<div class="form-group">
<label class="col-sm-2 control-label">
Log Name <sup style="color: red;">(*)</sup></label
>
<div class="col-sm-2">
<input
type="text"
class="form-control text banner_value"
id="banner_value"
/>
<div class="help-block with-errors"></div>
</div>
<label class="col-sm-2 control-label">
Start Day <sup style="color: red;">(*)</sup></label
>
<div class="col-sm-2">
<input type="date" class="form-control text" id="start_day" />
<div class="help-block with-errors"></div>
</div>
<label class="col-sm-2 control-label">
End Day <sup style="color: red;">(*)</sup></label
>
<div class="col-sm-2">
<input type="date" class="form-control text" id="end_day" />
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">
Filter Condition <sup style="color: red;">(*)</sup></label
>
</div>
<div id="banner_input" class="form-group">
<label class="col-sm-2 control-label"> Banner </label>
<div class="col-sm-3">
<input type="text" class="form-control text" id="banner_value" />
<div class="help-block with-errors"></div>
</div>
<div class="col-sm-3">
<input type="checkbox" class="control-label" id="banner_split" />
<lable> split </lable><br />
</div>
</div>
<div id="domain_input" class="form-group">
<label class="col-sm-2 control-label"> Domain </label>
<div class="col-sm-3">
<input type="text" class="form-control text" id="domain_value" />
<div class="help-block with-errors"></div>
</div>
<div class="col-sm-3">
<input type="checkbox" class="control-label" id="domain_split" />
<lable> split </lable><br />
</div>
</div>
</div>
</div>
<button onclick="getValues()">click me</button>
var inputs = document.getElementById("log").getElementsByTagName("input");
var values = [];
for (i in inputs) {
values.push(inputs[i].value);
}
console.log(values);
you can use this JS code after click a button
if you want to get data from input tag
function myFunction() {
console.log(document.getElementById("myText").value)
}
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="">
<button onclick="myFunction()">Try it</button>
</body>
</html>
I think what you want to get is the whole information. In that case you need to use the
form
tag instead of div. Div doesn't have a meaning related to data. It is just a container displayed as block.
If You want to get the value of input fields, try to put this in your html:
<script>
const logYourLog = (e) => {
console.log('Here is your value', document.getElementById("banner_value").value);
}
</script>
If you want to get data from the form, and you are using jquery. There is function called serialize() already in there. But, if you are in plain javascript, I guess you should use library for easy purpose. You can also make your own function.
serialize library but I have not tested it. Just check if you get what you need.
You must be able to do sthg like this after you add that library:
var allData = serialize(document.getElementById("log"));
Note:- if allData is not stored, try changing div to form, that should do work.

How to create a JSON based on HTML inputs in 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.

Dynamic multiselect feature

I am creating the fields dynamically in HTML using this JS, and in multiselect I'm using bootstrap multiselect here is the code https://bootsnipp.com/snippets/Ekd8P when I click on the add more button it creates the form dynamically.
js code for creating a form dynamically :
$(function() {
// Remove button
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="remove"]',
function(e) {
e.preventDefault();
$(this).closest('.form-horizontal').remove();
}
);
// Add button
var i = 1;
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-horizontal [data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-horizontal:first-child').clone();
new_field_group.find('input').each(function() {
if (this.name == 'tags[0]') {
$(this).tagsinput('destroy');
$(this).tagsinput('removeAll');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="form-group"]');
new_container.find(".bootstrap-tagsinput:first").remove();
} else {
$(this).val('');
}
});
new_field_group.find('select').each(function() {
if (this.name == 'addons[0]') {
$(this).multiselect('rebuild');
this.name = this.name.replace('[0]', '[' + i + ']');
var new_container = $(this).closest('[class="multiselect-native-select"]');
new_container.find(".multiselect-native-select > .multi").remove();
} else {
$(this).val('');
}
});
i += 1;
container.append(new_field_group);
}
);
});
and html code for form elements:
<form action="" method="post" novalidate="novalidate" enctype="multipart/form-data">
{{ csrf_field() }}
<div data-role="dynamic-fields">
<div class="form-horizontal">
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Name1" name="Name[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Dish Price</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="Price" name="Price[]" required data-rule-minlength="2">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Select Food Type</label>
<div class="col-sm-8">
<select id="select1" class="form-control" name="select[]" required>
#foreach($types as $type)
<option value="{{$loop->iteration}}">{{$type->food_type_name}}</option>
#endforeach
</select>
<p class="help-block" data-toggle="tooltip" data-placement="bottom" title="xyz"><i class="md md-info"></i></p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Dish Description</label>
<div class="col-sm-8">
<textarea name="Description[]" id="field-value" class="form-control" rows="1"></textarea>
</div>
</div>
</div>
<div class="col-sm-4 contacts">
<div class="form-group">
<label class="col-sm-3" for="rolename">Add Addons</label>
<div class="col-sm-8">
<select id="dates-field2" class="multiselect-ak form-control" name="addons[0]" id="trigger3" data-role="multiselect" multiple="multiple">
#foreach($addons as $addon)
<option value="{{$addon->addonid}}">{{$addon->addon_name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label for="Firstname5" class="col-sm-3">Enter Tags</label>
<div class="col-sm-8">
<input type="text" value="" name="tags[0]" class="form-control" data-role="tagsinput" placeholder="e.g. spicy, healthy" />
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="col-sm-4">
<div class="checkbox checkbox-styled">
<label><em>Half Plate Price</em>
<input type="checkbox" value="" class="trigger2" id="trigger2" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields2" class="hidden_fields2" style="display:none;">
<input type="text" id="hidden_field2" name="Price2[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="col-sm-5">
<div class="checkbox checkbox-styled">
<label><em>Quarter Plate Price</em>
<input type="checkbox" value="" class="trigger" id="trigger" name="question">
</label>
</div>
</div>
<div class="col-sm-4">
<div id="hidden_fields" class="hidden_fields" style="display:none;">
<input type="text" id="hidden_field" name="Price3[]" placeholder="Please Enter" class="form-control">
</div>
</div>
</div>
</div>
<br>
<button class="btn btn-delete" data-toggle="tooltip" data-placement="bottom" title="Delete Field" data-role="remove">
Delete Item
</button>
<button class="btn ink-reaction btn-raised btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add More Field" data-role="add">
Add More Items
</button>
</div>
<!-- /div.form-inline -->
</div>
<!-- /div[data-role="dynamic-fields"] -->
<div class="form-group">
<button type="submit" name="submit" href="#" class="btn ink-reaction btn-raised btn-primary" style="margin-top: -62px;margin-left: 160px;">Submit Items</button>
</div>
<!--end .form-group -->
</form>
The issue is that when I click on the add more item it reflects the multiselect dropdown twice as you see in this image.
I want that if I click on the add more item button it restates the multiselect dropdown as in the first state.
see this jsfiddle.net/akshaycic/svv742r7/7 it will clear all your doubt. on click plus button it is not reflect to "none selected" state it will remain in its initial state.
Any leads would be helpful. Thank you in advance.

HTML dynamically add file input not working

For example, I have a section called students
I allow user to add student dynamically
Each student has the fields Name, Points, & Image
The Name & Points works. The problem comes when I add the Image field
See the attachment above, when I try to select the file from 2nd student, the image value goes to the 1st student.
<label for="student-image-1"> was point to the 1st student
<label for="student-image-2"> was point to the 2nd student
And the id for file input was correct.
NOTE: I'm using jQuery.clone to duplicate the div
Any idea why I choose 2nd input will populate to 1st one?
Source code
$('#student-add-more').click(function(e) {
e.preventDefault();
var count = $('div[id^=student-row-]').length;
var last = $('div[id^=student-row-]').last();
var $clone = last.clone(true);
var next_id = count + 1;
$clone.attr('id', 'student-row-' + next_id);
$clone.find('.image-label')
.attr('for', 'student-image-' + next_id)
;
var fileinput = $clone.find('.filestyle')
.attr('id', 'student-image-' + next_id)
.attr('name', 'students_image['+count+']')
;
fileinput.wrap('<form>').closest('form').get(0).reset();
fileinput.unwrap();
$clone.find('.bootstrap-filestyle > label.btn')
.attr('for', 'student-image-' + next_id)
;
$clone.find('.bootstrap-filestyle > input').val('');
var delete_button = $clone.find('.btn-danger')
.attr('data-url', 'student-row-' + next_id)
.attr('href','#deleteModal')
.attr('class', 'btn btn-danger btn-sm btn-delete')
;
delete_button.closest('.form-group').removeAttr('style');
$clone.show().insertAfter(last);
});
html from firebug
<div id="student-row-1">
<div class="form-group ">
<div class="col-lg-3 col-md-3 col-sm-3 control-label">
<span class="badge bg-info student-no">1</span>
<div class="clearfix visible-xs"></div>
<label class="student-label" for="student-1">Name</label> <em class="red">*</em>
</div>
<div class="col-lg-6 col-md-7 col-sm-7">
<input type="text" value="" name="students[0][title]" class="form-control title-control" id="title-1"> </div>
</div>
<div class="form-group">
<div class="col-lg-3 col-md-3 col-sm-3 control-label">
<label class="point-label" for="point-1">Points</label> <em class="red">*</em>
</div>
<div class="col-lg-6 col-md-7 col-sm-7">
<input type="text" value="" name="students[0][point]" class="form-control point-control" id="point-1"> </div>
</div>
<div class="form-group">
<div class="col-lg-3 col-md-3 col-sm-3 control-label">
<label class="image-label" for="student-image-1">Image</label> <em class="red">*</em>
</div>
<div class="col-lg-6 col-md-8 col-sm-8">
<input type="file" name="students_image[0]" data-classinput="form-control inline input-s" data-classbutton="btn btn-default" data-icon="false" class="filestyle" id="student-image-1" style="position: fixed; left: -500px;"><div style="display: inline;" class="bootstrap-filestyle"><input type="text" disabled="" class="form-control inline input-s"> <label class="btn btn-default" for="student-image-1"><span>Choose file</span></label></div> </div>
</div>
<div class="form-group">
<div class="col-lg-3 col-md-3 col-sm-3 control-label"></div>
<div class="col-lg-6 col-md-7 col-sm-7">
<a title="Delete" data-toggle="modal" href="#" class="btn btn-danger btn-sm hidden" data-url="student-row-1">Delete</a>
</div>
</div>
</div>
<div id="student-row-2" style="display: block;">
<div class="form-group ">
<div class="col-lg-3 col-md-3 col-sm-3 control-label">
<span class="badge bg-info student-no">2</span>
<div class="clearfix visible-xs"></div>
<label class="student-label" for="student-1">Name</label> <em class="red">*</em>
</div>
<div class="col-lg-6 col-md-7 col-sm-7">
<input type="text" value="" name="students[1][title]" class="form-control title-control" id="title-2"> </div>
</div>
<div class="form-group">
<div class="col-lg-3 col-md-3 col-sm-3 control-label">
<label class="point-label" for="point-1">Points</label> <em class="red">*</em>
</div>
<div class="col-lg-6 col-md-7 col-sm-7">
<input type="text" value="" name="students[1][point]" class="form-control point-control" id="point-2"> </div>
</div>
<div class="form-group">
<div class="col-lg-3 col-md-3 col-sm-3 control-label">
<label class="image-label" for="student-image-2">Image</label> <em class="red">*</em>
</div>
<div class="col-lg-6 col-md-8 col-sm-8">
<input type="file" name="students_image[1]" data-classinput="form-control inline input-s" data-classbutton="btn btn-default" data-icon="false" class="filestyle" id="student-image-2" style="position: fixed; left: -500px;"><div style="display: inline;" class="bootstrap-filestyle"><input type="text" disabled="" class="form-control inline input-s"> <label class="btn btn-default" for="student-image-2"><span>Choose file</span></label></div> </div>
</div>
<div class="form-group">
<div class="col-lg-3 col-md-3 col-sm-3 control-label"></div>
<div class="col-lg-6 col-md-7 col-sm-7">
<a title="Delete" data-toggle="modal" href="#deleteModal" class="btn btn-danger btn-sm btn-delete" data-url="student-row-2">Delete</a>
</div>
</div>
</div>
Finally solved the problem, I just realized that the file input was using Bootstrap Filestyle.
// file
var file_container = $clone.find('.filestyle').parent();
file_container.empty();
var fileinput = $('<input>').addClass('filestyle').attr({
id: 'student-image-'+next_id,
name: 'students_image['+count+']',
type: 'file',
});
file_container.append(fileinput);
fileinput.filestyle({
icon: 'false',
classButton: 'btn btn-default',
classInput: 'form-control inline input-s',
});
var file_label_container = file_container.prev();
var new_label = $('<label>').addClass('image-label').attr('for', 'student-image-'+next_id).text(file_label_container.find('label').text());
file_label_container.find('label').remove();
file_label_container.prepend(new_label);
I remove the original input, and recreate a plain input, then use the filestyle to style the file input and append to the container. As well as the label on left hand side.

Categories

Resources