Create unique id in each click of button using Jquery/Javascript - javascript

i want to create unique id in each click of button using Jquery.Actually i am creating file field by clicking on a button here i need first file field's id will remain constant(i.e-fileid) as it is when user will click on a button and the next file field will created the id will change(i.d-fileid1) and so on.I am explaining my code below.
<div class="col-md-6 bannerimagefile bmargindiv1">
<label for="expcerti" accesskey="B"><span class="required">*</span> Publication/Papers Upload your publication/papers certificate.</label>
<ol id="expOl">
<li>
<div class="totalaligndiv">
<div class="col-md-10 padding-zero bannerimagefilenew bmargindiv1">
<input type="file" class="filestyle" data-size="lg" name="expcerti" id="expcerti" />
</div><div class="col-md-2 padding-zero bmargindiv1">
<button type="button" class="btn btn-success btn-sm " id="Expadd">+</button>
<button type="button" class="btn btn-danger btn-sm" id="Expminus" style="display:none;" >-</button>
</div>
<div class="clearfix"></div>
</div>
</li>
</ol>
</div>
<script>
$(document).ready(function () {
$(document).on('click','.btn-success', function () {
// var i=1;
$.getScript("js/bootstrap-filestyle.min.js");
$('#expOl').append("<li><div class='totalaligndiv'><div class='col-md-10 padding-zero bannerimagefilenew bmargindiv1'><input type='file' class='filestyle' data-size='lg' name='expcerti' ></div><div class='col-md-2 padding-zero bmargindiv1'><button type='button' class='btn btn-success btn-sm ' id='Expadd'>+</button><button type='button' class='btn btn-danger btn-sm' id='minus' style='display:none'>-</button></div><div class='clearfix'></div></div></li>");
// $('.filestyle').attr("id","expcerti"+i);
$(this).css('display', 'none');
$(this).siblings("button.btn-danger").css('display', 'block');
// i++;
});
$(document).on('click','.btn-danger', function () {
console.log('delete');
$(this).closest("li").remove();
});
});
</script>
Check my above code first file field's id is expcerti,when one new will be created it should be expcerti1 and like this it will increment .so that if i have 5 filed i can add 5 file in their respective field.But in my case if i have more file field all file is appending one file field. Please help me to resolve this issue.

To generate a new ID on every click maintain a counter flag.
Let's say var i = 1;
Increment this counter on every click i++.
Use this counter variable with id attribute.
Have modified your code snippet as below:
$(document).ready(function () {
var i=1;
$(document).on('click','.btn-success', function () {
$.getScript("js/bootstrap-filestyle.min.js");
$('#expOl').append("<li><div class='totalaligndiv'><div class='col-md-10 padding-zero bannerimagefilenew bmargindiv1'><input type='file' class='filestyle' data-size='lg' name='expcerti' id='expcerti"+i+"' ></div><div class='col-md-2 padding-zero bmargindiv1'><button type='button' class='btn btn-success btn-sm ' id='Expadd'>+</button><button type='button' class='btn btn-danger btn-sm' id='minus' style='display:none'>-</button></div><div class='clearfix'></div></div></li>");
// $('.filestyle').attr("id","expcerti"+i);
$(this).css('display', 'none');
$(this).siblings("button.btn-danger").css('display', 'block');
i++;
});
$(document).on('click','.btn-danger', function () {
console.log('delete');
$(this).closest("li").remove();
});
});

You have to add the click event listener to the newly created buttons.

Related

Remove specific file from the input file list of array in php

I'm doing a multiple image upload with PHP. When doing the preview, I have provided the button to remove the image as well.
My code is as follow :
HTML
<div class="col-md-12 margin-bottom10">
<input type="file" accept="image/*" name="file_name[]" id="file_name" onchange="preview_image()" class="inputfile" multiple />
<?php echo '<div class="margin-bottom10">'.form_error('file_name').'</div>'; ?>
<label class="btn btn-danger" for="file_name"><i class="fa fa-upload"></i> Choose image to upload</label>
<button type="submit" name="submit" class="btn btn-primary">Create</button>
</div>
<div class="col-md-12 margin-bottom10">
<div class="row" id="image_preview">
</div>
</div>
JAVASCRIPT
var newFileList = null;
function preview_image(){
var total_file=document.getElementById("file_name").files.length;
newFileList = Array.from(event.target.files);
for(var i=0;i<total_file;i++){
$('#image_preview').append("<div class='col-md-2 margin-top10 appendedImg'><img style='width: 100%; height: 130px; object-fit: cover;' src='"+URL.createObjectURL(event.target.files[i])+"'><button class='btn btn-block btn-danger margin-top5 btnRemove' value='"+i+"'>Remove</button></div>");
}
}
$(document).on('click', '.btnRemove', function(){
$(this).closest('.appendedImg').remove();
var id = $(this).val();
newFileList.splice(id,1);
});
As what you can see from my code, I've successfully done with the removing a specific file from the list by saving to an array first then only use the splice() to delete.
So, my question is, is it possible to assign the php $_FILES array value with the newFileList array value? Since, the deletion only working on the javascript side so it doesn't affect the list from the file input of php array.
The file list of the input is read only which is how the $_FILES global is set.
See: https://developer.mozilla.org/en-US/docs/Web/API/FileList
However, you could set a hidden element that stores the files that "have been removed" and filter them in PHP on post.
Consider the following example:
When the remove button is used it adds the file name to an array which is covered to a JSON string in a hidden element.
On post, loop through the $_FILES global and if the file name is in the remove list then don't process it.
Of course you'll want to make the uploads less loose and more secure but I hope this gives you the idea.
(I haven't tested this so you may have to adjust.)
HTML
<div class="col-md-12 margin-bottom10">
<input type="file" accept="image/*" name="file_name[]" id="file_name" class="inputfile" multiple />
<label class="btn btn-danger" for="file_name"><i class="fa fa-upload"></i> Choose image to upload</label>
<button type="submit" name="submit" class="btn btn-primary">Create</button>
</div>
<div class="col-md-12 margin-bottom10">
<div class="row" id="image_preview">
</div>
</div>
<input type="hidden" id="removed_files" name="removed_files" value="" />
JavaScript
window.newFileList = [];
$(document).on('click', '.btnRemove', function () {
var remove_element = $(this);
var id = remove_element.val();
remove_element.closest('.appendedImg').remove();
var input = document.getElementById('file_name');
var files = input.files;
if (files.length) {
if (typeof files[id] !== 'undefined') {
window.newFileList.push(files[id].name)
}
}
document.getElementById('removed_files').value = JSON.stringify(window.newFileList);
});
$(document).on('change', '#file_name', function (event) {
var total_file = document.getElementById("file_name").files.length;
for (var i = 0; i < total_file; i++) {
$('#image_preview').append("<div class='col-md-2 margin-top10 appendedImg'><img style='width: 100%; height: 130px; object-fit: cover;' src='" + URL.createObjectURL(event.target.files[i]) + "'><button class='btn btn-block btn-danger margin-top5 btnRemove' value='" + i + "'>Remove</button></div>");
}
});
PHP
<?php
$removedImages = json_decode($_POST['removed_files'], true);
foreach ($_FILES['file_name'] as $FILE) {
if (in_array($FILE['name'], $removedImages)) {
continue;
}
// [import file stuff]
}

How do you pull id data with a JQuery button click?

I can pull data from a modal $('#ID').on('shown.bs.modal', function (e) { var somevariable = e.id; }); doing this method, but can't figure out how to do it with a button click.
If that is possible, how can I also inherit the data if this button click opens the modal?
http://www.bootply.com/jCXXE6chXu
$(document).ready(function(){
$(".file_to_upload").click(function (data) {
//alert("works");
var questionID = data.id;
alert(questionID);
$('[id*="uploaded_files_"]').modal('show');
$('[id*="uploaded_files_"]').on('shown.bs.modal', function (e) {
$("#auditinstanceupload").html("<input id='audit_instance_id' name='audit_instance_id' value='"+questionID+"' type='hidden' style='display:none;'>");
$("#auditidupload").html("<input id='audit_id' name='audit_id' value='"+questionID+"' type='hidden' style='display:none;'>");
});
});
});
<!-- 5 is a php row id for an example -->
<a title="Upload file" href="#" id="5"
class="btn btn-default file_to_upload" >upload button</a>
<!-- modal pop up for [F] button -->
<div class='modal fade' style='z-index:10000' id='uploaded_files_5' role='dialog'>
<div class='modal-dialog modal-lg'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'></button>
<h4 class='modal-title'>Perform Audit</h4>
</div>
<div class='modal-body' id='perform_audit1'>
<form id='my_form' name='form' action='ajax/file_upload.php' method='POST' enctype='multipart/form-data' style=''>
<h1>Upload File</h1>
<div id='main'>
<strong>File: </strong><input name='myFile' id='myFile' size='27' type='file'>
<input id='my_button' name='action' value='Upload' onclick='uploadshow()' type='button'>
<input id='auditinstanceupload' style='display:none;' />
<input id='auditidupload' style='display:none;' />
<input id='question_id' name='question_id' value='$row[questionID]' type='hidden'>
</div>
<!--<input id='close_file_upload' value='Close' type='button'>-->
</form>
</div>
<div class='modal-footer'>
<form method = 'POST'>
<input type='button' id='yes_delete' value='Yes ' name='view_audits_delete' />
<button type='button' class='btn btn-default' data-dismiss='modal'>No</button>
</form>
</div>
</div>
</div>
</div>
<!-- modal pop up for [F] file upload button -->
shown.bs.modal is basically used to execute a function when bootstrap modal is fully open.
If you want to execute a function on click of a button, then you don't need this method. This is for a different purpose. You can use jQuery click() function for that purpose:
$( "#modalButtonId" ).click(function() {
alert( "Handler for .click() called." );
//write other methods here
});
source
try this
$(document).ready(function(){
$(".file_to_upload").click(function (data) {
//alert("works");
//var questionID = data.id;
var questionID = $(this).attr("id");
alert(questionID);
$('[id*="uploaded_files_"]').modal('show');
$('[id*="uploaded_files_"]').on('shown.bs.modal', function (e) {
$("#auditinstanceupload").html("<input id='audit_instance_id' name='audit_instance_id' value='"+questionID+"' type='hidden' style='display:none;'>");
$("#auditidupload").html("<input id='audit_id' name='audit_id' value='"+questionID+"' type='hidden' style='display:none;'>");
});
});
});
var questionID = $(this)[0].id
This worked for me!

Button onClick is not referenced properly and output is not as expected

I am using the variable template and using AddCard function to be called when button is clicked but is not read correctly when I inspect the element.
It looks something like this in Console:
But is should look something like this :
<input type="button" class="btn btn-success btn-xs" onclick="AddCard("CSE101")" value="Add">
Here is the code I have used to get the ID.
var template = " <div class='mycard text-center col-md-2' id ='"+obj.Course+"'> <div class='card-header'> <p1>"+ obj.Course +"</p1> </div> <div class = 'card-block'> <div id = 'svgcontainer"+i+"'> </div> </div> <div class = 'coursename'> <p2> "+obj.CourseName+" </p2> </div> <div class='contact-submit' > <input type='button' class ='btn btn-success btn-xs' onClick = 'AddCard('"+ obj.Course +"')' value='Add' > <input type='button' class ='btn btn-danger btn-xs' onClick = 'SkillVis2();this.disabled=true' value='Play'> </div> <div class='card-footer text-muted'> Prof. XYZ </div> </div>"
function AddCard (corsename)
{
var obj = _.find(data, function(obj){ return obj.Course == corsename; });
SkillVis(obj);
};
Use escape characters to avoid this issue:
onclick="AddCard(\"CSE101\")"
Another possibility is to use single quotes for the parameter:
onclick="AddCard('CSE101')"
For your js-string, the solution would be:
onClick =\"AddCard('" + obj.Course + "')\"
"onClick = 'AddCard("+ obj.Course + ")' "
Shouldn't it be just like that?

How to dynamically Add/Remove file type input field using jquery?

I cannot remove input field dynamically, I can add field but my remove option is not working.
I am using jquery for dynamically add/remove field and bootstrap 3 for my layout.
Here is my markup:
<div class="row margin-bottom">
<div class="col-md-12 col-sm-12">
<button type="submit" class="add-box btn btn-info"><span class="glyphicon glyphicon-plus"></span> Add More Fields</button>
</div>
</div>
<?php $attributes = array('class' => 'form-horizontal', 'role' => 'form'); echo form_open_multipart('config/upload_image', $attributes);?>
<div class="text-box form-group">
<div class="col-sm-4"><input type="file" class="" name="txtImage[]" id="imageinput"/></div>
</div>
<div class="form-group">
<div class="col-sm-2">
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-upload"></span> Upload</button>
</div>
</div>
<?php echo form_close();?>
Here is my jquery code:
$(document).ready(function(){
$('.add-box').click(function(){
var n = $('.text-box').length + 1;
if(n > 5)
{
alert('Only 5 Savy :D');
return false;
}
var box_html = $('<div class="text-box form-group"><div class="col-sm-4"><input type="file" class="" name="txtImage[]" id="imageinput'+ n +'"/></div><div class="col-sm-2"><button type="submit" class="remove-box btn btn-danger btn-sm"><i class="fa fa-minus-circle fa-lg"></i></button></div></div>');
$('.text-box:last').after(box_html);
box_html.slidedown('slow');
});
$('.form-horizontal').on('click', '.remove-box', function(){
$(this).parent().remove();
return false;
});
});
The error is in the remove button click event handler. You need to remove the closest form group rather than the immediate parent:
$('.form-horizontal').on('click', '.remove-box', function(){
$(this).closest(".form-group").remove();
return false;
});
check this bootply for a working example: http://www.bootply.com/x8n3dQ6wDf
EDIT
for animation on remove you can use jQuery slideUp like this:
$('.form-horizontal').on('click', '.remove-box', function(){
var formGroup = $(this).closest(".form-group");
formGroup.slideUp(200, function() {
formGroup.remove();
});
return false;
});

Dynamically appending HTML elements using jQuery not working

I need to build a button menu dynamically using Javascript, but I cannot make it work.
I´m using Bootstrap as base style class.
Here is my code:
<div class="well">
<button type="button" class="btn btn-primary btn-xs">Button 1</button>
<button type="button" class="btn btn-primary btn-xs">Button 2</button>
<button type="button" class="btn btn-primary btn-xs">Button 3</button>
<small class="pull-right">Right Text</small>
</div>
<div id="myMenu">
</div>
<script type="text/javascript">
$(document).ready(function () {
var upperWell = $("<div class='well clearfix'>");
$('myMenu').append(upperWell);
var createButton = $("<button type='button' class='btn btn-primary btn-xs'>Button1</button>");
var updateButton = $("<button type='button' class='btn btn-primary btn-xs'>Button 2</button>");
var exportButton = $("<button type='button' class='btn btn-primary btn-xs'>Button 3</button>");
$(upperWell).append(createButton);
$(upperWell).append(updateButton);
$(upperWell).append(exportButton);
});
</script>
The HTML code is what I need to build using Javascript.
The given Javascript code is not working.
Here is a fiddle that shows the code:
JsFiddle
Help very much appreaciated. Thanks.
You have forgotten the # from the selector.
Should be this.
$('#myMenu').append(upperWell);
Updated: http://jsfiddle.net/P7pTL/2/
Hi Please see here http://jsfiddle.net/hz37q/
$(document).ready(function () {
var upperWell = $("<div class='well clearfix'>");
$('#myMenu').append(upperWell); // <-- you miss hash
var createButton = $("<button type='button' class='btn btn-primary btn-xs'>Button1</button>");
var updateButton = $("<button type='button' class='btn btn-primary btn-xs'>Button 2</button>");
var exportButton = $("<button type='button' class='btn btn-primary btn-xs'>Button 3</button>");
$(upperWell).append(createButton);
$(upperWell).append(updateButton);
$(upperWell).append(exportButton);
});

Categories

Resources