How to save html page content in .txt file using JavaScript? - javascript

I have create a static html page for quiz.
Following is my code
<style>
body {
font-family: Open Sans;
}
#quiz {display:none;}
#prev {display:none;}
#start {display:none;}
#submit{display:none;}
ul{list-style:outside none none; margin:0px; padding:0px;}
.question>div>div>div>p{ color: #fff;
background-color: #337ab7;
padding: 6px;
border-radius: 3px;}
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;}
</style>
<body>
<div class='container question'>
<div class='row'>
<div class='col col-md-12' id='quiz'>
</div>
</div>
</div>
<div class='container question' >
<div class='row' id='quiz'>
</div>
</div>
<br/>
<div class='container'>
<a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a>
<a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a>
<a href='#' class='btn btn-md btn-default' id='start'>Start Over</a>
<div class='button' id='submit' style='display:none;'>
<input type='text' placeholder='Name' id="inputFileNameToSaveAs"/>
<button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button>
</div>
</div>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type="text/javascript">
function saveTextAsFile()
{
var textToSave = document.getElementById("question").text;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
(function() {
var questions = [
{
question: "Which one is correct?",
choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'],
correctAnswer: 0
},
];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<p>Question ' + (index + 1) + '</p>');
qElement.append(header);
var question = $('<h3>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
$('#submit').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<h4>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();
</script>
</body>
all is working fine but i want to save the checked radio button value and final result in .txt file
i want to save all the answers by user and along with the correct and the wrong to.

Things to note :
- initialize the variable textToSave first with no value;
- document.getElementById("question").text; Should be document.getElementById("question").innerHTML;
- in the body of choose, add the value of radio to the variable textToSave
And the result
var textToSave='';
function saveTextAsFile()
{
textToSave += ". Final Result : "+document.getElementById("question").innerHTML;
var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
(function() {
var questions = [
{
question: "Which one is correct?",
choices: ['a!=b', 'a=!b', 'a:=b', 'a=-b'],
correctAnswer: 0
},
];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<p>Question ' + (index + 1) + '</p>');
qElement.append(header);
var question = $('<h3>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
textToSave += "Choosen Value : "+selections[questionCounter];
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
$('#submit').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<h4>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();
<style>
body {
font-family: Open Sans;
}
#quiz {display:none;}
#prev {display:none;}
#start {display:none;}
#submit{display:none;}
ul{list-style:outside none none; margin:0px; padding:0px;}
.question>div>div>div>p{ color: #fff;
background-color: #337ab7;
padding: 6px;
border-radius: 3px;}
.navbar-default {background-color: #fff;border-color: #ddd; border-radius:0px;}
</style>
<body>
<div class='container question'>
<div class='row'>
<div class='col col-md-12' id='quiz'>
</div>
</div>
</div>
<div class='container question' >
<div class='row' id='quiz'>
</div>
</div>
<br/>
<div class='container'>
<a href='#' class='btn btn-md btn-default pull-right' id='next'>Next</a>
<a href='#' class='btn btn-md btn-default pull-left' id='prev'>Prev</a>
<a href='#' class='btn btn-md btn-default' id='start'>Start Over</a>
<div class='button' id='submit' style='display:none;'>
<input type='text' placeholder='Name' id="inputFileNameToSaveAs"/>
<button type='submit' class='btn btn-success' onclick="saveTextAsFile()">Submit</button>
</div>
</div>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
</body>

I assume you want to save the data for yourself, not the end user.
If you are looking to generate a txt file and download it - You can refer answer from Sagar V.
You can't directly save your answers or whatever data into a file by using JavaScript from a web browser.
You neeed a small server, maybe in node.js , php or java
First format your answers in particular structure like json and sene it as POST request method parameter
In server parse your parameter and save to an file you need

function downloadFile(filename, content) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}

Related

Store text from dynamically created textareas in localStorage

Problem - I have 2 buttons addNew and submitText. I have created a javascript function for each of these two buttons. The addNewcreates textareas with unique ids (note0, note1...). The submitText is supposed to submit the text from all the dynamically created textareas in localStorage in the (key, value) format (notesList0, data), (notesList1, data) and so on. The code is as follows -
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
} , false);
});
The addNew works but submitText only saves value of the first textarea. Where am I going wrong?
I guess it's because of flag staying "false" after the first loop:
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
var flag=true;
for(counter=0; counter<=note_id; counter++) {
var textData = document.getElementById("note"+counter).value;
alert(textData);
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
flag = true;
}
} , false);
});
Use the following for the submit function to make it work for dynamically created elements:
$(document).on("click", "#submitText", function(){
// Do stuff
})
Make sure the ID is only used once on the page. Otherwise switch to class definition.
$(document).ready(function(){
var note_id = 0;
$("#addNew").click(function () {
note_id++;
var inputField = $('<p align="center"><br><textarea id="note' + note_id + '" placeholder="Enter note, max limit 200 words" class="form-control" rows="5" style="width:80%;overflow:auto;"></textarea></p>');
$('#textFields').append(inputField);
});
document.getElementById("submitText").addEventListener("click", function(){
var id=0, counter;
for(counter=0; counter<=note_id; counter++) {
var flag=true;
var textData = $("#note"+counter).val();
if(textData != undefined && textData != '') {
while(flag==true)
{
if(localStorage.getItem("notesList"+id)!=null) {
id++;
}
else {
localStorage.setItem("notesList"+id, textData);
flag=false;
alert("Text saved");
}
}
}
}
} , false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="addNew">Add new</span>
<span id="submitText">Submit</span>
<div id="textFields"></div>
In case you get error when executing the code, check this link:
Failed to read the 'localStorage' property from 'Window'

how to upload multiple image in php using javascript array

i have an array in java script, that array have file name and file path, now i have to assign that array in php and upload that file which are store in array, what can i do please give me solutions.
This is my javascript
<script type="text/javascript">
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
//console.log(files);
var filePath = $(this).val();
//console.log("fake pathddddddddddd"+filePath);
for (var i = 0; i < filesLength; i++) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = files[i];
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API");
}
});
</script>
dict is my array how can assign that array in php and upload in file,
you can check in console to gat the value
php file
<!DOCTYPE html>
<head>
<style>
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
whenever click the clickMe button you can the file name and file path in console check it and please help me
Sorry for the late return. I am not 100% sure if this is what you wanted. But i did it anyway :). Thanks to #Ben_Lee with his answer I managed to wrap the initiation inside a function.
var arrImgNPath = [];
var arrUniqueIds = [];
function myFunction() {
var files = $('#filesID').prop("files");
var names = $.map(files, function(val) { return val.name; });
console.log(names);
console.log("N the final result is :");
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
//$('#str').val(JSON.stringify(dict));
console.log("obj value :",dict);
}
}
function removeImageDataFromArray(spanId){
console.log("spanID--------------------------------------"+spanId);
arrImgNPath= arrImgNPath.filter(function(el) { return el.ID != spanId; });
for (var i=0; i<arrImgNPath.length; i++){
var dict = arrImgNPath[i];
console.log("obj value :",dict);
}
}
function uniqId() {
while (1) {
var uid = Math.round(new Date().getTime() + (Math.random() * 100));
var isPresent = false;
for(var i=0; i<arrUniqueIds.length; i++){
var idFromArray = arrUniqueIds[i];
if (uid == idFromArray){
isPresent = true;
}
}
if (isPresent === false) {
return uid;
}
}
}
function initiateFiles(file) {
var tmppath = URL.createObjectURL(event.target.files[0]);
filePath =tmppath;
var f = file;
var randomId = uniqId();
var dict = {};
dict.name = f.name;
dict.path = filePath;
dict.ID = randomId;
arrImgNPath[arrImgNPath.length] = dict;
var fileReader = new FileReader();
fileReader.onload = (function(e) {
//var file = e.target;
//console.log("bfsd dsf sdfdsfds"+e.target.result);
// console.log("adsfdsfsd fsdf sdfsdfsdfsdsdfd"+randomId);
$("<span id=\"" + randomId + "\" class=\"pip\" >" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#filesID");
$(".remove").click(function(){
//$(this).find("span").attr("id", "myspan_"+i);
console.log("files id values :"+ $(this).parent(".pip").attr("id"));
removeImageDataFromArray($(this).parent(".pip").attr("id"));
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#filesID").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
var filePath = $(this).val();
for (var i = 0; i < filesLength; i++) {
initiateFiles(files[i]);
}
console.log(arrImgNPath);
var myJSON = JSON.stringify(arrImgNPath);
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
});
} else {
alert("Your browser doesn't support to File API");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
<h3>Upload your images</h3>
<input type="file" id="filesID" name="files[]" size="150" multiple="multiple" >
<input type="submit" name="submit" >
<input type="button" onclick="myFunction()" value="clickMe">
</form>
</div>
Here i created a hidden input, which stores the array.
$("<input value=\'" + myJSON + "\' name=\"myJSON\" type=\"hidden\" />").insertAfter("#filesID");
And then assigned an action to the form to send the data to another php file.
<form method="post" action="yourOther.php" enctype="multipart/form-data" >
And now it is time to get the data and process:
<?php
$data = json_decode($_POST['myJSON']);
foreach ($data as $key => $value) {
echo " Name : $value->name <hr>";
echo " Path : $value->path <hr>";
echo " ID : $value->ID <hr>";
}
?>
I hope this helps, if you have further questions, don't hesitate to ask.

How to clear all dynamically created SPAN elements

I've created some code that dynamically creates some fields within a SPAN element. One of the fields is a delete icon, that when click runs a function to remove the selected span. Now I want to create a function that simply wipes out all the spans, sounds simple but it breaks after the first one.
This is a sample of my code (modified it for simplicity):
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ip = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ip.setAttribute("type", "text");
ip.setAttribute("value", item)
ip.setAttribute("Name", "text_item_element_" + global_i);
ip.setAttribute("id", "id_item_" + global_i);
ip.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ip);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
In each line for the image I set the onclick event handler to run the function removeSpanElement(parentDiv, childDiv) and it works fine. So to clear them all I'd think I just run the function through an incremental loop, clearItems(), but it stops after removing the first one and I can't figure out why.
You can simply add a new class to the dynamically added span(to make it easy to select them), then remove all the elements with the added class like
var global_i = 0; // Set Global Variable i
function increment() {
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem() {
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ins = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ins.setAttribute("type", "text");
ins.setAttribute("value", item);
ins.setAttribute("Name", "text_item_element_" + global_i);
ins.setAttribute("id", "id_item_" + global_i);
ins.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ins);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
el.className = 'dynamic'
document.getElementById("myForm").appendChild(el);
}
/* This function only clears 1st span */
function clearItems() {
var spans = document.getElementsByClassName('dynamic');
while (spans.length) {
spans[0].remove();
}
global_i = 0;
}
<form>
<input type='text' id='item' value='' />
<input type="button" value="Add" onclick="addItem()" />
<input type="button" value="Clear All" onclick="clearItems()" />
<span id="myForm"></span>
</form>
You were using a reserved keyword, and you were having a variable undefined. I've edited the code for you. Compare my code with yours to see where are the mistakes.
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem(){
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ig = document.createElement("INPUT"); // "in" is a reserved keyword. It can't be used as a variable
var ip = document.createElement("IMG");
var el = document.createElement('SPAN');
ig.setAttribute("type", "text"); // modified
ig.setAttribute("value", item) //
ig.setAttribute("Name", "text_item_element_" + global_i); //
ig.setAttribute("id", "id_item_" + global_i); //
ig.setAttribute("style", "width:80px"); //
ig.setAttribute("src", "delete.png"); // "im" was undefined. You probably wanted to write "in", but it was wrong anyway
ig.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')"); // the same
el.appendChild(ig);
el.appendChild(ig);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
<code> <form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
try{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var in_e = document.createElement("INPUT");
var ip_e = document.createElement("IMG");
var el = document.createElement('SPAN');
in_e.setAttribute("type", "text");
in_e.setAttribute("value", item)
in_e.setAttribute("Name", "text_item_element_" + global_i);
in_e.setAttribute("id", "id_item_" + global_i);
in_e.setAttribute("style", "width:80px");
ip_e.setAttribute("src", "delete.png");
ip_e.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(in_e);
el.appendChild(in_e);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}catch(e){alert(e)}
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
</code>

Cannot get file type input to clear

So i've looked at the other questions and I am too far along in my page to try something else. I have an input type of file and I am trying to clear it when the user decides that they do not want to use it. I have some other functionality that is set to show the file name, size, etc... based on the FILE API but for some reason I cannot get the input to clear. I am trying a few different ways to clear it but still nothing. Anyone see what I am doing wrong. I have a jQuery check to check the value of the input and it never clears. The only thing I can think of is that I am using the standard hide the input and using a link so I can actually style the file input button.
Here is the FIDDLE:
JS FIDDLE
Here is the HTML:
<div>
<label id="huf1-label">fileGroup 1</label>
<input type="file" id="fileElem" accept="image/*" style="display:none"
onchange="handleFiles(this.files)" name="file">
<a href="#" id="fileSelect" class="c1-button right gray" tabindex="0">Select
File to
Upload<span class="icon-checkmark"></span> </a>
</div>
<div>
<label id="huf1Btn-label">
<div class="fileInfoContainer">
<ul>
<li>
<div id="fileList" class="fileInfoContainer">
</div>
</li>
</ul>
</div>
</label>
<button id="removeFile1" class="c1-button red left-icon"
aria-controls="huf1">
<span class="icon-remove"></span><b> Cancel</b>
<span class="hidden">fileGroup 1</span>
</button>
<div class="filename"></div>
Here is the script:
window.URL = window.URL || window.webkitURL;
//BEGIN - fileSelect1 and handleFile
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
function handleFiles(files) {
if (!files.length) {
fileList.innerHTML = "<p></p>";
} else {
$('#fileList').empty().append();
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
$("#removeFile1").click(function (event) {
event.preventDefault();
$("#fileList").empty();
$("#removeFile1").find('b').html('Cancel');
$('#fileElem').each(function() {
$(this).val();
});
document.getElementById("fileElem").value = "";
document.getElementById("fileSelect").value = "";
console.log('#fileList' + 'was deleted');
console.log('#fileElem' + 'was deleted I hope');
// console.log($(this)+'#fileList'.val());
});
}
};
$("#fileElem").change(function(){
if (this.val == "" ) {
$("#removeFile1").find('b').html('Cancel');
} else {
$("#removeFile1").find('b').html('Remove this file');
}
});
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
I Corrected It this is the answer Try this....
The problem you are facing is this error...
Uncaught ReferenceError: handleFiles is not defined
So I canged it like this...
HTML
<div>
<label id="huf1-label">fileGroup 1</label>
<input type="file" id="fileElem" accept="image/*" style="display:none"
name="file">
<a href="#" id="fileSelect" class="c1-button right gray" tabindex="0">Select
File to
Upload<span class="icon-checkmark"></span> </a>
</div>
<div>
<label id="huf1Btn-label">
<div class="fileInfoContainer">
<ul>
<li>
<div id="fileList" class="fileInfoContainer">
</div>
</li>
</ul>
</div>
</label>
<button id="removeFile1" class="c1-button red left-icon"
aria-controls="huf1">
<span class="icon-remove"></span><b> Cancel</b>
<span class="hidden">fileGroup 1</span>
</button>
<div class="filename"></div>
</div>
SCRIPT
window.URL = window.URL || window.webkitURL;
//BEGIN - fileSelect1 and handleFile
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
$("#fileElem").change(function() {
var files=this.files;
if (!files.length) {
fileList.innerHTML = "<p></p>";
} else {
$('#fileList').empty().append();
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
$("#removeFile1").click(function (event) {
event.preventDefault();
$("#fileList").empty();
$("#removeFile1").find('b').html('Cancel');
$('#fileElem').each(function() {
$(this).val();
});
document.getElementById("fileElem").value = "";
document.getElementById("fileSelect").value = "";
console.log('#fileList' + 'was deleted');
console.log('#fileElem' + 'was deleted I hope');
// console.log($(this)+'#fileList'.val());
});
}
});
$("#fileElem").change(function(){
if (this.val == "" ) {
$("#removeFile1").find('b').html('Cancel');
} else {
$("#removeFile1").find('b').html('Remove this file');
}
});
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$(".filename").html(fileName);
});
});
JSFIDDLE LINK HERE
This is the Link for updated JSFIDDLE...

how to remove added item in cart?

i am trying make drag and drop shopping cart. By the help from some site on internet i am able to add the item in the cart and also it calculates the total price. But i am unable to remove a selected item fro the cart. I am very new to javascript and html5, so please help me..
the code is:
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var items = document.querySelectorAll("section.products ul li");
var cart = document.querySelectorAll("#cart ul")[0];
function updateCart(){
var total = 0.0;
var cart_items = document.querySelectorAll("#cart ul li")
for (var i = 0; i < cart_items.length; i++) {
var cart_item = cart_items[i];
var quantity = cart_item.getAttribute('data-quantity');
var price = cart_item.getAttribute('data-price');
var sub_total = parseFloat(quantity * parseFloat(price));
cart_item.querySelectorAll("span.sub-total")[0].innerHTML = " = " + sub_total.toFixed(2);
total += sub_total;
}
document.querySelectorAll("#cart span.total")[0].innerHTML = total.toFixed(2);
}
function addCartItem(item, id) {
var clone = item.cloneNode(true);
clone.setAttribute('data-id', id);
clone.setAttribute('data-quantity', 1);
var btn=document.createElement('BUTTON');
btn.className = 'remove-item';
var t=document.createTextNode("X");
btn.appendChild(t);
cart.appendChild(btn);
clone.removeAttribute('id');
fragment = document.createElement('span');
fragment.setAttribute('class', 'sub-total');
clone.appendChild(fragment);
cart.appendChild(clone);
$('#product').on('click','.remove-item',function(){
$(this).closest('li').remove();// remove the closest li item row
});
}
function updateCartItem(item){
var quantity = item.getAttribute('data-quantity');
quantity = parseInt(quantity) + 1
item.setAttribute('data-quantity', quantity);
var span = item.querySelectorAll('span.quantity');
span[0].innerHTML = ' x ' + quantity;
}
function onDrop(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var id = event.dataTransfer.getData("Text");
var item = document.getElementById(id);
var exists = document.querySelectorAll("#cart ul li[data-id='" + id + "']");
if(exists.length > 0){
alert("Already present");
} else {
addCartItem(item, id);
}
updateCart();
return false;
}
function onDragOver(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
return false;
}
addEvent(cart, 'drop', onDrop);
addEvent(cart, 'dragover', onDragOver);
function onDrag(event){
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.dropEffect = "move";
var target = event.target || event.srcElement;
var success = event.dataTransfer.setData('Text', target.id);
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.setAttribute("draggable", "true");
addEvent(item, 'dragstart', onDrag);
};
});
</script>
and
<section id="product">
<ul class="clear">
<li data-id="1">
<a href="#">
<img src="a.jpg" alt="">
<h3>item 1</h3>
<p>xyz</p>
</a>
</li>
</ul>
</secton>
and css is:
<style>
ul, li{
list-style: none;
margin: 0px;
padding: 0px;
cursor: pointer;
}
section#cart ul{
height: 200px;
overflow: auto;
background-color: #cccccc;
}
</style>
Add a close button to every cart item like
<input type="button" class="remove-item" value="X" />
Try this to remove the item-row,
$('#product').on('click','.remove-item',function(){
$(this).closest('li').remove();// remove the closest li item row
});
Then Try this to remove the item in the cart
$(".remove").click(function(e) {
pid = $(this).siblings("#checkIDinput:hidden").attr("value");
Or--------------------
$(".remove").click(function(e) {
pid = $(this).siblings("input:hidden").attr("value");

Categories

Resources