How to remove the uploaded image in any box? - javascript

My code is very long. I can not show you all here. I just show the javascript code only
My javascript like this :
<script type="text/javascript">
let current = 0;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-delete-'+i).click(function(){
current -= 1;
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+current).style.display = "none";
document.getElementById("thumbnail-upload-li-"+current).style.display = "";
document.getElementById("thumbnail-upload-li-"+(current+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(current+1)).style.display = "";
});
}
var editClicked = false;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-edit-'+i).click(function(){
editClicked = true;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-add-'+i).click(function(){
editClicked = false;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
var reader = new FileReader();
$('input[name="photo-'+i+'"]').change(function (e) {
let indexPhoto = i;
current += 1;
reader.onload = function(){
imageProducIsLoaded(indexPhoto);
};
reader.readAsDataURL(e.target.files[0]);
});
}
function imageProducIsLoaded(indexPhoto) {
$('#thumbnail-view-'+indexPhoto).attr('src', reader.result);
if (!editClicked) {
document.getElementById("thumbnail-upload-li-"+indexPhoto).style.display = "none";
document.getElementById("thumbnail-view-li-"+indexPhoto).style.display = "";
if((indexPhoto+1) < 5) {
document.getElementById("thumbnail-upload-li-"+(indexPhoto+1)).style.display = "";
document.getElementById("thumbnail-slot-li-"+(indexPhoto+1)).style.display = "none";
}
}
};
</script>
You can see my complete code and demo here : http://www.phpfiddle.org/main/code/adjv-sfuy
I use show hide to add, delete and edit image. If you look at the demo, it has worked. Images can be edited, deleted and added
But my problem is when the user does delete image
When user delete an image, the image on last box is deleted. Should be when user delete an image, then the image that I click its delete button is deleted
For example I input 5 image. When deleting image to 3, image to 3 deleted
I've been trying to modify the code for some days, but I have not found a solution
Is there anyone who can help me?

Use jquery features for doing complex things very simple.
<?php
if(isset($_POST['submit'])) {
echo "<pre>";
print_r($_FILES);
for($i=0;$i<count($_FILES);$i++) {
if($_FILES['photo-'.$i]['error'] == 0) {
$file_name = $_FILES['photo-'.$i]['name'];
$file_tmp =$_FILES['photo-'.$i]['tmp_name'];
move_uploaded_file($file_tmp,"img/".$file_name);
}
}
echo "</pre>";
}
?>
<style type="text/css">
.img-container{width:162px;height:142px;border:1px dashed #337ab7;float:left;margin-right:5px;position:relative;border-radius:5px}
.upload-add-product{position:absolute;display:block;margin:34% 42%}
.upload-add-product i{font-size:30px}
.img-container ul{list-style:none;bottom:0;position:absolute;width:100%;padding:0;margin:0;background-color:rgba(255,255,255,0.7)}
.img-container ul li{display:inline;padding:0;display:table-cell;width:1%;text-align:center;position:relative;padding:2px 0}
.img-container ul li:hover{background-color:#eee}
.img-container ul li a{color:red}
</style>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<form method="post" enctype="multipart/form-data">
<div class="images-area">
<?php
for($i=0;$i<5; $i++) { ?>
<div class="img-container" id="box<?php echo $i ?>" data-status="0" data-index="<?=$i?>">
<input type='file' name="photo-<?=$i?>" style="visibility: hidden;position:absolute;" id="upload-file<?=$i?>" class="upload-file"/>
<div class="image">
<?php if ($i == 0): ?>
<i class="fa fa-plus"></i>
<?php endif; ?>
</div>
</div>
<?php } ?>
</div>
<input type="submit" name="submit" value="submit">
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on('change',".upload-file",function () {
var $input = $(this);
var inputFiles = this.files;
if(inputFiles == undefined || inputFiles.length == 0) return;
var inputFile = inputFiles[0];
var i = parseInt($(this).closest('.img-container').attr('data-index'));
var reader = new FileReader();
reader.onload = function(event) {
// console.log($('#box'+i).find('img').length);
if($('#box'+i).find('img').length) {
$('#box'+i).find('img').attr('src',event.target.result);
} else {
var imgTmpl ='<img height="142" width="162" src='+event.target.result+'>'+
'<ul><li class="btn-click" onclick=\'$("#upload-file'+i+'").click()\'><i class="fa fa-pencil"></i></li>'+
'<li class="delete-button"><i class="fa fa-trash"></i></li></ul>';
$('#box'+i+' .image').html('');
$('#box'+i+' .image').append(imgTmpl);
$('#box'+i).attr('data-status',1);
$('#box'+(i+1)+' .image').html('</i>');
}
};
reader.onerror = function(event) {
alert("I AM ERROR: " + event.target.error.code);
};
reader.readAsDataURL(inputFile);
});
$(document).on('click','.delete-button',function(){
var i = $(this).closest('.img-container').attr('data-index');
$('#box'+i).remove();
$('.images-area').append('<div class="img-container" data-status="0"><input type="file" style="display:none" id="upload-file" class="upload-file"><div class="image"></div></div>');
var blank = 0;
$('.img-container').each(function(i){
$(this).attr({'id':'box'+i,'data-index':i});
$(this).find('.upload-file').attr({'id':'upload-file'+i,'name':'photo-'+i});
$(this).find('.btn-click').attr('onclick','$("#upload-file'+i+'").click()');
if(($(this).attr('data-status') == 0) && (blank == 0)) {
blank = i;
}
});
if($('.img-container').find('.upload-add-product').length == 0) {
$('#box'+blank+' .image').append('</i>');
}
});
</script>
I put efforts for understand your task..
See this it will help you..

Sorry, I was misunderstand.
Mayby you need a judgement after you delete an image that make sure the next image is not show.
$('#thumbnail-view-delete-'+i).click(function(){
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+i).style.display = "none";
document.getElementById("thumbnail-upload-li-"+i).style.display = "";
if(document.getElementById("thumbnail-view-li-"+(i+1)).style.display === "none"){
document.getElementById("thumbnail-upload-li-"+(i+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(i+1)).style.display = "";
}
});
This can descrease the messy.

I have found out your problem. Your delete function does not detect the number of photos currently uploaded but simply deletes the last one.
Added: current photo count, changed delete method to use current instead of 'i', increment count on upload and decrement count on delete.
<script type="text/javascript">
let current = 0;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-delete-'+i).click(function(){
current -= 1;
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+current).style.display = "none";
document.getElementById("thumbnail-upload-li-"+current).style.display = "";
document.getElementById("thumbnail-upload-li-"+(current+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(current+1)).style.display = "";
});
}
var editClicked = false;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-edit-'+i).click(function(){
editClicked = true;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-add-'+i).click(function(){
editClicked = false;
$('input[name="photo-'+i+'"]').click();
});
}
for(let i = 0; i < 5; i++) {
var reader = new FileReader();
$('input[name="photo-'+i+'"]').change(function (e) {
let indexPhoto = i;
current += 1;
reader.onload = function(){
imageProducIsLoaded(indexPhoto);
};
reader.readAsDataURL(e.target.files[0]);
});
}
function imageProducIsLoaded(indexPhoto) {
$('#thumbnail-view-'+indexPhoto).attr('src', reader.result);
if (!editClicked) {
document.getElementById("thumbnail-upload-li-"+indexPhoto).style.display = "none";
document.getElementById("thumbnail-view-li-"+indexPhoto).style.display = "";
if((indexPhoto+1) < 5) {
document.getElementById("thumbnail-upload-li-"+(indexPhoto+1)).style.display = "";
document.getElementById("thumbnail-slot-li-"+(indexPhoto+1)).style.display = "none";
}
}
};
</script>

Here's my answer: http://phpfiddle.org/main/code/0h1g-mvus
I just shift the images instead. You might need to do some changes to pass values or w/e.
let current = 0;
for(let i = 0; i < 5; i++) {
$('#thumbnail-view-delete-'+i).click(function(){
current -= 1;
$('input[name="photo-'+i+'"]').val('');
document.getElementById("thumbnail-view-li-"+current).style.display = "none";
document.getElementById("thumbnail-upload-li-"+current).style.display = "";
document.getElementById("thumbnail-upload-li-"+(current+1)).style.display = "none";
document.getElementById("thumbnail-slot-li-"+(current+1)).style.display = "";
shift_image(i);
});
}
function shift_image(start)
{
let finish = 4;
for (; start < finish - 1; start++)
{
let next = $('#thumbnail-view-'+(start+1)).attr('src');
$('#thumbnail-view-'+start).attr('src', next);
}
}

Related

HTML Div Element turns to null when I'm accessing it a 2nd time?

Here are the relevant bits of the client-side code:
function simpsonsShow(forest) {
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2); // simpsonsIndex is a function not shown here
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML =
document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
forest = forestGenerate(content);
simpsonsShow(forest);
});
document.getElementById("sim").appendChild(button);
});
});
When that simpsonsShow function is ran a second time, all of a sudden document.getElementById("simpsons") becomes null even though upon first try, it's a proper HTML Div Element.
Here are the relevant parts of the HTML:
<head>
<script src="sim.js"></script>
</head>
<body>
<div id="content">
<div id="intro">
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
</div><!--close id="content"-->
</body>
</html>
I've added the code snippet: The website works by pressing generate, then continually pressing generate. The error pops up once you press generate a 2nd time
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function () {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts, [emoji]: (counts[emoji] || 0) + 1 }),
{}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
<!doctype html>
<html>
<head>
<title>FOREST SIMULATOR</title>
<script src="sim.js"></script>
<link rel="stylesheet" href="base.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet" >
</head>
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet">
<body>
<div id="content">
<h1>FOREST SIMULATOR</h1>
<style>
.hidden{
display:none;
}
</style>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div><!--close id="content"-->
</body>
</html>
#simpsons is a child of #sim. The problem is in this code here:
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
It effectively removes all div children of #sim which don't have a pinned attribute. Try removing only divs after the first index, thereby keeping #simpsons (which is the first div inside #sim):
for (let i = 1; i < curr.length; i++) {
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
} else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function() {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts,
[emoji]: (counts[emoji] || 0) + 1
}), {}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function() {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function() {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 1; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
.hidden {
display: none;
}
<div id="content">
<h1>FOREST SIMULATOR</h1>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div>

How do i restrict the user add duplicates and specific file format

How can I achieve gmail style of file uploading. From the below code i can select multiple file and am displaying selected files with anchor tag. How can i avoid duplicate files and adding and How to restrict the user to select only pdf and doc file? i need to alert if user select duplicate or if user select other than doc or pdf
<div class="container">
<form id="fileupload" action="#" method="POST" enctype="multipart/form-data">
<div class="row files" id="files1">
<h2>Files 1</h2>
Browse <input type="file" name="files1" multiple />
<br />
<ul class="fileList"></ul>
</div>
</form>
</div>
var filesToUpload = [];
var output = [];
$.fn.fileUploader = function (filesToUpload) {
this.closest(".files").change(function (evt) {
for (var i = 0; i < evt.target.files.length; i++) {
var found = false;
for(var j = 0; j < filesToUpload.length; j++){
if(evt.target.files[i].name == filesToUpload[j].name){
found = true;
break;
}
}
if(found == false){
filesToUpload.push(evt.target.files[i]);
}
else{
alert("duplicate");
}
}
for (var i = 0; i < evt.target.files.length; i++) {
var file= evt.target.files[i];
var found = false;
for(var j = 0; j < filesToUpload.length; j++){
if(evt.target.files[i].name == filesToUpload[j].name){
found = true;
break;
}
}
if(found == false){
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\">X</a>";
output.push("&nbsp&nbsp&nbsp<li><strong>",file.name,"</strong>&nbsp",removeLink,"</li> ");
}
else{
alert("duplicate");
}
}
$(this).children(".fileList").append(output.join(""));
});
};
$(document).on("click",".removeFile", function(e){
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches FileName
// and get the index of the match
for(i = 0; i < filesToUpload.length; ++ i){
if(filesToUpload[i].name == fileName){
//console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
//console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).parent().remove();
});
$("#files1").fileUploader(filesToUpload);
$("#files2").fileUploader(filesToUpload);
$("#uploadBtn").click(function (e) {
e.preventDefault();
});
$.fn.fileUploader = function(filesToUpload) {
this.closest(".files").change(function(evt) {
var index;
for (var i = 0; i < evt.target.files.length; i++) {
index = filesToUpload.indexOf(evt.target.files[i]);
if (index > -1) {
filesToUpload.splice(index, 1);
}
}
for (i = 0; i < evt.target.files.length; i++) {
var filename = evt.target.files[i].name;
var valid_extensions = /(\.pdf|\.doc|\.docx)$/i;
if (valid_extensions.test(filename)) {
for (var i = 0; i < evt.target.files.length; i++) {
filesToUpload.push(evt.target.files[i]);
};
var output = [];
for (var i = 0, f; f = evt.target.files[i]; i++) {
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\""+ i + "\">Remove</a>";
output.push("<li><strong>", escape(f.name),"</strong> - ", removeLink,"</li> ");
}
$(this).children(".fileList").append(output.join(""));
} else {
alert('Invalid File');
return false;
}
}
});
};
var filesToUpload = [];
$(document).on("click", ".removeFile", function(e) {
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches
// FileName
// and get the index of the match
for (i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].name == fileName) {
// console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
// console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).parent().remove();
});
$("#files1").fileUploader(filesToUpload);
$("#files2").fileUploader(filesToUpload);
$("#uploadBtn").click(function(e) {
e.preventDefault();
});

I am trying to connect multiple functions and buttons together using js. and html. and I'm not sure what i'm missing

When I open the Html file in the browser, it shows that the two are connected properly but it wont output anything I type into the box.I just need it to output the function result depending on which button was pressed. Any help or advice is appreciated.
function reverseStr(s) {
var o = [];
for (var i = 0, len = s.length; i <= len; i++)
o.push(s.charAt(len - i));
return o.join('');
}
reverseStr("Hello");
var ch = "a";
var pattern =/a|e|i|o|u|y/i ;
isVowelR(ch, pattern);
function isVowelR(ch,pattern){
if(pattern.test(ch)){
return true;
}
else{return false}
}
function countVowles(str1)
{
var vowel_list = 'aeiouAEIOU';
var vcount = 0;
for(var x = 0; x < str1.length ; x++)
{
if (vowel_list.indexOf(str1[x]) !== -1)
{
vcount += 1;
}
}
return vcount;
}
console.log(countVowles(""));
var pattern = /[0-9]/;
function isDigit(regexp){
if(pattern.test(regexp)){
return true;
}
else{return false}
}
var main = function() {
document.getElementByld("#inpt").value;
//this keyword is set to the button that fired the event
console.log(this.id);
//dispatch on button id
if (this.id == "btn1")
document.querySelector("div").innerHTML = "You clicked Button1";
else if (this.id == "btn2")
document.querySelector("div").innerHTML = "You clicked Button2";
else if (this.id == "btn3")
document.querySelector("div").innerHTML = "You clicked Button3";
else
document.querySelector("div").innerHTML = "You Clicked Button4";
};
//2. register the onclick handlers after the DOM is complete
window.addEventListener("load", function() {
//select the buttons
var buttons = document.querySelectorAll("button");
//register the same handler for each button
for (var i = 0; i < buttons.length; ++i) {
buttons[i].addEventListener("click", main);
}
});
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' >
<title> Buttons Demo </title>
</head>
<body>
<h2>String Machine</h2>
<p>
Enter a String:
</p>
<input id= "inpt"> </input>
<button id="btn1">Reverse</button>
<button id="btn2">Vowel or no Vowel</button>
<button id="btn3">Count Vowels</button>
<button id="btn4">Digit or no Digit</button>
<br>
<hr style="width:23%; margin-left:0;">
<div id="outDiv"></div>
<script src="stringMach.js"></script>
</body>
</html>
This is working fine. Hope it'll helps
function reverseStr(s) {
var o = [];
for (var i = 0, len = s.length; i <= len; i++)
o.push(s.charAt(len - i));
return o.join('');
}
reverseStr("Hello");
var ch = "a";
var pattern =/a|e|i|o|u|y/i ;
isVowelR(ch, pattern);
function isVowelR(ch,pattern){
if(pattern.test(ch)){
return true;
}
else{ return false }
}
function countVowles(str1)
{
var vowel_list = 'aeiouAEIOU';
var vcount = 0;
for(var x = 0; x < str1.length ; x++)
{
if (vowel_list.indexOf(str1[x]) !== -1)
{
vcount += 1;
}
}
return vcount;
}
var pattern = /[0-9]/;
function isDigit(regexp){
if(pattern.test(regexp)){
return true;
}
else{return false}
}
var main = function() {
//this keyword is set to the button that fired the event
var str = document.getElementById('inpt').value;
var pattern =/a|e|i|o|u|y/i ;
var pattern2 = /[0-9]/;
console.log(this.id);
//dispatch on button id
if (this.id == "btn1")
document.querySelector("div").innerHTML = reverseStr(str);
else if (this.id == "btn2")
document.querySelector("div").innerHTML = isVowelR(str, pattern);
else if (this.id == "btn3")
document.querySelector("div").innerHTML = countVowles(str);
else
document.querySelector("div").innerHTML = "You Clicked Button4";
};
//2. register the onclick handlers after the DOM is complete
window.addEventListener("load", function() {
//select the buttons
var buttons = document.querySelectorAll("button");
//register the same handler for each button
for (var i = 0; i < buttons.length; ++i) {
buttons[i].addEventListener("click", main);
}
});
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' >
<title> Buttons Demo </title>
</head>
<body>
<h2>String Machine</h2>
<p>
Enter a String:
</p>
<input id= "inpt"> </input>
<button id="btn1">Reverse</button>
<button id="btn2">Vowel or no Vowel</button>
<button id="btn3">Count Vowels</button>
<button id="btn4">Digit or no Digit</button>
<br>
<hr style="width:23%; margin-left:0;">
<div id="outDiv"></div>
<script src="stringMach.js"></script>
</body>
</html>

How To Change Image in Array Based on Textbox input in JavaScript?

I'm trying to make my page so a user can type a number value between 1 and 200 to get to whichever image they want to view. I've played around with the code, but I can't seem to get anything to work. Below is my code that I've tried to do this with. What am I doing wrong?
Edit: New Code:
`
<html>
<head>
<title></title>
</head>
<body style="background-color: teal;">
<form>
<center>
<div width="50%" style="width: 50%;">
<div id="main" align="middle">
<img src="page1.jpg" alt="" id="mainImg" height="90%">
</div>
<div id="imglist">
<a href="javascript:previousImage('mainImg')"><img src="previous.png" alt=""
align="left"></a>
<input id="myid" name="myid" size="3" type="text"></input>
<img src="next.png" alt="" align="right">
<script>
var imgArray = new Array();
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
function previousImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === 0){
document.getElementById(element).src = imgArray[imgArray.length-1].src;
break;
}
else{
document.getElementById(element).src = imgArray[i-1].src;
break;
}
}
}
}
window.onload = function() {
var elm = document.getElementById("myid"),
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200 {
img.src = "page" + num + ".jpg";
}
}
}
}
</script>
</div>
</div>
</center>
</form>
</body>
</html>
Perhaps you mean for this:
if (this.value.length === 1,2,3) {
to be this:
if (this.value.length <= 3) {
In addition, I think you want to be converting the whole input value to a number, not using the individual keycodes.
I might suggest this different/simpler way of doing this that is much more DRY (don't repeat yourself):
// preload images
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
window.onload = function() {
var elm = document.getElementById("myid");
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200) {
img.src = "page" + num + ".jpg";
}
}
}
}
Working Demo: http://jsfiddle.net/jfriend00/4dqbP/
Summary of changes:
Preload images in a loop rather than copied code
Construct image names dynamically
Make img variable to a local variable rather than an implicit global with var in front of it
Check to see if the input field is empty
Use parseInt() to parse the value of the input field into a number
Range check the parsed number
If in valid range, then construct the image name using that number

checking for duplicate file while uploading multiple file in Javascript

I used the below code to upload multiple files. Its working absolutely fine but as i need to check that the file which i am uploading is duplicate or not, i am facing one problem in that. I created one function called checkDuplicate for that and calling it inside the function. But the problem is that the for loop is looping double the size of the array. I don't know why it is so. Please kindly help me if anyone has any idea.
Here is the Javascript
<script type="text/javascript">
function MultiSelector(list_target, max) {
this.list_target = list_target;
this.count = 0;
this.id = 0;
if (max) {
this.max = max;
} else {
this.max = -1;
};
this.addElement = function(element) {
if (element.tagName == 'INPUT' && element.type == 'file') {
element.name = 'file_' + this.id++;
element.multi_selector = this;
element.onchange = function() {
var new_element = document.createElement('input');
new_element.type = 'file';
this.parentNode.insertBefore(new_element, this);
this.multi_selector.addElement(new_element);
this.multi_selector.addListRow(this);
this.style.position = 'absolute';
this.style.left = '-1000px';
};
if (this.max != -1 && this.count >= this.max) {
element.disabled = true;
}
;
this.count++;
this.current_element = element;
}
else {
alert('Error: not a file input element');
}
;
};
this.addListRow = function(element) {
var new_row = document.createElement('div');
var new_row_button = document.createElement('img');
new_row_button.setAttribute("src","<%=request.getContextPath()%>/images/deletei.gif");
new_row_button.onclick = function() {
this.parentNode.element.parentNode.removeChild(this.parentNode.element);
this.parentNode.parentNode.removeChild(this.parentNode);
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
if(checkDuplicate(element)) {
new_row.element = element;
new_row.innerHTML = element.value + " ";
new_row.appendChild(new_row_button);
this.list_target.appendChild(new_row);
}
};
};
function checkDuplicate(element) {
var arr = new Array();
var i = 0,dup=0;
//alert(new_row.element = element.value);
if(dup==0) {
arr[i++] = element.value;
dup=1;
}
alert("Length ==> "+ arr.length);
for ( var j = 0; j < arr.length; j++) {
alert("Name ==> " + arr[j]);
if(arr[j] == element.value && j>=1) {
alert("Duplicate");
} else {
alert("Not Duplicate");
arr[i++] = element.value;
}
}
}
</script>
Here is the HTML
<body>
<!-- This is the form -->
<form enctype="multipart/form-data" action=""method="post">
<input id="my_file_element" type="file" name="file_1">
<input type="submit">
<br/>
<br/>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
</form>
<script>
var multi_selector = new MultiSelector(document
.getElementById('files_list'), 15);
multi_selector.addElement(document.getElementById('my_file_element'));
</script>
</body>
</html>
because you have the arr[i++] = element.value; in the last line, and j < arr.length in the for, so every time the array.lenght gets bigger and bigger.
change the for line to these two lines:
var len = arr.length;
for ( var j = 0; j < len; j++) {

Categories