Image preview not working in Dynamic Add / Remove file upload fields - javascript

I have created Dynamic Add / Remove fields... Along with other fields there is an Image file field... Every thing is working well except the image preview.
The preview of first field is working well, but in other added fields the preview is not working...
I m not getting, where I m wrong... Plz help me... Thanks...
Following is my Code:
<div class="card">
<div class="card-header text-center">
<b>Team Members</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-4">
<img src="<?php echo esc_url( site_url('/wp-content/img/blank-image.png') ); ?>" class="img-thumbnail" id="output_member0">
<br><br>
<label class="btn btn-success btn-block btn-file">Select Image<input type="file" name="member_image[]" onchange="preview_member(event, 0)" style="display: none;"></label>
</div>
<div class="col-8">
<div class="form-group">
<label for="member_name"><b>Member Name</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_name[]">
</div>
<div class="form-group">
<label for="member_email"><b>Email Address</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_email[]">
</div>
<div class="form-group">
<label for="member_role"><b>Role in Project</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_role[]">
</div>
<div class="form-group">
<label for="member_fb"><b>Facebook Username</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_fb[]">
</div>
</div>
</div>
<div id="team-member-fields">
</div>
<button type="button" class="btn btn-success btn-block" id="add-member-fields">Add Member</button>
</div>
</div>
<script type="text/javascript">
var i = 0;
function preview_member(event, inp) {
var reader = new FileReader();
console.log(inp);
reader.onload = function() {
var output = document.getElementById("output_member" + inp);
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
}
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on("click", "#remove-member-fields", function(event) {
event.preventDefault();
$(this)
.parent()
.fadeOut(300, function() {
$(this).empty();
return false;
});
});
//add input
$("#add-member-fields").click(function() {
i++;
var rows = '<div class="member-fields"><div class="row"><div class="col-4"><img src="<?php echo esc_url( site_url('/wp-content/img/blank-image.png') ); ?>" class="img-thumbnail" id="output_member${i}"><br><br><label class="btn btn-success btn-block btn-file">Select Image<input type="file" name="member_image[]" onchange="preview_member(event, ${i})" style="display: none;"></label></div><div class="col-8"><div class="form-group"><label for="member_name"><b>Member Name</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_name[]"></div><div class="form-group"><label for="member_email"><b>Email Address</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_email[]"></div><div class="form-group"><label for="member_role"><b>Role in Project</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_role[]"></div><div class="form-group"><label for="member_fb"><b>Facebook Username</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_fb[]"></div></div></div><button type="button" class="btn btn-danger btn-block" id="remove-member-fields">Remove Member</button></div>';
$(rows)
.fadeIn("slow")
.appendTo("#team-member-fields");
return false;
});
});
</script>

Your rows variable is a bit mixed up with string literals and single quotation marks.
If you want to output a string like ${variablename} you have to put backticks around that string. (see Template literals)
Check the follwing snippet (just surrounded the row string with backticks).
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Team Members</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-4">
<img src="<?php echo esc_url( site_url('/wp-content/img/blank-image.png') ); ?>" class="img-thumbnail" id="output_member0">
<br><br>
<label class="btn btn-success btn-block btn-file">Select Image<input type="file" name="member_image[]" onchange="preview_member(event, 0)" style="display: none;"></label>
</div>
<div class="col-8">
<div class="form-group">
<label for="member_name"><b>Member Name</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_name[]">
</div>
<div class="form-group">
<label for="member_email"><b>Email Address</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_email[]">
</div>
<div class="form-group">
<label for="member_role"><b>Role in Project</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_role[]">
</div>
<div class="form-group">
<label for="member_fb"><b>Facebook Username</b> <b style="color:#FF0000;">*</b></label>
<input type="text" class="form-control" name="member_fb[]">
</div>
</div>
</div>
<div id="team-member-fields">
</div>
<button type="button" class="btn btn-success btn-block" id="add-member-fields">Add Member</button>
</div>
</div>
<script type="text/javascript">
var i = 0;
function preview_member(event, inp) {
var reader = new FileReader();
console.log(inp);
reader.onload = function() {
var output = document.getElementById("output_member" + inp);
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
}
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on("click", "#remove-member-fields", function(event) {
event.preventDefault();
$(this)
.parent()
.fadeOut(300, function() {
$(this).empty();
return false;
});
});
//add input
$("#add-member-fields").click(function() {
i++;
var rows = `<div class="member-fields"><div class="row"><div class="col-4"><img src="<?php echo esc_url( site_url('/wp-content/img/blank-image.png') ); ?>" class="img-thumbnail" id="output_member${i}"><br><br><label class="btn btn-success btn-block btn-file">Select Image<input type="file" name="member_image[]" onchange="preview_member(event, ${i})" style="display: none;"></label></div><div class="col-8"><div class="form-group"><label for="member_name"><b>Member Name</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_name[]"></div><div class="form-group"><label for="member_email"><b>Email Address</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_email[]"></div><div class="form-group"><label for="member_role"><b>Role in Project</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_role[]"></div><div class="form-group"><label for="member_fb"><b>Facebook Username</b> <b style="color:#FF0000;">*</b></label><input type="text" class="form-control" name="member_fb[]"></div></div></div><button type="button" class="btn btn-danger btn-block" id="remove-member-fields">Remove Member</button></div>`;
$(rows)
.fadeIn("slow")
.appendTo("#team-member-fields");
return false;
});
});
</script>

Related

i have problem with my javascript on codeigniter, parse to javascript

i have some problem, i want to push my data to form html with javascript obj but it can't push with id
this is my javascript
{if {form_case} == ubah}
<script type="text/javascript">
var data={data_by_id};
for (var obj in data)
{
alert(data[obj]);
$("#" + obj).val(data[obj]);
}
</script> {/if}
this my form html
<form class="form" form-case="{form_case}">
<div class="form-group">
<label for="Nama">Nama</label>
<input type="text" class=" riset form-control" id="nama_user" name="nama_user" placeholder="">
<div>
<?php print form_error('nama_user', '<small class="text-danger">', '</small>') ?>
</div>
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" id="username" name="username">
<div>
<?php print form_error('username', '<small class="text-danger">', '</small>') ?>
</div>
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" id="password" name="password">
<div>
<?php print form_error('password', '<small class="text-danger">', '</small>') ?>
</div>
</div>
<div class="form-group">
<div class="float-right">
<button class="btn btn-sm btn-primary" name="simpan" data-link="{base_url}/{lvl_auth}/{base_class}/store">Simpan</button>
<button type="reset" class="btn btn-sm btn-success" name="reset">Reset</button>
</div>
</div>
</form>
this my result in inspect element
enter image description here
then this ini my result on html it can't show the value in field
enter image description here

Pass javascript variable to appended row in Dynamic form

I am working with dynamic form.
I want to pass javascript value to append row. Here how can I pass uid value to appended row. I tried <?php echo $uid = "<script>document.write(uid)</script>"; ?> in append row.
Bbut it is not working.
Here is my code
default row
<div class="form-group row">
<?php $uid = '1';?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="<?php echo $uid;?>">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-info btn-sm" id="btnAddMoreSpecification" data-original-title="Add More">
<i class="fa fa-plus"></i>
</a>
</div>
</div>
<div id="divSpecificatiion">
</div>
Append row
<script type="text/template" id="temSpecification">
<div class="form-group row" style="padding-top:10px;">
<?php $uid =''; ?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="<?php echo $uid;?>">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-danger btn-sm btnRemoveMoreSpecification" data-original-title="Add More">
<i class="fa fa-times"></i>
</a>
</div>
</div>
</script>
$(document).ready(function (event) {
uid=1;uvd=2;$('#btnAddMoreSpecification').click(function ()
{$('#divSpecificatiion').append($('#temSpecification').html());uid++;uvd++; });
$(document).on('click', '.btnRemoveMoreSpecification', function () {
$(this).parent('div').parent('div').remove();
});
});
Output should be like this
Use something like this:
$(document).ready(function(event) {
uid = 1;
uvd = 2;
$('#btnAddMoreSpecification').click(function() {
uid++;
var templateHtml = $('#temSpecification').html();//save the html in a variable
var temp = $(templateHtml).find('input[type="text"]').val(uid).end();//find the input and append the new uid
$('#divSpecificatiion').append(temp);//append the new html to the div
});
$(document).on('click', '.btnRemoveMoreSpecification', function() {
$(this).parent('div').parent('div').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<?php $uid = '1';?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="<?php echo $uid;?>">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-info btn-sm" id="btnAddMoreSpecification" data-original-title="Add More">Add more
<i class="fa fa-plus"></i>
</a>
</div>
</div>
<div id="divSpecificatiion">
</div>
<script type="text/template" id="temSpecification">
<div class="form-group row" style="padding-top:10px;">
<?php $uid =''; ?>
<label for="name" class="col-sm-1 form-control-label">Item</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="" id="inputc" value="">
</div>
<div class="box-tools">
<a href="javascript:void(0);" class="btn btn-danger btn-sm btnRemoveMoreSpecification" data-original-title="Add More">
<i class="fa fa-times"></i>
</a>
</div>
</div>
</script>

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.

how can i validate the checkbox?

<form target="_self" id="immunization_info_form" class="form-validation save_immune25 update_immune25" role="form" method="POST" enctype="multipart/form-data">
<div class="form-group row" style="margin-top:10px;height:50px;">
<div class="checkbox checkbox-styled col-md-offset-1 col-md-4">
<label style="font-size:15px;"><input type="checkbox" id="checkbox25" name="ch" class="checkbx" value="25">
<span>Hepatitis A vaccine</span></label>
</div>
<div class="form-group col-md-4">
<!-- Date input -->
<input class="form-control edit25" id="date25" name="date" placeholder="Enter Date" value="<?php echo $date[25]; ?>" type="text" required>
</div>
</div>
<div class="row" style="padding:15px;">
<div class="col-md-3 col-md-offset-1">
<div class="form-group">
<h3 style="color:orange;">Clinic Name</h3><br>
<input name="clinic_name" id="clinic" class="form-control edit25" type="text" value="<?php echo $clinic_name[25]; ?>" required>
<label for="clinic_name"></label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<h3 style="color:orange;">Name of the Health practitioner</h3><br>
<input name="hp_name" id="hp" class="form-control edit25" type="text" value="<?php echo $practitioner[25]; ?>" required>
<label for="hp_name"></label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<h3 style="color:orange;">Lot no. of Vaccine</h3><br>
<input name="lotno" id="lot" class="form-control edit25" type="text" value="<?php echo $lotno[25]; ?>" required>
<label for="lotno"></label>
</div>
</div>
<div class="row col-md-offset-1">
<div class="col-md-6 text-right">
<input type="button" name="submit" value="SAVE" class="save btn btn-lg btn-primary ink-reaction justify" id="save_immune25">
</div>
</div>
</div>
</form>
i have added my html code also..
$('.save').on('click', function() {
var chk = $(this).parent().parent().parent().parent().parent().find('input [name="ch"]').attr('class');
if ($("." + chk).attr('checked', false)) {
alert("please check the checkbox");
} else {
alert("you have checked the checkbox");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i have tried with this code and getting the alert "please check the checkbox" for both conditions if and else.
i just want to validate the checkbox whether it is checked or not .. if checked means it should display the relevant message if not checked also should display the message.
There are two things i am noticing:
Instead use .closest() against .parent() multiple times.
Do not set the attribute in the if condition, instead of .attr() use .prop().
You can change to this
var chk = $(this).closest('form').find('input[name="ch"]');// use form if you have one.
if (!$(chk).prop('checked')) {
$('.save').on('click', function() {
var chk = $(this).closest('form').find('input[name="ch"]');
if (!$(chk).prop('checked')) {
alert("please check the checkbox");
} else {
alert("you have checked the checkbox");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form target="_self" id="immunization_info_form" class="form-validation save_immune25 update_immune25" role="form" method="POST" enctype="multipart/form-data">
<div class="form-group row" style="margin-top:10px;height:50px;">
<div class="checkbox checkbox-styled col-md-offset-1 col-md-4">
<label style="font-size:15px;"><input type="checkbox" id="checkbox25" name="ch" class="checkbx" value="25">
<span>Hepatitis A vaccine</span></label>
</div>
<div class="form-group col-md-4">
<!-- Date input -->
<input class="form-control edit25" id="date25" name="date" placeholder="Enter Date" value="<?php echo $date[25]; ?>" type="text" required>
</div>
</div>
<div class="row" style="padding:15px;">
<div class="col-md-3 col-md-offset-1">
<div class="form-group">
<h3 style="color:orange;">Clinic Name</h3><br>
<input name="clinic_name" id="clinic" class="form-control edit25" type="text" value="<?php echo $clinic_name[25]; ?>" required>
<label for="clinic_name"></label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<h3 style="color:orange;">Name of the Health practitioner</h3><br>
<input name="hp_name" id="hp" class="form-control edit25" type="text" value="<?php echo $practitioner[25]; ?>" required>
<label for="hp_name"></label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<h3 style="color:orange;">Lot no. of Vaccine</h3><br>
<input name="lotno" id="lot" class="form-control edit25" type="text" value="<?php echo $lotno[25]; ?>" required>
<label for="lotno"></label>
</div>
</div>
<div class="row col-md-offset-1">
<div class="col-md-6 text-right">
<input type="button" name="submit" value="SAVE" class="save btn btn-lg btn-primary ink-reaction justify" id="save_immune25">
</div>
</div>
</div>
</form>

Convert mutlidimensional inputs to JavaScript object

I've been trying to solve this one for several days now and it's driving me nuts. I have some data that needs to be submitted by Ajax. It is dynamic, so I don't know how many fields it has. On top of that the names of the fields are multidimensional and also dynamic. For example one might have inputs with the name data[name] and data[title] whilst another larger one might have data[images][0][src], data[images][0][alt], data[images][0][description], data[images][1][src], data[images][1][alt], data[images][1][description] with an unknown number of elements to the array. My problem is that I need to get an object I can submit via Ajax whilst maintaining the structure of the data.
I've tried serialising the data, but that just comes up with a string of name = value. I've tried serialise array as well, but that just gives me an array of [name, value]. I've managed to generate the object manually using a regex to split it up, but I can't find a way to merge the resultant objects together. The latest version of my code is:
$('.modal-content').find('input[name^="data"]').each(function () {
var found = $(this).attr('name').match(re).reverse();
var temp = $(this).val();
$.each(found, function ()
{
str = this.substr(1, this.length - 2);
var t = {};
t[str] = temp;
temp = t;
});
data = $.each({}, data, temp);
});
Unfortunately it doesn't merge them, it overwrites what is in data with what is in temp. If data has data.images[0].src = "mysrc" and temp has data.images[0].alt = "myalt" then I just end up with data.images[0].alt = "myalt" and src is no longer there.
There has to be a simple way to do this, hell at this point I'd even take a complicated way to do this. Can someone please help me with this?
Although there is already an accepted answer. Here are my 5 cents:
IMHO working with regex should be avoided when possible. So my suggestion would be to change the HTML a bit, adding some classes to the div that contain the image and change the name attribute of the inputs:
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div class="my-image">
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="src" value="img/example.jpg">
<div class="form-group">
<label for="title-0">Title:</label>
<input type="text" name="title" class="form-control" id="title-0" value="Default Example Image 1" placeholder="Title">
</div>
<div class="form-group">
<label for="description-0">Description:</label>
<input type="text" name="description" class="form-control" id="description-0" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-0">Alt tag (SEO):</label>
<input type="text" name="alt" class="form-control" id="alt-0" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-0">Order:</label>
<input type="number" name="order" class="form-control image-order" id="order-0" value="0">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div class="my-image">
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="src" value="img/example.jpg">
<div class="form-group">
<label for="title-1">Title:</label>
<input type="text" name="title" class="form-control" id="title-1" value="Default Example Image 2" placeholder="Title">
</div>
<div class="form-group">
<label for="description-1">Description:</label>
<input type="text" name="description" class="form-control" id="description-1" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-1">Alt tag (SEO):</label>
<input type="text" name="alt" class="form-control" id="alt-1" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-1">Order:</label>
<input type="number" name="order" class="form-control image-order" id="order-1" value="1">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
Then build the object matching this class:
var obj = {
data: {
images: []
}
}
var groups = $('.my-image');
groups.each(function(idx, el) {
var child = {}
$(el).find('input').each(function(jdx, info){
var $info = $(info);
child[$info.attr('name')] = $info.val();
});
obj.data.images.push(child);
});
We would have the same result, but it might be less error prone. Here is a plunker.
You can loop all inputs with each() loop, create array from name attributes using split() and then use reduce to add to object
var result = {}
$('input').each(function() {
var name = $(this).attr('name');
var val = $(this).val();
var ar = name.split(/\[(.*?)\]/gi).filter(e => e != '');
ar.reduce(function(a, b, i) {
return (i != (ar.length - 1)) ? a[b] || (a[b] = {}) : a[b] = val;
}, result)
})
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="gallery-images" class="ui-sortable">
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="data[images][0][src]" value="img/example.jpg">
<div class="form-group">
<label for="title-0">Title:</label>
<input type="text" name="data[images][0][title]" class="form-control" id="title-0" value="Default Example Image 1" placeholder="Title">
</div>
<div class="form-group">
<label for="description-0">Description:</label>
<input type="text" name="data[images][0][description]" class="form-control" id="description-0" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-0">Alt tag (SEO):</label>
<input type="text" name="data[images][0][alt]" class="form-control" id="alt-0" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-0">Order:</label>
<input type="number" name="data[images][0][order]" class="form-control image-order" id="order-0" value="0">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/img/example.jpg">
<input type="hidden" name="data[images][1][src]" value="img/example.jpg">
<div class="form-group">
<label for="title-1">Title:</label>
<input type="text" name="data[images][1][title]" class="form-control" id="title-1" value="Default Example Image 2" placeholder="Title">
</div>
<div class="form-group">
<label for="description-1">Description:</label>
<input type="text" name="data[images][1][description]" class="form-control" id="description-1" value="A default example image." placeholder="Description">
</div>
<div class="form-group">
<label for="alt-1">Alt tag (SEO):</label>
<input type="text" name="data[images][1][alt]" class="form-control" id="alt-1" value="fluid gallery example image" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-1">Order:</label>
<input type="number" name="data[images][1][order]" class="form-control image-order" id="order-1" value="1">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/uploads/galleries\21\4-tux-30.jpg">
<input type="hidden" name="data[images][2][src]" value="uploads/galleries\21\4-tux-30.jpg">
<div class="form-group">
<label for="title-2">Title:</label>
<input type="text" name="data[images][2][title]" class="form-control" id="title-2" value="" placeholder="Title">
</div>
<div class="form-group">
<label for="description-2">Description:</label>
<input type="text" name="data[images][2][description]" class="form-control" id="description-2" value="" placeholder="Description">
</div>
<div class="form-group">
<label for="alt-2">Alt tag (SEO):</label>
<input type="text" name="data[images][2][alt]" class="form-control" id="alt-2" value="" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-2">Order:</label>
<input type="number" name="data[images][2][order]" class="form-control image-order" id="order-2" value="2">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-3 gallery-image ui-sortable-handle">
<div>
<img src="http://localhost:8000/uploads/galleries\21\all-free-backgrounds-simple-style-darkblue-18.jpg">
<input type="hidden" name="data[images][3][src]" value="uploads/galleries\21\all-free-backgrounds-simple-style-darkblue-18.jpg">
<div class="form-group">
<label for="title-3">Title:</label>
<input type="text" name="data[images][3][title]" class="form-control" id="title-3" value="" placeholder="Title">
</div>
<div class="form-group">
<label for="description-3">Description:</label>
<input type="text" name="data[images][3][description]" class="form-control" id="description-3" value="" placeholder="Description">
</div>
<div class="form-group">
<label for="alt-3">Alt tag (SEO):</label>
<input type="text" name="data[images][3][alt]" class="form-control" id="alt-3" value="" placeholder="Alt tag">
</div>
<div class="form-group">
<label for="order-3">Order:</label>
<input type="number" name="data[images][3][order]" class="form-control image-order" id="order-3" value="3">
</div>
<button type="button" class="btn btn-danger remove-gallery-image-btn">× Delete</button>
</div>
</li>
</ul>

Categories

Resources