Why is my elseif statement running everytime - javascript

I am building a form sending function in JavaScript, and I have run into a problem where it executes an else if statement every time. Here is my script:
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
The problem being that the else if(el != "#submit"){} runs even when the id in question is "#submit". Does anyone know why this doesn't work?
To help, here is my php document, and the rest of the form constructer:
php:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<?php if(!$_GET): ?>
<form id="form1">
<input type="text" id="input1" name="name"/>
<br>
<select id="dropdown" name="color">
<option id="null" name="null"></option>
<option id="opt1" name="blue">blue</option>
<option id="opt2" name="yellow">yellow</option>
</select>
<br>
<button type="submit" id="submit" name="submit"onclick="form1.submit()">Submit data</button>
</form>
<script src="http://charlie/form.js"></script>
<script>
var form1 = new form("form1");
form1.setElements();
form1.logElements();
</script>
<?php elseif(!(isset($_GET['name']) || isset($_GET['color']))): ?>
<p style="color:red">ERROR! form.js failed</p>
<?php else: ?>
<p><?= $_GET['name'] ?></p>
<p><?= $_GET['color'] ?></p>
<?php endif; ?>
</body>
</html>
form constructer:
function form(id) {
this.id = "#" + id;
this.url = window.location.href;
this.elements = [];
this.names = [];
this.setElements = function() {
var elements = [],names = [],children = $(this.id).children();
for(var i = 0; i < children.length; i++) {
var childid = children[i].id;
if(childid)
{
elements.push('#' + childid);
}
}
this.elements = elements;
for(var e in this.elements) {
names.push($(this.elements[e]).attr('name'));
}
this.names = names;
};
this.logElements = function() {
for(var e in this.elements) {
console.log(this.elements[e]);
}
for(var n in this.names) {
console.log(this.names[n]);
}
};
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
}

Turning my comment into an answer with some code. The "in" operator in Javascript iterates over properties not the elements at each index. To make your current code work, change the code to the following:
var el;
var elementCount = this.elements.length;
for (var i = 0; i < elementCount; i++) {
el = this.elements[i];
This will produce the expected behavior.

The for...in loop is the cause. el tkaes the values 0, 1, 2 ...you need to compare this.elements[el] instead of el :
if(this.elements[el] == "#dropdown") ...
else if(this.elements[el] != "#submit") {
...

Related

Reload the table along with as button get clicked

I'm working on code that I got via watching YouTube, It's an HR staff clock in and Clock out records, I've added additionally a table data in the HTML but It does not reload the table as the buttons are clicked ( we have to refresh the page to get the new records in the table), I searched for some articles and fount out this was helpful but I'm having some trouble to configure it. can I get some help to get this working?
My code
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('TimeTracker');
}
function getEmployees() {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var employeeSheet = ss.getSheetByName("EMPLOYEES");
var getLastRow = employeeSheet.getLastRow();
return employeeSheet.getRange(2, 1, getLastRow - 1, 1).getValues();
}
function clockIn(employee) {
//DEFINE ALL ACTIVE SHEETS
var ss = SpreadsheetApp.getActiveSpreadsheet();
//DEFINE MAIN SHEET
var mainSheet = ss.getSheetByName("MAIN");
//LAST ROW ON MAIN SHEET
var lastRow = mainSheet.getLastRow();
//Define Return Variables
var return_date = '';
var error = 'SUCCESS';
var return_array = [];
for (var j = 2; j <= lastRow; j++)
{
// CHECK CLOCK IN
if(employee == mainSheet.getRange(j, 1).getValue() && mainSheet.getRange(j,3).getValue() == '')
{
error = 'Need to Clock Out before Clocking In';
return_array.push([error, return_date, employee]);
return return_array;
}
}
var new_date = new Date();
return_date = getDate(new_date);
// ADD CLOCK IN RECORD
mainSheet.getRange(lastRow+1,1).setValue(employee)
.setFontSize(12);
mainSheet.getRange(lastRow+1,2).setValue(new_date)
.setNumberFormat("MM/dd/yyyy hh:mm:ss am/pm")
.setHorizontalAlignment("left")
.setFontSize(12);
return_array.push([error, return_date, employee]);
return return_array;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function getDate(date_in)
{
var currentDate = date_in;
var currentMonth = currentDate.getMonth()+1;
var currentYear = currentDate.getFullYear();
var currentHours = (addZero(currentDate.getHours()) > 12) ? addZero(currentDate.getHours()) - 12 : addZero(currentDate.getHours());
var currentMinutes = addZero(currentDate.getMinutes());
var currentSeconds = addZero(currentDate.getSeconds());
var suffix = (addZero(currentDate.getHours()) >= 12)? 'PM' : 'AM';
var date = currentMonth.toString() + '/' + currentDate.getDate().toString() + '/' +
currentYear.toString() + ' ' + currentHours.toString() + ':' +
currentMinutes.toString() + ':' + currentSeconds.toString() + ' ' + suffix;
return date;
}
function clockOut(employee) {
//DEFINE ALL ACTIVE SHEETS
var ss = SpreadsheetApp.getActiveSpreadsheet();
//DEFINE MAIN SHEET
var mainSheet = ss.getSheetByName("MAIN");
//LAST ROW ON MAIN SHEET
var lastRow = mainSheet.getLastRow();
var foundRecord = false;
var new_date = new Date();
var return_date = getDate(new_date);
var error = 'SUCCESS';
var return_array = [];
for (var j = 2; j <= lastRow; j++)
{
// FIND CLOCK IN RECORD
if(employee == mainSheet.getRange(j, 1).getValue() && mainSheet.getRange(j,3).getValue() == '')
{
// UPDATE CLOCK IN RECORD
mainSheet.getRange(j,3)
.setValue(new_date)
.setNumberFormat("MM/dd/yyyy hh:mm:ss am/pm")
.setHorizontalAlignment("left")
.setFontSize(12);
var totalTime = (mainSheet.getRange(j,3).getValue() - mainSheet.getRange(j,2).getValue()) /(60*60*1000);
mainSheet.getRange(j,4).setValue(totalTime.toFixed(2))
.setNumberFormat("#0.00")
.setHorizontalAlignment("left")
.setFontSize(12);
foundRecord = true;
}
}
// IF NO CLOCK IN RECORD
if(foundRecord == false)
{
return_array.push(['Need to Clock In First', '', employee]);
return return_array;
}
// CALL TOTAL HOURS
TotalHours();
return_array.push([error, return_date, employee]);
return return_array;
}
function TotalHours()
{
//DEFINE ALL ACTIVE SHEETS
var ss = SpreadsheetApp.getActiveSpreadsheet();
//DEFINE MAIN SHEET
var mainSheet = ss.getSheetByName("MAIN");
//LAST ROW ON MAIN SHEET
var lastRow = mainSheet.getLastRow();
//DEFINE ARRAY
var totals = [];
//LOOP THROUGH ALL RATES
for (var j = 2; j <= lastRow; j++)
{
var rate = mainSheet.getRange(j, 4).getValue();
var name = mainSheet.getRange(j, 1).getValue();
var foundRecord = false;
for(var i = 0; i < totals.length; i++)
{
//FOUND RECORD ADD TO TOTAL
if(name == totals[i][0] && rate != '')
{
totals[i][1] = totals[i][1] + rate;
foundRecord = true;
}
}
//ADD NEW RECORD, EXISTING RECORD NOT FOUND
if(foundRecord == false && rate != '')
{
totals.push([name, rate]);
}
}
//CLEAR DATA
mainSheet.getRange("F5:G1000").clear();
//DISPLAY TOTALS
for(var i = 0; i < totals.length; i++)
{
mainSheet.getRange(2+i,6).setValue(totals[i][0]).setFontSize(12);
mainSheet.getRange(2+i,7).setValue(totals[i][1]).setFontSize(12);
}
}
//Send Table to HTML
function doGet() {
return HtmlService
.createTemplateFromFile('TimeTracker')
.evaluate();
}
//Table Data
function getData() {
const headerColumns = 5; // In your case, the number of header columns is 5.
const sheet = SpreadsheetApp.openById('15Sb-g71H6-7PPey3aQROo-oCx_ULKQq2a5kIUeLEmNY').getSheetByName("TODAY");
const values = sheet.getRange(1, 1, sheet.getLastRow(), headerColumns).getDisplayValues();
console.log(values)
return values;
}
MY HTML out put
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
getEmployees();
});
function getEmployees()
{
google.script.run.withSuccessHandler(function(ar)
{
var employeeSelect = document.getElementById("employee");
console.log(ar);
let option = document.createElement("option");
option.value = "";
option.text = "";
employeeSelect.appendChild(option);
ar.forEach(function(item, index)
{
let option = document.createElement("option");
var employee = item[0];
option.value = item[0];
option.text = item[0];
employeeSelect.appendChild(option);
});
}).getEmployees();
};
function ClockIn()
{
$('#message').html("");
var employee = document.getElementById("employee").value;
if(employee != '')
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
ar.forEach(function(item, index)
{
if(item[0] == 'SUCCESS')
{
var message = item[2] + ' Clocked in at ' + item[1];
$('#message').html(message);
document.getElementById("message").className = "alert alert-primary";
}
else
{
var message = item[2] + ' ' + item[0];
$('#message').html(message);
document.getElementById("message").className = "alert alert-warning";
}
});
}).clockIn(employee);
}
}
function ClockOut()
{
$('#message').html("");
var employee = document.getElementById("employee").value;
if(employee != '')
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
ar.forEach(function(item, index)
{
if(item[0] == 'SUCCESS')
{
var message = item[2] + ' Clocked out at ' + item[1];
$('#message').html(message);
document.getElementById("message").className = "alert alert-primary";
}
else
{
var message = item[2] + ' ' + item[0];
$('#message').html(message);
document.getElementById("message").className = "alert alert-warning";
}
});
}).clockOut(employee);
}
}
</script>
</head>
<body>
<div class="container">
<div style="padding: 10px;" >
<h1>WORK LOG</h1><br>
<form>
<div class="form-row">
<div class="form-group col-md-4">
<label for="employee">Employee</label>
<select class="form-control" id="employee">
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="button" value="Clock In" id="clockin" class="btn btn-primary" onclick="ClockIn()" />
<input type="button" value="Clock Out" id="clockout" class="btn btn-primary" onclick="ClockOut()" /><br><br>
<div class="alert alert-primary" role="alert" id="message">
</div>
</div>
</div>
</form>
</div>
<table class="table">
<? var [header, ...data] = getData(); ?>
<thead class="thead-dark"><tr>
<? for (var j = 0; j < header.length; j++) { ?>
<th><?= header[j] ?></th>
<? } ?>
</tr></thead>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</div>
</body>
</html>
[1]: https://stackoverflow.com/questions/45864415/button-action-to-retrieve-data-from-spreadsheet-using-google-app-script
So the reason that you code is not working is because your not actually calling getData() on server side when either clockin or clockout buttons are clicked.

javascript check onchange function on dynamic element

I created an HTML array with some tr lines which need to be hidden by default and when user check the checkbox, the element is showed.
I have a Javascript function to show html element when checkbox is checked. It works but not when I use a loop.
I need that checkbox1 works on tr1, checkbox2 on tr2 ...
The PHP code which creates elements
<?php
if (isset($_SESSION['wordsListArray']))
{
$length = count($_SESSION['wordsListArray']);
for ($i = 0; $i < $length; $i++)
{
echo '<tr><td>' . htmlspecialchars($_SESSION['wordsListArray'][$i]) . '</td><td>' . htmlspecialchars($_SESSION['translationsListArray'][$i]) . '</td><td><input type="checkbox" id="checkboxId' . ($i+1) . '"/></td></tr>';
echo '<tr class="trHide" id="trHide' . ($i+1) . '"><td><input type="text" placeholder=' . $_SESSION['personel_language_array'][0] . '></td><td><input type="text" name="other" placeholder=' . $_SESSION['personel_language_array'][1] . '></td><td><button type="submit">Edit</button><button type="submit">Erase</button></td></tr>';
}
}
?>
This Javascript works but only on one element (getElementById is unique), but I need a loop to use different Id (trHide1, trHide2 ...)
var tr = document.getElementById("trHide1");
var check = document.getElementById("checkboxId1");
check.onchange = function() {
if(check.checked)
{
tr.style.display = 'contents';
}
else
{
tr.style.display = 'none';
}
};
I try this loop but it doesn't work.
for (var i = 1; i <= lengthWordList; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
var tr = document.getElementById(trId);
var check = document.getElementById(checkId);
check.onchange = function() {
if(check.checked)
{
tr.style.display = 'contents';
}
else
{
tr.style.display = 'none';
}
};
}
Your code does not work because it overwrites the event and the selector
This could be worth it
var elemento=[];
for (var i = 1; i <= 2; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
console.log(trId);
elemento.push(
{
tr:document.getElementById(trId),
check:document.getElementById(checkId),
event:function(){}
}
);
console.log(elemento[(i-1)]);
elemento[(i-1)].check.setAttribute('elemento',(i-1));
elemento[(i-1)].event = elemento[(i-1)].check.onchange = function() {
var valor = this.getAttribute('elemento');
if(elemento[valor].check.checked)
{
elemento[valor].tr.style.display = 'contents';
}
else
{
elemento[valor].tr.style.display = 'none';
}
};
}
var elemento=[];
for (var i = 1; i <= 2; i++)
{
var trId = 'trHide' + i;
var checkId = 'checkboxId' + i;
console.log(trId);
elemento.push(
{
tr:document.getElementById(trId),
check:document.getElementById(checkId),
event:function(){}
}
);
console.log(elemento[(i-1)]);
elemento[(i-1)].check.setAttribute('elemento',(i-1));
elemento[(i-1)].event = elemento[(i-1)].check.onchange = function() {
var valor = this.getAttribute('elemento');
if(elemento[valor].check.checked)
{
elemento[valor].tr.style.display = 'contents';
}
else
{
elemento[valor].tr.style.display = 'none';
}
};
}
<table>
<tr id="trHide1" style="display:none"><td>AAAA</td></tr>
<tr id="trHide2" style="display:none"><td>BBBB</td></tr>
</table>
<input type="checkbox" id="checkboxId1">
<input type="checkbox" id="checkboxId2">

Scroll to bottom when new content is added to div

How can I get the chat to scroll to bottom when new content is sent into the chat? I'm trying to add something like this:
$('#what do I have to put here?').animate({scrollTop: $('#and here?').prop("scrollHeight")}, 200);
but I can't make it work (I have no idea where in the code to place it).
Thanks!
This is an important part of the code... Maybe I have to add it here (but I don't know how or where):
<script type="text/javascript">
var _answerBot = new answerBot();
function keypressInput(sender, event) {
if (event.which == 13) {
document.getElementById('subcontent').innerHTML += _answerBot.processInput(sender.value);
sender.value = '';
}
}
</script>
This is a separate scripts.js file:
var answerBot = function () {
var _this = this;
_this.processInput = function (text) {
updateUrl(text);
var _result = "<p class='answerbot-input'>" + text + "</p>";
text = text.replace(new RegExp("[ ]{2,}", "g"), " ");
var _words = text.toLowerCase().split(" ");
var _answers = [];
var _title = "";
if (_words.length === 0 || _words.toString() === '') { //if the input is empty
_answers = _this.specialContext.emptyInput;
_title = _this.specialContext.emptyInput;
} else {
var _possibleAnswers = findMatches(_words);
if (_possibleAnswers.length === 0) { //if no answer found
_answers = _this.specialContext.wrongInput;
_title = _this.specialContext.wrongInput;
}
if (_possibleAnswers.length == 1) { //context recognized
_answers = _this.answers[_possibleAnswers[0]].values;
_title = _this.answers[_possibleAnswers[0]].description;
}
if (_possibleAnswers.length > 1) {
_result += formatText(_this.specialContext.rephrase, _this.specialContext.rephrase);
for (var i = 0; i < _possibleAnswers.length; i++) {
_result += formatText(_this.answers[_possibleAnswers[i]].description, _this.answers[_possibleAnswers[i]].description);
}
}
}
if (_answers.length > 0) {
var _rand = Math.floor((Math.random() - 0.001) * _answers.length);
_result += formatText(_answers[_rand], _title);
}
return _result;
};
function formatText(text, title) {
return "<p class=\'answerbot-ai\' title=\'" + title + "\'>" + text + "</p>";
}
function findMatches(words) {
var foundKeywords = [];
var _possibleAnswers = [];
for (var i = 0; i < _this.keywords.length; i++) {
foundKeywords[i] = 0;
for (var j = 0; j < words.length; j++) {
if (_this.keywords[i].keys.indexOf(words[j]) >= 0) {
foundKeywords[i]++;
if (foundKeywords[i] == _this.keywords[i].keys.length) {
return [_this.keywords[i].value];
}
}
}
if (foundKeywords[i] * 2 > _this.keywords[i].keys.length) {
_possibleAnswers.push(_this.keywords[i].value);
}
}
return _possibleAnswers.filter(function (elem, pos) {
return _possibleAnswers.indexOf(elem) == pos;
});
}
function updateUrl(text){
history.pushState(null, null, "#question=" + encodeURIComponent(text));
if(typeof ga === "function")//google analytics
ga('send', 'event', 'question', text);
}
};
function AddMessage() {
var $message = $("<p>").text("message");
var $messages = $("#messages");
$messages.append($message);
$messages.animate({
scrollTop: $messages.prop("scrollHeight")
});
}
#messages {
border: 1px solid #000;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
<div id="messages"></div>
<button onClick="AddMessage()">Add Message</button>
</div>

submitting csv form data with jquery then showing as json

I am a beginner in jquery so this may be stupid.
I want to take csv data from the user and transform it into json. Found a nice library but don't quite understand how the submitting is done in jquery.
For instance if I have a view
<script type="text/javascript" src="<?php echo site_url('public/js/jquery.js') ?>" ></script>
<script type="text/javascript" src="<?php echo site_url('javascript/main.js') ?>" ></script>
<div id="message"><p></p></div>
<form id="convertForm" name="convertForm" onsubmit="return false; ">
CSV<br /><textarea id="csv" name="csv" rows="10" cols="60"></textarea><br /><br />
JSON<br /><textarea id="json" name="json" rows="10" cols="60" readonly="readonly"></textarea><br /><br />
<input type="button" value="Convert" id="submitButton"/> <input type="reset" />
</form>
And the main.js file
function parseCSVLine (line)
{
line = line.split(',');
for (var i = 0; i < line.length; i++)
{
var chunk = line[i].replace(/^[\s]*|[\s]*$/g, "");
var quote = "";
if (chunk.charAt(0) == '"' || chunk.charAt(0) == "'") quote = chunk.charAt(0);
if (quote != "" && chunk.charAt(chunk.length - 1) == quote) quote = "";
if (quote != "")
{
var j = i + 1;
if (j < line.length) chunk = line[j].replace(/^[\s]*|[\s]*$/g, "");
while (j < line.length && chunk.charAt(chunk.length - 1) != quote)
{
line[i] += ',' + line[j];
line.splice(j, 1);
chunk = line[j].replace(/[\s]*$/g, "");
}
if (j < line.length)
{
line[i] += ',' + line[j];
line.splice(j, 1);
}
}
}
for (var i = 0; i < line.length; i++)
{
// remove leading/trailing whitespace
line[i] = line[i].replace(/^[\s]*|[\s]*$/g, "");
// remove leading/trailing quotes
if (line[i].charAt(0) == '"') line[i] = line[i].replace(/^"|"$/g, "");
else if (line[i].charAt(0) == "'") line[i] = line[i].replace(/^'|'$/g, "");
}
return line;
}
function csvToJson ()
{
var message = "";
var error = false;
var f = document.forms["convertForm"];
var csvText = f.elements["csv"].value;
var jsonText = "";
setMessage(message, error);
if (csvText == "") { error = true; message = "Enter CSV text below."; }
if (!error)
{
benchmarkStart = new Date();
csvRows = csvText.split(/[\r\n]/g); // split into rows
// get rid of empty rows
for (var i = 0; i < csvRows.length; i++)
{
if (csvRows[i].replace(/^[\s]*|[\s]*$/g, '') == "")
{
csvRows.splice(i, 1);
i--;
}
}
if (csvRows.length < 2) { error = true; message = "The CSV text MUST have a header row!"; }
else
{
objArr = [];
for (var i = 0; i < csvRows.length; i++)
{
csvRows[i] = parseCSVLine(csvRows[i]);
}
benchmarkParseEnd = new Date();
for (var i = 1; i < csvRows.length; i++)
{
if (csvRows[i].length > 0) objArr.push({});
for (var j = 0; j < csvRows[i].length; j++)
{
objArr[i - 1][csvRows[0][j]] = csvRows[i][j];
}
}
benchmarkObjEnd = new Date();
jsonText = JSON.stringify(objArr, null, "\t");
benchmarkJsonEnd = new Date();
f.elements["json"].value = jsonText;
benchmarkPopulateEnd = new Date();
message = getBenchmarkResults();
}
}
setMessage(message, error);
}
$(document).ready(function(){
$('#submitButton').on('click', function(){
console.log('i got here');
csvToJson;
});
});
This works perfectly but console.log is never shown.
And if I try to do something like return the jsonText from the csvToJson function and then append it to the second textarea, that doesn't work either.
function csvToJson ()
{
//same code here
return jsonText;
}
$(document).ready(function(){
$('#submitButton').on('click', function(){
console.log('i got here');
jsont = csvToJson();
$("#json").val(jsonT);
});
It's clearly something I don't get about submitting. Should I use jquery .submit() function ?
You are missing brackets when calling csvToJson inside the click handler.
Change:
$('#submitButton').on('click', function(){
csvToJson;
});
TO
$('#submitButton').on('click', function(){
csvToJson();
});
DEMO: http://jsfiddle.net/MRmJM/1/
One note: If CSV is separated by semi-colon (not uncommon) , parser code fails to create proper object

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