going through substr with loop and then want to identify the index - javascript

Im trying to get the index number of corresponding characters in a string.
I mean a loop does make it possible to treat characters in a string like an 'array' of characters with the string method charAt() and indexOf(), right?
here's the code:
/** ****** WINDOW ONLOAD EVENT HANDLER **************** */
window.onload = function(){
// DOM elements
var theButton = document.getElementById('theButton');
var form = document.formISBN;
var numberField = document.getElementById('theInput')
theButton.onclick = function(){
var number = numberField.value;
console.log(number)
controlNr = calculControlNr(number);
// console.log(controlNr);
}
}
function calculControlNr(number) {
number = number.replace(' ','','g');
number = number.replace('-','','g');
var sum = 0;
var sumEven = 0;
var sumUneven = 0;
var factor = 3;
var numberExtract = number.substr(0,11);
console.log(numberExtract.length)
for (var i = 0; i < numberExtract.length; i++) {
console.log(numberExtract.indexOf(numberExtract.charAt(i)));
}
}

How about
var numberExtract = number.split('');
console.log(numberExtract.length)
for (var i = 0; i < numberExtract.length; i++) {
if (i==11) break; // you only wanted the first 11?
console.log(i+':'+numberExtract[i]);
}
But your code does work anyway.
Here is what I did to test it
<script>
/** ****** WINDOW ONLOAD EVENT HANDLER **************** */
window.onload = function(){
// DOM elements
var theButton = document.getElementById('theButton');
var form = document.formISBN;
var numberField = document.getElementById('theInput')
theButton.onclick = function(){
var number = numberField.value;
alert(number)
controlNr = calculControlNr(number);
// alert(controlNr);
}
}
function calculControlNr(number) {
number = number.replace(' ','','g');
number = number.replace('-','','g');
var sum = 0;
var sumEven = 0;
var sumUneven = 0;
var factor = 3;
var numberExtract = number.substr(0,11);
alert(numberExtract.length+':'+numberExtract);
for (var i = 0; i < numberExtract.length; i++) {
alert(i+':'+numberExtract.indexOf(numberExtract.charAt(i)));
}
}
</script>
<form name="formISBN">
<input id="theInput" type="text" value="01234567890-A A" />
<input id="theButton" type="button" value="click"/>
</form>

Related

JS select correct line in select list

I am using this JS code to do some magic. Working perfect to get a variabele and remove unwanted text and display the correct text in a text field.
values 2 or 3 or 5 or 7 etc. in <input type="text" id="calc_dikte[0][]" name="calc_dikte[]" value="">
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
if(isNaN(elems_1_split_2[0])) { elems_2[i].value = ''; }
else { elems_2[i].value = parseFloat(elems_1_split_2[0]); }
}
}
}
So this works, but now the form field has changed from text to select like:
<select id="calc_dikte[0][]" name="calc_dikte[]">
<option value="">
<option value="2|2000">2</option>
<option value="3|2000">3</option>
<option value="5|2000">5</option>
<option value="7|2000">7</option>
</select>
Therefore I have changed my JS code (with some tips from here) to:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var sel = elems_2[i];
var val = parseFloat(elems_1_split_2[0]);
for(var m=0, n=sel.options.length; m<n; m++)
{
if(sel.options[i].innerHTML === val)
{
sel.selectedIndex = m;
break;
}
}
}
}
}
But this is not working, no item is selected in the select list, no errors are shown.
Please help me out change to a working code to have the correct line selected. It should not select on the value but in the text between the ><
option value="5|2000">5</option
If I check with
for(var m=0, n=sel.options.length; m<n; m++) {
alert('sel = '+sel.options[i].innerHTML+'\nval = '+val);
}
I see that val is correct. But sel is just the number as used in $i so 0 1 2
You are using a strict equals operator to compare a Number (parseFloat) agains .innerHTML, which is always a string.
Convert sel.options[i].innerHTML to a Number aswell:
if (parseFloat(sel.options[i].innerHTML) === val) {
sel.selectedIndex = m;
break;
}
If you want to filter out invalid numbers (NaNs), use !isNaN(val) aswell.
Code to get this working:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var val = parseFloat(elems_1_split_2[0]);
var sel = elems_2[i];
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++)
{
if (opt.text == val)
{
sel.selectedIndex = j;
break;
}
}
}
}
}

js Page Freezing on from .length?

This function is freezing my page.
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
}
However, when I remove this it runs just fine.
modeArr.length = array.length;
modeCounter.length = array.length;
Here is all of my code:
<html>
<head>
</head>
<body>
<p> Please enter a series of numbers, each separated by a new line.<br><p>
<textarea id="myTextArea" rows = "7" cols = "50"></textarea><br>
<button onclick="processData()">Done</button>
<p id = "mean"></p>
<p id = "median"></p>
<p id = "count"></p>
<p id = "summation"></p>
<p id = "mode"></p>
<p id = "variance"></p>
<p id = "sd"></p>
<script type = "text/javascript">
var mean = 0;
var median = 0;
var count = length;
var mode = 0;
var variance = 0;
var standard_deviation = 0;
var meanOutput = document.getElementById('mean');
var medianOutput = document.getElementById('median');
var modeOutput = document.getElementById('mode');
var countOutput = document.getElementById('count');
var summationOutput = document.getElementById('summation');
var varianceOutput = document.getElementById('variance');
var sdOutput = document.getElementById('sd');
function processData()
{
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
var sum = findSum(arrayOfLines);
findMean(arrayOfLines, sum);
findMedian(arrayOfLines);
findMode(arrayOfLines);
findVariance(arrayOfLines);
findStandardDeviation(arrayOfLines);
findVariance(arrayOfLines);
}
function findSum (array)
{
var count = array.length;
var sum = 0;
for (var a = 0; a < array.length; a++)
{
sum += parseInt(array[a]);
}
countOutput.innerHTML = "Count: " + array.length;
summationOutput.innerHTML = "Sum: " + JSON.stringify(sum);
return sum;
}
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
for (var a = 0; a < array.length; a++)
{
for (var b = 0; b < modeArr.length; b++)
{
if (modeArr[a] == modeArr[b])
{
modeCounter[a]++;
}
if (a == 0)
{
b--;
}
}
modeArr[a] = array[a];
}
modeOutput.innerHTML = "Mode: ";
}
function findMean (array, sum)
{
mean = sum/array.length;
meanOutput.innerHTML = "Mean: " + mean.toPrecision(2);
}
function findMedian (array)
{
for(var i=0; i < array.length; i++)
{
array[i] = +array[i];
}
var sortedArrayOfLines = array.sort(function(a, b){return a - b});
if (array.length % 2 == 1)
{
median = sortedArrayOfLines[((array.length - 1)/2)]
}
else
{
median = (sortedArrayOfLines[array.length/2] + sortedArrayOfLines[(array.length/2)+1])/2
}
medianOutput.innerHTML = "Median: " + median;
}
function findVariance (array)
{
var mean = mean(array);
return mean(array.map(function(num)
{
varianceOutput.innerHTML = Math.pow(num - mean, 2);
}));
}
function findStandardDeviation (array)
{
medianOutput.innerHTML = Math.sqrt(variance(array));
}
</script>
</body>
</html>
So the issue isn't the length it's a infinite loop.
The problem is this bit of code
if (a == 0)
{
b--;
}
This is inside the following loop with b as the iterator. See below.
for (var b = 0; b < modeArr.length; b++)
a is set to zero by the outer loop. Thus a==0 is always true inside the inner loop. b will never increase only decrease. Thus this is a infinite loop because b will never be greater than modeArr.length.
So I would consider revising the function, below is a example of a possible candidate for a mode function:
Get the element with the highest occurrence in an array

how to add checkboxes in cells of first column of HTML table?

I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});

Number of checked checkboxes

How to rewrite this code from jQuery to vanilla JavaScript? I need to see how many checkboxes are checked. The problem is I do not know how to remove unchecked checkboxes from the total score.
$(function () {
var countChecked = function () {
var n = $("input:checked").length;
$(".output").text(n);
};
countChecked();
$("input[type=checkbox]").on("click", countChecked);
});
What should I do next?
var box = document.querySelectorAll('form input');
var par = document.querySelector('.output');
var great = 0;
for (var i = 0; i < box.length; i++) {
box[i].addEventListener('click', countIt);
function countIt() {
for (var i = 0; i < box.length; i++) {
if ( box[i].checked ) {
great++
par.innerHTML = great;
return
}
}
}
}
You need to reset the great variable each time you count (for example by moving it inside the countIt function).
var box = document.querySelectorAll('form input');
var par = document.querySelector('.output');
function countIt() {
var great = 0;
for (var i = 0; i < box.length; i++) {
if (box[i].checked) {
great++;
}
}
par.innerHTML = great;
}
for (var i = 0; i < box.length; i++) {
box[i].addEventListener('click', countIt);
}
You can also move the countIt function definition out of the loop and the same with innerHTML setting.

Input Button onclick event not firing

I'm fairly new to JavaScript and trying to build a simple photoviewer, slideshow application. I probably have errors/wrong practices in code that I don't know about yet. The event on slideshow button fires and I can see the output in the console, however the event on the random slide show button does not fire.
HTML5 snippet
<form>
<div id="controls">
<input type="button" id="slideshow" value="Slide Show" />
<input type="button" id="randomSlideshow" value="Random Slide Show" />
</div>
</form>
<script src="js/PhotoViewer.js"></script>
</body>
JS snippet
var photosArrayGlobal = new Array();
var photoIndexGlobal = 0;
var displayGlobal;
window.onload = main;
function main() {
"use strict";
document.getElementById("slideshow").onclick = getArrayPhotosNames;
document.getElementById("randomSlideshow").onclick = randomize(photosArrayGlobal);
displayGlobal = document.getElementById("myImage");
document.getElementById("nextSlide").onclick = function () {
displayGlobal.setAttribute("src", photosArrayGlobal[1]); //Test value, image 2
};
}
function getArrayPhotosNames() {
var folderName = document.getElementById("photoFolder").value;
var commonName = document.getElementById("commonName").value;
var startNum = document.getElementById("startNum").value;
var endNum = document.getElementById("endNum").value;
var j = 0;
if (startNum > endNum) {
alert("Invalid Numbers");
}
var nameArray = new Array();
for (var i = startNum; i <= endNum; i++) {
nameArray[j] = folderName + commonName + i + ".jpg";
j++;
}
photosArrayGlobal = nameArray.slice();
console.log(photosArrayGlobal);
return nameArray;
}
function randomize(dataArray) {
var i = dataArray.length;
var j, tempi, tempj;
if (i === 0) {
return false;
}
while (--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = dataArray[i];
tempj = dataArray[j];
dataArray[i] = tempj;
dataArray[j] = tempi;
}
console.log(dataArray);
}
The onclick handler is expecting a function, but you're passing it the value returned from the randomize() function (which happens to be undefined). Change it to the following:
document.getElementById("randomSlideshow").onclick = function() {
randomize(photosArrayGlobal);
};

Categories