Multiple form upload data is mixing with each other - javascript

I created an image website. I want users to be able to upload images with titles.
var fileCollection = new Array();
$('#images').on('change', function(e) {
var files = e.target.files;
$.each(files, function(i, file) {
fileCollection.push(file);
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
var template = '<form class="upload_form col-md-6 col-xs-12" action="/upload">' +
'<img class="col-md-4 col-xs-4" src="' + e.target.result + '"> ' +
'<input style="width:90px; height:28px" class="col-md-2 col-xs-4" type="number" name="table" id="table" >' +
'<button style="margin:0px 5px 0px 5px; width:95px" class="btn btn-sm btn-primary col-md-3 col-xs-3 submit_form" value="Upload" name="submit_weight">Upload</button>' +
'<button type="button" class="btn btn-sm btn-danger remove_form col-md-2 col-xs-6">Cancel</button>' +
'<div style="height: 30px; font-size: 20px; margin: 0px 0px 10px 0px; padding: 0px; text-align: center;" class="progress col-md-7 col-xs-6 progress-stripped active"><div class="progress-bar" style="font-size: 15px; width:0%"></div></div> ' +
'</form>';
$('#images-to-upload').append(template);
};
});
});
$(document).on('submit', 'form', function(e) {
e.preventDefault();
var index = $(this).index();
var formdata = new FormData($(this)[0]);
$form = $(this);
formdata.append('images', fileCollection[index]);
var request = new XMLHttpRequest();
// progress complete load event
request.open('post', 'script/file_upload_admin.php', true);
request.send(formdata);
});
$("#upload_button").on('click', function(event) {
event.preventDefault();
$(".submit_form").click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1>Image Uploader</h1>
<input type="file" name="images[]" id="images" multiple>
<div id="images-to-upload" class="row"></div>
<div class="col-md-12">
<button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>
</div>
</div>
When a user uploads multiple images the titles are mixed up with each other. For example, image_1 title gets set on image_2 and vice versa. Is there any way I can loop the form so they upload one by one?

Related

What is preventing jQuery .click() function from executing?

This click function was previously working, until i added another button and some php...curious what's preventing it from executing as before, i've checked issues from other questions:
-jquery is properly loaded before the local script
-all functions are wrapped in .ready() [Why is this jQuery click function not working?
I found an interesting post about delegated event handling here: Jquery button click() function is not working
But i don't understand if or why this would apply to my situation...and if it does can someone explain to me its significance?
Javascript:
jQuery ( document ).ready( function ( $ ) {
function initColorPicker0 () {
for ( x=0; x < 4; x++ ) {
var canvasEl0 = document.getElementById('colorCanvas0');
var canvasContext0 = canvasEl0.getContext('2d');
var image0 = new Image(150, 150);
image0.onload = () => canvasContext0.drawImage(image0, 0, 0, image0.width, image0.height);
image0.src = "../img/color-wheel-opt.jpg";
}
canvasEl0.onclick = function ( mouseEvent0 ) {
var imgData0 = canvasContext0.getImageData(mouseEvent0.offsetX, mouseEvent0.offsetY, 1, 1);
var rgba0 = imgData0.data;
var bannerInput = $ ( '#bannerColor' );
bannerInput.val("rgba(" + rgba0[0] + ", " + rgba0[1] + ", " + rgba0[2] + ", " + rgba0[3] + ")" );
}
}
function demoBanner () {
// set click handler
$( '#demo' ).click( function () {
// store input values
var formObject = {
"prompt": document.getElementById('prompt').value,
"c2a" : document.getElementById('c2a').value,
"bannerColor" : document.getElementById('bannerColor').value,
}
//apply input values to style of new content
var newContent = " <div style='height: auto; padding: 15px 0px; margin: 0px -15px; background-color:" + formObject.bannerColor + ";'> <a href='#'> <p style=' margin-top: 0px; margin-bottom: 0px; text-align: center; color:" + formObject.promptTextColor + ";'>"+ formObject.prompt + " <a style='padding: 5px 12px; border-radius: 7px; background-color:" + formObject.c2aBG + "; color:" + formObject.c2aTextColor + " ' href='#'> <em> " + formObject.c2a + " </em> </a> </p> </a> </div>";
//set input as html content of demo
$( 'div.demo' ).html( newContent );
})
}
// called functions
$ ( function () {
initColorPicker0();
demoBanner();
});
});
HTML:
<div id="demo" class="demo"></div>
<div class="container">
<div class="row">
<div class="col-sm-3 text-center">
<div class="form-group">
<br>
<form action="test.php" method="post" name="form">
<label for="prompt">Prompt:
<input class="form-control" name="prompt" id="prompt" type="text">
</label>
<label for="c2a">Call-to-Action:
<input class="form-control" name="c2a" id="c2a" type="text">
</label>
<label for="bannerColor">Banner Background Color:
<input class="form-control" name="bannerColor" id="bannerColor" type="text">
<canvas style="border-radius:50%;" id="colorCanvas0" class="color-canvas" width="150" height="150"></canvas>
</label>
<input id="demo" type="button" class="btn btn-warning" value="Demo Banner">
<br>
<br>
<input id="submit" type="submit" class="btn btn-success" name="submit" value="Submit Form">
</form>
</div>
</div>
</div>
</div>
<!--jquery CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- local JS -->
<script src="http://localhost:8888/vorotech_site/js/banner-tool.js"> </script>
EDIT: $( '#demo' )
First of all, for .click(), it passes an event to the callback. For type="submit", this includes submitting the form. Would advise using .preventDefault().
Here is an example including some jQuery cleanup. Also tried to retain proper object indexes.
$(function() {
function initColorPicker0() {
var canvasEl0, canvasContext0;
for (x = 0; x < 4; x++) {
canvasEl0 = $('#colorCanvas0')[0];
canvasContext0 = canvasEl0.getContext('2d');
var image0 = new Image(150, 150);
image0.onload = () => canvasContext0.drawImage(image0, 0, 0, image0.width, image0.height);
image0.src = "../img/color-wheel-opt.jpg";
}
canvasEl0.onclick = function(mouseEvent0) {
var imgData0 = canvasContext0.getImageData(mouseEvent0.offsetX, mouseEvent0.offsetY, 1, 1);
var rgba0 = imgData0.data;
var bannerInput = $('#bannerColor');
bannerInput.val("rgba(" + rgba0[0] + ", " + rgba0[1] + ", " + rgba0[2] + ", " + rgba0[3] + ")");
};
}
function demoBanner() {
// set click handler
$('#demo').click(function(e) {
e.preventDefault();
// store input values
var formObject = {
prompt: $('#prompt').val(),
c2a: $('#c2a').val(),
bannerColor: $('#bannerColor').val(),
};
//apply input values to style of new content
var newContent = $("<div>").css({
height: "auto",
padding: "15px 0px",
margin: "0px -15px",
"background-color": formObject.bannerColor,
});
$("<a>", {
href: "#"
}).appendTo(newContent);
$("<p>")
.css({
"margin": "0",
"text-align": "center ",
color: formObject.prompt
})
.html(formObject.prompt)
.appendTo($("a", newContent));
$("<a>", {
href: "#"
}).css({
padding: "5px 12px",
"border-radius": "7px",
"background-color": formObject.c2a,
color: formObject.c2a
}).html("<em>" + formObject.c2a + "</em>").appendTo("p", newContent);
//set input as html content of demo
$('div.demo').html(newContent);
});
}
// called functions
initColorPicker0();
demoBanner();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo" class="demo">DEMO</div>
<div class="container">
<div class="row">
<div class="col-sm-3 text-center">
<div class="form-group">
<br>
<form action="test.php" method="post" name="form">
<label for="prompt">Prompt:
<input class="form-control" name="prompt" id="prompt" type="text">
</label>
<label for="c2a">Call-to-Action:
<input class="form-control" name="c2a" id="c2a" type="text">
</label>
<label for="bannerColor">Banner Background Color:
<input class="form-control" name="bannerColor" id="bannerColor" type="text">
<canvas style="border-radius:50%;" id="colorCanvas0" class="color-canvas" width="150" height="150"></canvas>
</label>
<input id="demo" type="button" class="btn btn-warning" value="Demo Banner">
<br>
<br>
<input id="submit" type="submit" class="btn btn-success" name="submit" value="Submit Form">
</form>
</div>
</div>
</div>
</div>

Set input value in form from another Input , dynamically

I trying to upload image to website with its title . I want user to see image before uploading .
HTML
<div class="container">
<h1>Image Uploader</h1>
<input type="file" name="images[]" id="images" multiple>
<br>
<div id="images-to-upload" class="row">
</div>
<br>
<div class="col-md-12">
<button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>
</div>
</div>
When user select some images , Jquery add image with form in DIV .
Jquery
<script>
var fileCollection = new Array();
$('#images').on('change', function(e) {
var files = e.target.files;
$.each(files, function(i, file) {
fileCollection.push(file);
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
var template = '<form enctype="multipart/form-data" class="upload_form col-md-6 col-xs-12" action="/upload">' +
'<img id="img_xx" name="images" class="col-md-4 col-xs-4" src="' + e.target.result + '"> ' +
'<input style="width:90px; height:28px" class="col-md-2 col-xs-4" type="number" name="table" id="table" >' +
'<input style="width:90px; height:28px" class="col-md-2 col-xs-4" type="file" name="images" value="' + e.target.result + '" >' +
'<button style="margin:0px 5px 0px 5px; width:95px" class="btn btn-sm btn-primary col-md-3 col-xs-3 submit_form" value="Upload" name="submit_weight">Upload</button>' +
'<button type="button" class="btn btn-sm btn-danger remove_form col-md-2 col-xs-6">Cancel</button>' +
'<div style="height: 30px; font-size: 20px; margin: 0px 0px 10px 0px; padding: 0px; text-align: center;" class="progress col-md-7 col-xs-6 progress-stripped active"><div class="progress-bar" style="font-size: 15px; width:0%"></div></div> ' +
'</form>';
$('#images-to-upload').append(template);
};
});
});
$(document).on('submit', 'form', function(e) {
e.preventDefault();
var formdata = new FormData(this);
$form = $(this);
var request = new XMLHttpRequest();
request.open('post', 'script/file_upload_admin.php', true);
request.send(formdata);
$form.on('click', '.remove_form', function() {
console.log("Cancel");
alert("hello");
$(this).hide();
});
});
$("#upload_button").on('click', function(event) {
event.preventDefault();
$(".submit_form").click();
});
</script>
My problem is how i set value of input from FileReader , so image can be send in form data . I tried below method but its not working.
$(document).on('submit','form',function(e){
e.preventDefault();
//this form index
var index = $(this).index();
var formdata = new Formdata($(this)[0]); //direct form not object
//append the file relation to index
formdata.append(fileCollection[index]);
var request = new XMLHttpRequest();
request.open('post', 'script/file_upload_admin.php', true);
request.send(formdata);
});
maybe this can help you.
<div class="container">
<h1>Image Uploader</h1>
<input id="fileItem" type="file" name="images[]" id="images" multiple>
<br>
<div id="images-to-upload" class="row">
</div>
<br>
<div class="col-md-12">
<button id="upload_button" class="btn btn-sm btn-success col-md-4 col-xs-12">Upload all images</button>
</div>
</div>
Javascript
$('#upload_button').click(function(){
var files = document.getElementById('fileItem').files;
console.log(files)
$.each(files, function(index, item) {
//console.log(index, item);
console.log(item.name);
// here you can do anything with name of file.
// maybe here you can create your form
});
});
test it jsfiddle

Jquery, image showing after change input

Anyone can show me what is wrong with my code? It show picture after change input but still in first input
It changes only first input everytime
Here is the code
$(document).ready(function() {
function readURL(input, data) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var blah = '#blah' + data;
$(blah).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".active_file").change(function() {
var data = $(this).data('im');
var img_div = '#img_div' + data;
var img_id = '#image_id' + data;
$(img_id).html('<img id="blah' + data + '" src="#" alt="your image" />');
alert(data);
readURL(this, data);
data = data + 1;
$(this).removeClass('active_file');
$(img_div).after('<div class="col-md-2 img_div" id="img_div' + data + '" ><input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im=' + data + '><label class="col-md-12 image " for="fileI" id = "image_id' + data + '"> <i class="fa fa-cloud-upload"></i><br>Nahrať obrázok..</label></div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6 gallery">
<div class="row galeria_row">
<div class="col-md-2 img_div" id="img_div1">
<input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im='1'>
<label class="col-md-12 image " for="fileI" id="image_id1"> <i class="fa fa-cloud-upload"></i>
<br>Nahrať obrázok..</label>
</div>
</div>
</div>
</div>
You need to use delegate event of jQuery because your DOM is being updated in real time.
So instead of doing:
$(".active_file").change(function() {
do this
$(document).on('change', '.active_file', function(){
$(document).ready(function(){
function readURL(input,data) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var blah = '#blah' + data;
$(blah).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).on('change', '.active_file', function(){
var data = $(this).data('im');
var img_div = '#img_div' + data;
var img_id = '#image_id' + data;
$(img_id).html('<img id="blah'+data+'" src="#" alt="your image" />');
alert(data);
readURL(this,data);
data = data + 1;
$(this).removeClass('active_file');
$(img_div).after('<div class="col-md-2 img_div" id="img_div'+data+'" ><input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im='+data+'><label class="col-md-12 image " for="fileI" id = "image_id'+data+'"> <i class="fa fa-cloud-upload"></i><br>Nahrať obrázok..</label></div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-6 gallery">
<div class="row galeria_row">
<div class="col-md-2 img_div" id="img_div1" >
<input form="formid" name="file" type="file" id="fileI" class="inputfile active_file" data-im='1'>
<label class="col-md-12 image " for="fileI" id = "image_id1"> <i class="fa fa-cloud-upload"></i>
<br>Nahrať obrázok..</label>
</div>
</div>
</div>
</div>

Filter rows and show only selected ones on screen

I have populated the table on screen using a csv file. I need to filter this table using comma separated ID values(e.g 1,2,8,34) and show only those rows used in these values on the click of button 'Filter'.
HTML file -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello there</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
<!--<script type="text/javascript" src="JavaScript.js"></script>-->
<script type="text/javascript" src="JavaScript2.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
table {
border-spacing: 5px;
}
.guide {
text-decoration: underline;
text-align: center;
}
.odd {
color: #fff;
background: #666;
}
.even {
color: #666;
}
.hot {
border: 1px solid #f00;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h2>aaaaaaaaaaaaaaaaa</h2>
</div>
<div class="panel panel-primary">
<div class="panel-heading">pppppp</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-sm-offset-1">
<form id="form1" runat="server" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<div class="col-sm-6">
<input type="file" accept=".csv" id="fileUpload" /></div>
<div class="col-sm-6">
<input type="button" id="upload" class="btn btn-primary" value="Upload" /></div>
</div>
<div class="col-sm-7">
<div class="col-sm-2">
<input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" /></div>
<div class="col-sm-2">
<input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" /></div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12">
<center>
<div class="input-append" id="filterDev" style="visibility:hidden">
<input name="search" id="inputFilter" placeholder="Enter ID to filter" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></center>
</div>
<br />
<br />
</div>
<div class="row">
<div class="col-sm-12" id="dvCSV"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12"><p id="download" style="color:cornflowerblue; visibility:hidden"><strong>Please click the below links to download the processed file..</strong></p></div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3"><p id="File1" style="color:cornflowerblue;text-decoration:underline;visibility:hidden">File1 Download</p></div>
<div class="col-sm-3"><p id="File2" style="color:cornflowerblue;text-decoration:underline;visibility:hidden">File2 Download</p></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$("#cancel").on("click", function() {
$('input:checked').each( function() {
$( this ).closest("tr").remove();
});
});
$('#inputFilter').keyup(function () {
var that = this;
$.each($('tr'),
function (i, val) {
if ($(val).text().indexOf($(that).val()) == -1) {
$('#name').animate({
marginTop: 0
},
50,
function () {
$('tr').eq(i).hide();
});
} else {
$('#name').animate({
marginTop: 0
},
50,
function () {
$('tr').eq(i).show();
});
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
</script>
JavaScript2.js
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table id='name'/>");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
$("<td/>").html('<input type="checkbox" id='+cells[0]+'>').appendTo(row);
//alert(cells[0]);
for (var j = 0; j < cells.length; j++) {
$("<td/>").html('<input type="text" disabled value=' +cells[j]+ '>').appendTo(row);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
//document.getElementById("filter").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
Something like this -
EDIT#1
After using the script by #user3273700 , though the filter functionality works but every time the last column of my table shows 'Undefined'. The csv file looks like this -
And the table looks like this -
Modified HTML -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<title>J---</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
<!--<script type="text/javascript" src="JavaScript.js"></script>-->
<script type="text/javascript" src="JavaScript4.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
table {
border-spacing: 5px;
}
.guide {
text-decoration: underline;
text-align: center;
}
.odd {
color: #fff;
background: #666;
}
.even {
color: #666;
}
.hot {
border: 1px solid #f00;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<h2>SAS</h2>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Aa</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12 col-sm-offset-1">
<form id="form1" runat="server" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<div class="col-sm-6">
<input type="file" accept=".csv" id="fileUpload" />
</div>
<div class="col-sm-6">
<input type="button" id="upload" class="btn btn-primary" value="Upload" />
</div>
</div>
<div class="col-sm-7">
<div class="col-sm-2">
<input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" />
</div>
<div class="col-sm-2">
<input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" />
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12">
<center>
<div class="input-append" id="filterDev" style="visibility:hidden">
<input name="search" id="inputFilter" placeholder="Enter ID to filter" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></center>
</div>
<br />
<br />
</div>
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
<p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
</div>
<div class="col-sm-3">
<p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$("#cancel").on("click", function () {
$('input:checked').each(function () {
$(this).closest("tr").remove();
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
document.getElementById("download").style.visibility = "visible";
});
});
$("#filter").click(function () {
ids = $("#inputFilter").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function (i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
</script>
Modified JavaScript4.js -
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
//var table = $("<table id='name'/>");
var lines = e.target.result.split("\n");
var result = [];
var headers = lines[0].split(",");
//alert(headers);
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
populateTable(result);
document.getElementById("cancel").style.visibility = "visible";
document.getElementById("process").style.visibility = "visible";
document.getElementById("filterDev").style.visibility = "visible";
}
reader.readAsText($("#fileUpload")[0].files[0]);
}
}
});
});
$(function () {
$("#process").bind("click", function () {
document.getElementById("File1").style.visibility = "visible";
document.getElementById("File2").style.visibility = "visible";
});
});
function populateTable(finalObject) {
var obj = finalObject;
var table = $("<table id='my-table' />");
table[0].border = "1";
var columns = Object.keys(obj[0]);
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
var headerCell = $("<th />");
headerCell.html([columns[i]]);
row.append(headerCell);
}
$.each(obj, function (i, obj) {
row = '<tr data-id="' + obj.ID + '"><td>' + obj.ID + '</td><td>' + obj.NAME + '</td><td>' + obj.CITY + '</td><td>' + obj.ADDRESS + '</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
You can add a custom attribute (data-id) to each row while you append rows to your table and then use this reference to filter your table.
Try this working sample
$(function() {
var data = [{
id: "1",
name: "Ravi",
city: "Mumbai",
address: "Address1",
designation: "programer"
}, {
id: "2",
name: "Mohit",
city: "Delhi",
address: "Address1",
designation: "Project Manager"
}, {
id: "3",
name: "Mohan",
city: "Mumbai",
address: "Address1",
designation: "CEO"
}, {
id: "4",
name: "John",
city: "Landon",
address: "Address1",
designation: "programer"
}, {
id: "5",
name: "Jane",
city: "Landon",
address: "Address1",
designation: "programer"
}];
//set table header
var headRow = '<tr>';
$.each(data[0], function(attr, val) {
headRow += '<th>' + attr + '</th>'
});
headRow += '</tr>';
$("#my-table").append(headRow);
//add data rows to table
$.each(data, function(i, obj) {
row = '<tr data-id="' + obj.id + '"><td>' + obj.id + '</td><td>' + obj.name + '</td><td>' + obj.city + '</td><td>' + obj.address + '</td><td>' + obj.designation + '</td></tr>';
$("#my-table").append(row);
});
$("#filter-btn").click(function() {
ids = $("#filter-box").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function(i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="filter-box">
<button id="filter-btn">filter</button>
<table id="my-table">
</table>
I hope it will help
You are getting as undefined because it read last column of header row as "ADDRESS\r" (with a carriage return) instead of "ADDRESS". And when you use it to make your array of objects it set a property "ADDRESS\r" instead "ADDRESS".
So you need to remove it from your headers array like this.
var headers = lines[0].split(",").map(function(obj){
return obj.replace(/(?:\\[rn]|[\r\n]+)+/g,'');
});
Here is a working fiddle https://jsfiddle.net/1av8gzo5/

Javascript function: dynamically created div layout issue

http://jsfiddle.net/3Sd4W/
Reference: The above js fiddle provided by greener.
If the new Entry Button is clicked, there is an layout issue for that new added object.
The text box style is:
file.setAttribute("style", "margin-top: 60px;");
But I want the text box to be in the middle and not at the bottom. I tried myself but it doesn't works for me. Anybody could help me to solve this problem?
Your code is extremely complicated to read, so this may help:
HTML:
<form name="addpoll">
<div id="choices">
</div>
<input id="addchoice" type="button" value="Add New Entry">
</form>
JS:
function addnewDiv(counterAppended) {
counterAppended = parseInt(counterAppended) + 1;
var text = document.createElement("div");
text.innerHTML = '<input type="hidden" class="choicecount" name="choicecount" id="choicecount" value="' + counterAppended + '">\
<input type="file" name="choiceimg' + counterAppended + '" value ="Select" onchange="readURL(this)" style="display:none;">\
<div>\
<div style="width:400px;height:85px;">\
<div id="imgbg" style="float:left;width: 110px;height: 80px;text-align: center;border: 1px solid #CCC;">\
<input type="button" onclick="HandFileButtonClick();" value="Browse" id="firstremove" style="margin-top: 30px;" class="addmultiple">\
</div>\
<div style="float:right;margin-top: 30px;">\
<input type=text name="choicename' + counterAppended + '" id="firstremove2">\
<input type="button" value="Remove" class="remove" id="firstremove3" style="color: red; font-size: 12px; border: 0px; background: none; text-decoration: underline;">\
</div>\
</div>\
<img src="#" name="viewimg' + counterAppended + '" class="addmultiple" id="viewimg' + counterAppended + '" height="70px" width="85px" style="display:none"/>\
<br>\
</div>\
<span id="file"></span>';
text.id = 'choice' + counterAppended;
document.getElementById("choices").appendChild(text);
document.getElementsByClassName("remove")[document.getElementsByClassName("remove").length - 1].addEventListener("click", function() {
this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode);
});
}
function HandFileButtonClick() {
document.addpoll.choiceimg1.click();
}
function HandleFileButtonClick(val) {
var ss = val.name;
document.forms["addpoll"]
var n = ss.split("choiceimgs");
document.forms["addpoll"]["choiceimg" + n[1]].click();
}
document.getElementById("addchoice").addEventListener("click", function() {
var choicecounts = document.getElementsByClassName('choicecount');
addnewDiv(choicecounts[choicecounts.length - 1].value);
});
addnewDiv(0);
JsFiddle: http://jsfiddle.net/99vhF/1/
The first row uses a wrapper div for the input field with a style attribute containing float: right. The generated row (after clicking 'add new entry' button) does not have a div wrapper with the same attribute around the input.
You add elements to incorrect nodes. Review you "add" part. All of variables take "file" element. It looks odd:
var addfile = document.getElementById("file");
var view = document.getElementById("file");
var remove1 = document.getElementById("file");
var br2 = document.getElementById("file");
var textf1 = document.getElementById("file");
var myimgdiv = document.getElementById("file");

Categories