Having issue when i am using fileupload object to show the files while before upload in the modal
Even Try make a shallow copy of DOM object to use it but it still not working
Kindly Give me a possible solution for this problem
HTML and javascript Kindly see the FileConfigHandler Method
<div id="filedata"></div>
<div class="col-md-9">
<div class="homepage_contant">
<div class="container">
<!-- Start File Upload Section -->
<h4>File Upload</h4>
<form id="drag-and-drop-zone" class="upload_container" action="/Home/Upload" method="POST" enctype="multipart/form-data" ondrop="dropHandler(event);">
<div class="text-center">
<img class="cloud_upload_img" src="~/Content/images/cloud.png" />
<p>Drag & Drop Files Here or <span class="browse_btn_holder">Browse <input class="browse_btn" type="file" accept=".xls..xlsx image/* " multiple id="mfile" name="mfile" title='Click to add Files' /> </span> to upload files</p>
</div>
<!-- Modal -->
<div class="upload_file_modal modal" id="uploadFileModal" tabindex="-1" role="dialog" aria-labelledby="uploadFileModal" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">File Upload</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<ul class="list-unstyled p-2 d-flex flex-column col" style="padding:0 !important" id="files">
<li class="text-muted text-center empty"><p id="txt"> Files has been seleted. </p></li>
</ul>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="upload_field_wrap">
<label for="ItemTitle"> File Title</label>
<input type="text" class="form-control" id="title" name="title" />
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
#Html.DropDownList("Department", ViewBag.lst as SelectList, "Select Department", new { #class = "form-control" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select class="form-control" id="CourseId" name="CourseId">
<option value="" disabled selected>Course</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select class="form-control" id="category" name="category">
<option value="" disabled selected>Select Category</option>
<option value="mid">
Mid Term
</option>
<option value="final">
Final
</option>
<option value="quiz">
Quiz
</option>
<option value="summary">
Summary
</option>
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="upload_field_wrap">
<select id="yearOfPublish" name="yearOfPublish" class="form-control">
<option value="" disabled> Select Year</option>
#for (int i = 2000; i < 2020; i++)
{
<option value="#i">#i</option>
}
</select>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="upload_field_wrap">
<label for="description">Description</label>
<textarea class="form-control" id="" rows="3"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
<!-- End File Upload Section -->
#section scripts
{
<script src="~/Scripts/jquery.dm-uploader.min.js"></script>
<script src="~/Scripts/upload_file_ui.js"></script>
<script>
function dropHandler(event) {
event.preventDefault();
mfile.files = event.dataTransfer.files;
console.log(mfile);
//ChangeImageHandler();
FileConfigHandler();
}
function formatBytes(bytes, decimals) {
if (bytes == 0) return '0 Bytes';
var k = 1024,
dm = decimals <= 0 ? 0 : decimals || 2,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function ChangeImageHandler()
{
var x = $('#mfile').val();
let file = $('#mfile')[0].files[0];
var size = $('#mfile')[0].size;
var sizeWithTag = formatBytes(size);
$('#item_size').text(sizeWithTag);
$('#item_title').text(file.name);
if (x.split('.').pop()=='pdf') {
$("#item_type_img").attr("src", "../../Content/images/files_types/pdf.png");
}
else if (x.split('.').pop() == 'docx') {
$("#item_type_img").attr("src", "../../Content/images/files_types/doc.png");
}
else if (x.split('.').pop() == 'jpg') {
$("#item_type_img").attr("src", "../../Content/images/files_types/jpg.png");
}
else if (x.split('.').pop() == 'png') {
$("#item_type_img").attr("src", "../../Content/images/files_types/png.png");
}
else if (x.split('.').pop() == 'ppt') {
$("#item_type_img").attr("src", "../../Content/images/files_types/ppt.png");
}
else if (x.split('.').pop() == 'txt') {
$("#item_type_img").attr("src", "../../Content/images/files_types/txt.png");
}
else if (x.split('.').pop() == 'xls') {
$("#item_type_img").attr("src", "../../Content/images/files_types/xls.png");
}
else if (x.split('.').pop() == 'csv') {
$("#item_type_img").attr("src", "../../Content/images/files_types/csv.png");
}
console.log();
}
function FileConfigHandler()
{
console.log('chal raha h')
var files1 = mfile.files;
console.log(mfile.files);
for (var i = 0; i < files1.length; i++) {
// console.log(files1[i]);
//var x= AddChild(files1[i]);
$('#files').append(x);
}
}
function AddChild(item)
{
var template = $('#files-template').html();
var parent = $(template);
var extention = item.name.split('.').pop();
// console.log(item.name.split('.').pop());
var name = item.name;
var temp_size = item.size;
var size = formatBytes(temp_size);
parent.find('#item_size').text(size)
parent.find('#item_title').text(name)
if (extention == 'pdf') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/pdf.png");
}
else if (extention == 'docx') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/doc.png");
}
else if (extention == 'jpg') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/jpg.png");
}
else if (extention == 'png') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/png.png");
}
else if (extention == 'ppt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/ppt.png");
}
else if (extention == 'txt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/txt.png");
}
else if (extention == 'xls') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/xls.png");
}
else if (extention == 'csv') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/csv.png");
}
return '<li class="uploaded_item">' + parent.html() + '</li>'
}
//function dropHandler(ev) {
// console.log('File(s) dropped');
// // Prevent default behavior (Prevent file from being opened)
// ev.preventDefault();
// var file = ev.dataTransfer.files;
// // var file = e.originalEvent.dataTransfer.files;
// var fileData = new FormData();
// for (var i = 0; i < file.length; i++) {
// fileData.append("fileData", ev.dataTransfer.files[i]);
// }
//if (ev.dataTransfer.items) {
// // Use DataTransferItemList interface to access the file(s)
// for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// // If dropped items aren't files, reject them
// if (ev.dataTransfer.items[i].kind === 'file') {
// file[i] = ev.dataTransfer.items[i].getAsFile();
// fileData.append("fileData",ev.dataTransfer.files[i]);
// console.log('... file[' + i + '].name = ' + file.name);
// }
// }
//} else {
// // Use DataTransfer interface to access the file(s)
// for (var i = 0; i < ev.dataTransfer.files.length; i++) {
// fileData.append("fileData", ev.dataTransfer.files[i]);
// console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name);
// }
//}
// $.ajax({
// type: "POST",
// dataType: "json",
// enctype: 'multipart/form-data',
// url:'/Home/SendFile',
// contentType: false, // Not to set any content header
// processData: false, // Not to process data
// data: fileData,
// success: function (result, status, xhr) {
// alert(result);
// },
// error: function (xhr, status, error) {
// alert(status);
// }
// })
//}
$(document).ready(function () {
$('#uploadFileModal').hide();
$('#drag-and-drop-zone').dmUploader({
onDragEnter: function () {
// Happens when dragging something over the DnD area
this.addClass('active');
$('.upload_container .cloud_upload_img').addClass('animated infinite shake')
},
onDragLeave: function (e) {
// Happens when dragging something OUT of the DnD area
this.removeClass('active');
$('.upload_container .cloud_upload_img').removeClass('animated infinite shake');
//readmultifiles(document.getElementById('#file'));
$('#uploadFileModal').modal("show");
}})
})
$('#mfile').change(function () {
console.log(mfile.files);
$('#uploadFileModal').modal("show");
//document.getElementById("#txt").innerHTML = "1 file has been Selected";
// console.log(mfile.files);
//ChangeImageHandler();
FileConfigHandler();
});
$("#Department").change(function () {
LoadDepartments();
});
function LoadDepartments() {
var collegeId = document.getElementById("Department");
var ID = collegeId.options[collegeId.selectedIndex].value;
var depatments = document.getElementById("CourseId");
console.log(ID);
$.ajax({
url: '#Url.Action("getCourses", "Home")',
type: 'GET',
dataType: "json",
data: { idString: ID },
success: function (result) {
console.log(result)
depatments.innerHTML = "";
$.each(result, function (i, result) {
var options = "<option value='" + result.Id + "' id='" + result.Id + "'>" + result.name + "</option>";
$('#CourseId').append(options);
});
},
failure: function (response) {
alert(response.responseText);
console.log(response.responseText);
},
error: function (response) {
alert(response.responseText);
console.log(response.responseText);
}
});
}
</script>
}
<!-- Debug item template -->
<script type="text/html" id="debug-template">
<li class="list-group-item text-%%color%%"><strong>%%date%%</strong>: %%message%%</li>
</script>
<!-- File item template -->
<script type="text/template" id="files-template">
<li class="uploaded_item">
<div class="item_body">
<div class="item_img_and_info_holder">
<div class="item_type_img_holder">
<img class="item_type_img" id="item_type_img" src="../../Content/images/files_types/pdf.png" />
</div>
<div class="item_info" style="width: 100%">
<h6 class="item_title" id="item_title">%%filename%% </h6>
<div class="item_details" style="margin-bottom: 10px;">
<span class="item_size" id="item_size">00.0 MB</span>
</div>
</div>
</div>
</div>
</li>
</script>
When removing AddChild() from loop it start working
also tried to do shallow copy but it did not work for me
function FileConfigHandler()
{
console.log('chal raha h')
var files1 = mfile.files;
console.log(mfile.files);
for (var i = 0; i < files1.length; i++) {
// console.log(files1[i]);
//var x= AddChild(files1[i]);
$('#files').append(x);
}
}
function AddChild(item)
{
var template = $('#files-template').html();
var parent = $(template);
var extention = item.name.split('.').pop();
// console.log(item.name.split('.').pop());
var name = item.name;
var temp_size = item.size;
var size = formatBytes(temp_size);
parent.find('#item_size').text(size)
parent.find('#item_title').text(name)
if (extention == 'pdf') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/pdf.png");
}
else if (extention == 'docx') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/doc.png");
}
else if (extention == 'jpg') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/jpg.png");
}
else if (extention == 'png') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/png.png");
}
else if (extention == 'ppt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/ppt.png");
}
else if (extention == 'txt') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/txt.png");
}
else if (extention == 'xls') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/xls.png");
}
else if (extention == 'csv') {
$(parent).find('.item_type_img').attr("src", "../../Content/images/files_types/csv.png");
}
return '<li class="uploaded_item">' + parent.html() + '</li>'
}
Related
Hi I'm trying to get my SQL database to update with user input via my HTML form that was displayed from my javascript file. Help is very appreciated :)
index.html
Display Events (HTML)
<!---- My Events ---->
<div id="my_events" class="menu_link">
<br>
<nav class="clean">
<div class="nav-wrapper">
<div class="col s12">
Home
My Events
</div>
</div>
</nav>
<div class="row">
<div class="col s12">
<h4>My Events</h4>
<button onclick="displayEvents(); loadPage()" class="waves-effect waves-light btn indigo">Display
Events</button>
<!-- Preloader -->
<div class="loadprogress indigo darken-4" style="width: 100%">
<div class="runningbar indigo lighten-1"></div>
</div>
<div class="content">
<!-- Table container -->
<table>
<!-- <th>Event ID</th> -->
<th>Event ID</th>
<th>Event Name</th>
<th>Event Description</th>
<th>Event Category</th>
<th>Event Address</th>
<th>Event Location</th>
<th>Event Date</th>
<th>Event Time</th>
<table id="eventsTable" class="striped">
<!-- List user events -->
</table>
</table>
</div>
</div>
</div>
</div>
Update Events Modal (HTML)
<!---- Update Event Section ---->
<!-- Modal Structure -->
<div id="update_events" class="modal">
<h5 class="modal-close right" onclick="closeModal()">✕</h5>
<div class="modal-content">
</div>
</div>
script.js
Display Events Fetch (JavaScript)
/* - Display Events - */
function displayEvents() {
loadPage();
// Define output string that will display the database data
var outStr = '';
var outStr2 = '';
fetch('api/ws.php?action=displayEvents', {
method: "GET",
credentials: "include",
})
.then(function (response) {
loadPage();
response.json().then(function (data) {
localStorage.setItem("events", JSON.stringify(data));
// console.log(data);
data.forEach(row => {
outStr +=
'<tr><td>' + row.eventID +
'</td><td>' + row.eventName +
'</td><td>' + row.eventDescription +
'</td><td>' + row.eventCategory +
'</td><td>' + row.eventAddress +
'</td><td>' + row.eventLocation +
'</td><td>' + row.eventDate +
'</td><td>' + row.eventTime +
'</td><td><button href="#update_events" class="modal-trigger" onclick="fillUpdate(' + row.eventID + ')" value="' + row.eventID + '"><i class="material-icons">edit</i></button>' +
'</td><td>' + '<button onclick="deleteRemoveEvent(' + row.eventID + ')" value="' + row.eventID + '"><i class="material-icons">delete</i></button>' +
'</td></tr>';
outStr2 =
`<div>
<h4>Update Events</h4>
<form action="api/ws.php" method="POST" onclick="return preventDefault()" novalidate>
<div class="input-field">
<i class="material-icons prefix">title</i>
<input id="update_ev_name" name="update_ev_name" placeholder="Event Name" type="text">
</div>
<div class="input-field">
<i class="material-icons prefix">notes</i>
<textarea id="update_ev_desc" name="update_ev_desc" class="materialize-textarea"
placeholder="Event Description"></textarea>
</div>
<div class="input-field">
<i class="material-icons prefix">category</i>
<input type="text" id="update_ev_cat" name="update_ev_cat" placeholder="Enter Your Event Type">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">map</i>
<input type="text" id="update_ev_address" name="update_ev_address" placeholder="Enter Your Address">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">flag</i>
<input type="text" id="update_ev_loc" name="update_ev_loc" placeholder="Event Location">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">date_range</i>
<input type="text" id="update_ev_date" class="datepicker" placeholder="Event Date">
</div>
<div class="input-field col s6">
<i class="material-icons prefix">schedule</i>
<input type="text" id="update_ev_time" class="timepicker" placeholder="Event Time">
</div>
<input type="hidden" name="eventid" value="`+ row.eventID +`" id="eventid">
<input type="hidden" name="action" value="update" id="updateEvent">
<button class="btn waves-effect waves-light" type="submit" onclick="postUpdateEvent(`+ row.eventID +`)">Update
Event</button>
</form>
</div>`
});
document.getElementById('eventsTable').innerHTML = outStr;
document.getElementById('update_events').innerHTML = outStr2;
});
});
}
Autofill Update Form (JavaScript)
/* - Autofill Update Form - */
function fillUpdate(eventid) {
console.log("Fill event with id " + eventid);
events = JSON.parse(localStorage.getItem("events"));
// console.log(events);
selectedEvent = events.filter(event => event[0] == eventid)[0];
if (selectedEvent != null) {
console.log(selectedEvent);
document.getElementById("update_ev_name").value = selectedEvent[1];
document.getElementById("update_ev_desc").value = selectedEvent[2];
document.getElementById("update_ev_cat").value = selectedEvent[3];
document.getElementById("update_ev_address").value = selectedEvent[4];
document.getElementById("update_ev_loc").value = selectedEvent[5];
document.getElementById("update_ev_date").value = selectedEvent[6];
document.getElementById("update_ev_time").value = selectedEvent[7];
// document.getElementById("eventid").value = selectedEvent[8];
}
}
Update Events Function with Fetch (JavaScript)
/* - Update Events - */
function postUpdateEvent(eventid) {
console.log("Update event with id " + eventid);
events = JSON.parse(localStorage.getItem("events"));
selectedEvent = events.filter(event => event[0] == eventid)[0];
var eventid = "eventid";
if (selectedEvent != null) {
console.log(selectedEvent);
document.getElementById("update_ev_name").value = selectedEvent[1];
document.getElementById("update_ev_desc").value = selectedEvent[2];
document.getElementById("update_ev_cat").value = selectedEvent[3];
document.getElementById("update_ev_address").value = selectedEvent[4];
document.getElementById("update_ev_loc").value = selectedEvent[5];
document.getElementById("update_ev_date").value = selectedEvent[6];
document.getElementById("update_ev_time").value = selectedEvent[7];
// document.getElementById("eventid").value = selectedEvent[8];
}
var userUpdate = {
'update_ev_name': document.getElementById("update_ev_name").value,
'update_ev_desc': document.getElementById("update_ev_desc").value,
'update_ev_cat': document.getElementById("update_ev_cat").value,
'update_ev_address': document.getElementById("update_ev_address").value,
'update_ev_loc': document.getElementById("update_ev_loc").value,
'update_ev_date': document.getElementById("update_ev_date").value,
'update_ev_time': document.getElementById("update_ev_time").value
}
// var updatefd = new FormData();
// updatefd.append('action', 'update');
// updatefd.append('eventid', eventid.value);
// updatefd.append('update_ev_name', update_ev_name.value);
// updatefd.append('update_ev_desc', update_ev_desc.value);
// updatefd.append('update_ev_cat', update_ev_cat.value);
// updatefd.append('update_ev_address', update_ev_address.value);
// updatefd.append('update_ev_loc', update_ev_loc.value);
// updatefd.append('update_ev_date', update_ev_date.value);
// updatefd.append('update_ev_time', update_ev_time.value);
// updatefd.append('updateEvent', updateEvent.value);
fetch('api/ws.php?action=updateEvent', {
method: "POST",
body: JSON.stringify(userUpdate),
credentials: 'include',
// body: updatefd,
})
// Force error into console
.then(function (response) {
response.text().then(function (text) {
console.log(text);
});
// HTTP Response Codes
if (response.status === 200) {
// loadPage();
console.log(eventid.value);
}
if (response.status === 202) {
console.log('Update Successful');
}
if (response.status === 400) {
errormessage('Error: Bad Request');
console.log('Bad Request');
console.log(eventid.value);
return;
}
if (response.status === 401) {
console.log('Not permitted');
return;
}
if (response.status === 501) {
errormessage('Error: Not implemented');
console.log('Not implemented :(');
return;
}
response.text().then(function (text) {
console.log(text);
});
});
}
ws.php
Switch Case API (PHP)
/* - Display User Events - */
case "displayEvents":
// if ($_SESSION['se']->is_logged_in()) {
$result = $db->displayEvents();
if ($result == false) {
http_response_code(501);
} else {
http_response_code(202);
echo json_encode($result);
}
// } else {
// http_response_code(401);
// }
break;
/* - Autofill the update form - */
case "fillUpdate":
if (isset($_POST["action"])) {
$result = $_SESSION['se']->is_logged_in();
if ($result == true) {
$evid = $_POST['evid'];
$details = $db->get_details($evid);
if ($details == false) {
http_response_code(501);
} else {
http_response_code(201);
echo json_encode($details);
}
}
}
break;
/* - Update the User Event - */
case "updateEvent":
if (isset($_POST["action"])) {
// $evid = $_GET['evid'];
$_SERVER['REQUEST_METHOD'] == 'POST';
$objreg = json_decode(file_get_contents("php://input"), true);
$evid = testInput($objreg['evid']);
$update_ev_name = testInput($objreg['update_ev_name']);
$update_ev_desc = testInput($objreg['update_ev_desc']);
$update_ev_cat = testInput($objreg['update_ev_cat']);
$update_ev_address = testInput($objreg['update_ev_address']);
$update_ev_loc = testInput($objreg['update_ev_loc']);
$update_ev_date = testInput($objreg['update_ev_date']);
$update_ev_time = testInput($objreg['update_ev_time']);
$db->updateEvent($evid, $update_ev_name, $update_ev_desc, $update_ev_cat, $update_ev_address, $update_ev_loc, $update_ev_date, $update_ev_time);
// echo "Record updated successfully";
http_response_code(202);
} else {
http_response_code(400);
}
// if ($_POST["eventid"] == null)
break;
db.php
Database Functions (PHP + SQL)
/* -- Display Events Function -- */
function displayEvents()
{
db_connection();
try {
$stmt = $this->dbconn->prepare('SELECT eventID, eventName, eventDescription, eventCategory, eventAddress, eventLocation, eventDate, eventTime FROM events');
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
} catch (PDOException $ex) {
throw $ex;
}
}
/* - Autofill the Update Event Form - */
function get_details($evid)
{
$stmt = $this->dbconn->prepare("SELECT * FROM events WHERE eventID = :eid");
$stmt->bindValue(":eid", $evid);
$stmt->execute();
$result = $stmt->fetch();
return $result;
}
/* -- Update Events Function -- */
public function updateEvent($evid, $update_ev_name, $update_ev_desc, $update_ev_cat, $update_ev_address, $update_ev_loc, $update_ev_date, $update_ev_time)
{
print_r("hello");
db_connection();
try {
$this->dbconn->beginTransaction();
/* --- Event Table --- */
$stmt = $this->dbconn->prepare("UPDATE events SET eventName = :update_ev_name, eventDescription = :update_ev_desc, eventCategory = :update_ev_cat, eventAddress = :update_ev_address, eventLocation = :update_ev_loc, eventDate = :update_ev_date, eventTime = :update_ev_time WHERE eventID = :eid");
// bind values
$stmt->bindValue(":eid", $evid);
$stmt->bindValue(':update_ev_name', $update_ev_name);
$stmt->bindValue(':update_ev_desc', $update_ev_desc);
$stmt->bindValue(':update_ev_cat', $update_ev_cat);
$stmt->bindValue(':update_ev_address', $update_ev_address);
$stmt->bindValue(':update_ev_loc', $update_ev_loc);
$stmt->bindValue(':update_ev_date', $update_ev_date);
$stmt->bindValue(':update_ev_time', $update_ev_time);
// Execute the update statement
$stmt->execute();
// Commit changes here
$this->dbconn->commit();
} catch (PDOException $ex) {
$ex->getMessage();
exit();
}
}
Errors I'm getting :( and no respose/preview errors in network tab
I am working on implementing a web chat and have come up with an issue that I hope is easily solvable.
How do I change the color for the sender/receiver to differenciate them?
I have tried to saving the colors into my db but the issue is how I can identify that I am the sender and the receivers color needs to be different.
This is how I have implemented my chat:
Chat.js
connection.on("SessionNotification", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = user + " - " + moment(datetime).format("DD-MM-YYYY HH:mm:ss");
q.textContent = msg;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
});
Html
<script>
$(document).ready(function () {
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
var SessionId = document.getElementById("Id").value;
console.log(SessionId);
var form_data = {
"SessionId": SessionId
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
return false;
});
</script>
<div class="col-sm-12">
<h2>Session</h2>
<hr />
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div id="MessageListContainer">
<ul id="MessageList">
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.CurrentUser)
<input class="form-control col-sm-12" id="Message" type="text" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="clearfix">
<div class="pull-right">
<input id="Send" type="button" value="Send" class="btn btn-primary" />
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<hr />
</div>
</div>
<script src="~/aspnet/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
Your AJAX call that comes back as JSON appears to have a few fields like Name and CreatedOn. You can add an additional field server side for the SessionId, which you are injecting server-side anyway into your HTML. Then you can compare to see if the message's session matches yours. If so, then it is you and not the receiver. So you might have something like:
JS
// You set this earlier on
var SessionId = document.getElementById("Id").value;
// ........ OTHER CODE IN BETWEEN
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
// If session ID matches current session (i.e. you) then add different class
if (output[i].SessionId === SessionId) {
// It is you
p.setAttribute("class", "Sender");
} else {
// It is other person
p.setAttribute("class", "Receiver");
}
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
CSS
.Sender {
color: blue;
}
.Receiver {
color: green;
}
I am working on trying to link pages together so if a person were to login using the login page, they would be redirected to a specific created page, and if a user clicked the register button, they would be redirected to the register page and from there, after inputting in information, they would be directed to another page. The button for login or register does not work. Is there a way to fix this?
So far I have this for my login page.
function login() {
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
ivar aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
window.location = "dashboard.php";
break;
}
}
var myOut = document.getElementById("output");
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
Validation function:
function validation() {
for (i=1; i<=10; i++) {
var myErr = document.getElementById("err" + i);
myErr.innerHTML = "";
}
document.getElementById("output").innerHTML = "";
var dept_name = document.getElementById("dept_name").value;
var user_email = document.getElementById("user_email").value;
var user_password = document.getElementById("user_password").value;
var phone_number = document.getElementById("phone_number").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var office_location = document.getElementById("office_location").value;
var valid = true;
if (dept_name == "") {
document.getElementById("err1").innerHTML = "Invalid!";
valid = false;
}
if ((user_email) =="") {
valid = false;
document.getElementById("err2").innerHTML = "Invalid!";
}
if ((user_password) =="") {
valid = false;
document.getElementById("err3").innerHTML = "Invalid!";
}
if ((first_name) =="") {
valid = false;
document.getElementById("err4").innerHTML = "Invalid!";
}
if ((last_name) =="") {
valid = false;
document.getElementById("err5").innerHTML = "Invalid!";
}
if (isNaN(phone_number) || card_number.length !==11) {
valid = false;
document.getElementById("err6").innerHTML = "Invalid!";
}
if ((office_location) =="") {
valid = false;
document.getElementById("err7").innerHTML = "Invalid!";
}
}
window.onload=init;
Several errors
missing brackets
no execution of init
missing validation function
This works:
function login() {
var myOut = document.getElementById("output");
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
var aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
myOut.innerHTML = "Correct - you will be redirected";
setTimeout(function() {
window.location = "dashboard.php";
},1000);
return;
}
}
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
}
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
function validation() { /* you need some code here */ }
window.onload=init;
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
You can make the test simpler:
var userPos = users.indexOf(aUser);
if (userPos !=-1 && userPos === pass.indexOf(aPass)) {
...
}
I am making a MEAN stack application. It is an online live test taking application where user has to face a multiple choice question with 4 options and has to choose one.
Now, the problem i'm getting is, suppose there are 2 questions:
1. What is 1+0?
a. 1
b. 3
c. 4
d. 5
The answer to this question is at index 1,also the answer is 1. So my controller is sending 1 to the Submit button(it's sending the index, not the actual answer).
Take another question. What is 3+4?
a. 7
b. 8
c. 9
d. 10
Here, the controller sends 1 to the database, as the correct answer marked by user is at first index.
I want it to send 7.
This is my controller
liveController.js
examApp.controller('liveController', ['$scope', '$filter', '$http', '$location', '$routeParams', 'queryService', 'authenticationService', function($scope, $filter, $http, $location, $routeParams, queryService, authenticationService) {
var main = this;
var totalnoofQuestions;
var user;
main.questionsforTime = [];
this.getsecurityQuestion = function() {
var data = {
_id: $routeParams.userId
}
queryService.getsecurityQuest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
var userId;
var data = response.data.data;
main.user = data.name;
main.userId = data._id;
authenticationService.setToken(response.data.token);
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
this.getsecurityQuestion();
this.logged = function() {
main.username = queryService.userName;
if (queryService.log == 1 || queryService.userId !== 'undefined') {
return 1;
} else {
$location.path('/');
}
}
this.logged();
this.userId = $routeParams.userId;
main.heading = "Welcome To Exam App";
$('.thisismodalforlivetestwarning').modal('show');
$(document).on('click', '#returntotaketest', function() {
$('.thisismodalforlivetestwarning').modal('hide');
location.replace("#/taketheTest/" + main.userId);
})
this.getasingleTest = function() {
var singletestId = $routeParams.testId;
queryService.getasingleTest(singletestId)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
window.location.href = "#/taketheTest/" + main.userId;
} else {
if (response.data.data.questions.length == 0) {
$location.path("/taketheTest/" + main.userId);
alert("No questions present.");
} else {
main.totalnoofQuestions = response.data.data.questions.length;
main.questionsforTime.push(response.data.data.questions.length);
main.testHeading = "Test topic is " + response.data.data.testName;
main.singletestArray = response.data.data.questions;
main.time = response.data.data.testDuration;
}
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
this.getasingleTest();
var totalSeconds = 300;
var minutes = parseInt(totalSeconds / 60);
var seconds = parseInt(totalSeconds % 60);
this.theTime = function() {
totalSeconds = totalSeconds - 1;
minutes = parseInt(totalSeconds / 60);
seconds = parseInt(totalSeconds % 60);
main.timetakeninTest = (300 - totalSeconds);
document.getElementById('test-time-left').innerHTML = 'Time Left: ' + minutes + ' minutes ' + seconds + ' seconds';
if (totalSeconds <= 0) {
clearTimeout(main.counttime);
main.timetakeninTest = 300;
alert("Time Is Up!!");
container.style.display = 'none';
var testattemptData = {
testgivenBy: main.user + " " + $routeParams.userId,
testId: $routeParams.testId
}
queryService.testAttemptedBy(testattemptData)
.then(function successCallback(response) {}, function errorCallback(response) {})
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
score: score,
timeTaken: main.timetakeninTest,
totalCorrect: (score / 10),
totalIncorrect: (10 - (score / 10))
}
queryService.submitTest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
main.performanceUserID = response.data.data.user;
main.answerscorrect = response.data.data.totalCorrect;
main.answerswrong = response.data.data.totalIncorrect;
main.madeScore = response.data.data.score;
main.timeTaken = response.data.data.timeTaken;
$('.thisismodalforUserTestPerformance').modal('show');
}
}, function errorCallback(response) {
alert("There was a problem.");
})
}
}
var currentQuestion = 0;
var score = 0;
var totalQuestionAsked = 0;
var container = document.getElementById('quizContainer');
var questionEl = document.getElementById('question');
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
var nextButton = document.getElementById('nextButton');
var resultCont = document.getElementById('result');
this.loadQuestion = function(questionIndex) {
if (questionIndex == 0) {
totalQuestionAsked = main.totalnoofQuestions;
$('.thisismodalforlivetestwarning').modal('hide');
main.counttime = setInterval(this.theTime, 1000);
}
var q = main.singletestArray[questionIndex];
questionEl.textContent = (questionIndex + 1) + '.' + q.question;
opt1.textContent = q.optionA;
opt2.textContent = q.optionB;
opt3.textContent = q.optionC;
opt4.textContent = q.optionD;
};
this.nextQuestion = function() {
var selectedOption = document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert("Select An Answer First.");
return;
}
var answer = selectedOption.value; //This line
console.log("this is problem " + answer);
if (main.singletestArray[currentQuestion].answer == answer) {
score += 10;
}
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
questionid: main.singletestArray[currentQuestion]._id,
userAnswer: answer,
correctAnswer: main.singletestArray[currentQuestion].answer,
timetakenInsecs: main.timetakeninTest
}
queryService.submitAnswer(data)
.then(function successCallback(response) {}, function errorCallback(response) {})
selectedOption.checked = false;
currentQuestion++;
if (currentQuestion == totalQuestionAsked - 1) {
nextButton.textContent = 'Finish';
}
if (currentQuestion == totalQuestionAsked) {
container.style.display = 'none';
clearTimeout(main.counttime);
var testattemptData = {
testgivenBy: main.user + " " + $routeParams.userId,
testId: $routeParams.testId
}
queryService.testAttemptedBy(testattemptData)
.then(function successCallback(response) {}, function errorCallback(response) {})
var data = {
userid: $routeParams.userId,
testid: $routeParams.testId,
score: score,
timeTaken: main.timetakeninTest,
totalCorrect: (score / 10),
totalIncorrect: (10 - (score / 10))
}
queryService.submitTest(data)
.then(function successCallback(response) {
if (response.data.error === true) {
alert(response.data.message);
} else {
main.performanceUserID = response.data.data.user;
main.answerscorrect = response.data.data.totalCorrect;
main.answerswrong = response.data.data.totalIncorrect;
main.madeScore = response.data.data.score;
main.timeTaken = response.data.data.timeTaken;
$('.thisismodalforUserTestPerformance').modal('show');
}
}, function errorCallback(response) {
alert("There was a problem");
})
return;
}
this.loadQuestion(currentQuestion);
}
}]);
<link rel="stylesheet" href="../css/livetest.css">
<!-- W3 schools styles-->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet">
<div ng-controller="liveController as live">
<nav class="navbar fixed-top navbar-toggleable-md navbar-inverse bg-inverse">
<br/>
<div class="container">
<a class="navbar-brand" href="">
<h2>
<i class="fa fa-line-chart" aria-hidden="true"></i> Exam App Dashboard
</a>
</div>
<br/>
</nav>
<div Style="color:white;font-weight:bold;font-size:2em; text-align:center;" id="test-time-left"></div>
<div style="background: #F2F2F2;" id="quizContainer" class="container">
<div class="title" style="text-align: center; font-weight:bold; font-size: 1.5em;">{{live.testheading}}</div>
<div id="question" class="question" style="font-size: 2em; font-weight: bold;"></div>
<label class="option">
<input type="radio" name="option" value="1" />
<span id="opt1"></span>
</label>
<label class="option">
<input type="radio" name="option" value="2" />
<span id="opt2"></span>
</label>
<label class="option">
<input type="radio" name="option" value="3" />
<span id="opt3"></span>
</label>
<label class="option">
<input type="radio" name="option" value="4" />
<span id="opt4"></span>
</label>
<button id="nextButton" class="next-btn" ng-click="live.nextQuestion()">Next Question </button>
</div>
<br/>
<!-- Place to keep all the modals -->
<!-- Modal -->
<div class="modal fade thisismodalforlivetestwarning" id="modalfortestwarning" role="dialog" data-backdrop="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div style="background-color: #4CAF50;" class="modal-header">
<h4 align="center" class="modal-title">
<span style="color:white;">: Please Read The instructions Carefully :</span>
</h4>
</div>
<div class="modal-body">
<ol>
<li>You will be alloted 5 Minutes to Give Test, After which window will close Automatically.</li>
<li>You can't go back after submitting the Answer for each Question.</li>
<li>you can submit the Test before the finishing Time if you want but can't after the time finishes, It will Automatically be submitted.</li>
<li>Please don't do cheating in test. Be fair to yourself for your true Assessment of skills.</li>
<li>If you aggree with all the terms stated above you may proceed by clicking Start Button Below.</li>
</ol>
<h3 align="center">
<strong>
<em>Best Of Luck!</em>
</strong>
</h3>
</div>
<div style="background-color: #404549;" class="modal-footer">
<button type="button" class="btn btn-success" ng-click="live.loadQuestion(0)">Start!</button>
<button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
</div>
</div>
</div>
</div>
<!-- MOdal for User Performance -->
<!-- Modal -->
<div class="modal fade thisismodalforUserTestPerformance" role="dialog" data-backdrop="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div style="background-color: #4CAF50;" class="modal-header">
<h4 align="center" class="modal-title">
<span style="color:white;">: Your Score Card for the Test :</span>
</h4>
</div>
<div class="modal-body">
<div style="background-color: #404549;" class="modal-body">
<a class=" list-group-item">User ID: {{live.performanceUserID}}</a>
<a class=" list-group-item">Total Correct Answers: {{live.answerscorrect}}</a>
<a class=" list-group-item">Total Wrong Answers: {{live.answerswrong}}</a>
<a class=" list-group-item">Score Secured: {{live.madeScore}}</a>
<a class=" list-group-item">Total Time Taken: {{live.timeTaken}} Seconds</a>
</div>
<h3 align="center">
<strong>
<em>Thank You! For giving the Test...</em>
</strong>
</h3>
</div>
<div style="background-color: #404549;" class="modal-footer">
<button type="button" class="btn btn-danger" id="returntotaketest">Return</button>
</div>
</div>
</div>
</div>
The action happens at nextQuestion function at the commented line (commented with '//This line'). I have tried my best to explain my problem and can upload more code if required.
Any help will be appreciated.
You could do something like this
var selectedOption = document.querySelector('input[type=radio]:checked');
if (!selectedOption) {
alert("Select An Answer First.");
return;
}
//As selectedOption is actually an index we can use it to get the answer
var answerValue = document.getElementById('opt'+ selectedOption);
var answer = answerValue.textContent;
I am displaying a grid with some data fetched from a csv file along with a checkbox before each row. I am also saving unique ID in the value property of checkbox. Now I want to get the value of ID`s of all checked check boxes in alert() when 'Cancel' button is clicked.
html-
<div class="panel panel-primary">
<div class="panel-heading">DIS Automation</div>
<div class="panel-body">
<div class="field_row">
<input type="file" accept=".csv" id="fileUpload" name="fileUpload1" />
</div>
<br />
<div class="field_row">
<div class="col-lg-12">
<div class="form-group">
<center><div class="col-lg-3"><div class="input-append" id="filterDev" style="visibility: hidden">
<input name="search" id="inputFilter" placeholder="Enter comma separated ID" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></div></center>
<div class="col-lg-6"></div>
<input type="button" id="upload" value="Upload" class="btn btn-primary" />
<input type="button" id="cancel" value="Cancel/Save" style="visibility: hidden" class="btn btn-primary" />
<input type="button" id="process" value="Process" style="visibility: hidden" class="btn btn-primary" />
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style=" max-height:600px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</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>
<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();
}
});
/* $("#File1").click(function () {
window.location = "Files/CommitteeMembers.xlsx";
});
$("#File1").click(function () {
window.location = "Files/GSD_Offering_Completion.xlsx";
});*/
</script>
Javascript-
$(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");
//alert(lines);
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < headers.length; i++) {
var header = headers[i];
header = header.replace(/(\r\n|\n|\r)/gm, "");
headers[i] = header;
}
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
//alert(currentline);
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
//alert(obj[headers[j]]);
}
result.push(obj);
//alert(JSON.stringify(result));
}
//alert(result[0].NAME + ' '+ result[0].ADDRESS+" "+result[0].CITY);
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]);
columns.unshift('');
//alert(columns);
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><input type="checkbox" value='+obj.ID+'/></td>
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
How can this be implemented??
This is a sample code of how you can do it:
$(".btnCancel").click(function(){
var alertText="";
$("[type='checkbox']:checked").each(function(){
alertText+= $(this).attr("value") + " ";
});
alert(alertText);
});
Here is the JSFiddle demo