JS for loop to fill array - javascript

Good day all and happy b-lated new year
So I got a problem and I would rather not tie everything directly into an array and call it from there. Im building an old school chat based RPG and I have hit an issue with passing on the skills which are determined by the characters stats. Essentially what I am trying to do is this:
I have a bunch of buttons which represent a total of 72 skills:
<td><button type="button" onclick="" class="button" id="math">MATH</button></td>
which I would like to use their onclick event to pass both the skill name and skill rating to this targeted area of the page:
<td><input type="text" id="skill1" value="" readonly /></td>
<td><input type="text" id="skillRate1" value="" readonly /></td>
the skillRate(s) are reflected in their appropriate variables like so:
var math = (mem * 3) + (log * 2);
and ideally what will happen is I set each targeted recipient in an array as skill and skillRate respectively so that once all the skills are selected it is stored in the array and uploaded into the DB as such.
Originally I was thinking something along the lines of this:
function addSkill(){
var n = 0;
for (n = 0; n < 17; n++){
getElementById("skill" + n) = getElementById(this.id);
getElementById("skillRate" + n) = //figure out some way to turn this into the var for skillRate (getElementById(this.id));
}
}
I've been bumbling around with this for days now but cant seem to get anywhere and I would really rather not just put all the skills and their respective skillRates in an array unless I have to.
Any thoughts or suggestions as to how to accomplish this or maybe another approach altogether?
Thanks in advance!

If i understood you problem properly, maybe you can do it this way:
For html
<td>
<button type="button" data-skill="math" data-point="20" onclick="addSkill(this)" class="button" id="math">MATH</button>
</td>
For javascript
//Start your variables
var tagsSkills = []
var totalPoint = 0;
function addSkill(skill) {
var dataset = skill.dataset;
totalPoint += dataset.point; // Here you will sum the skill's point
tagsSkills.push(dataset.skill); // Add skill into array
}
Or maybe, instead you could use a map structure that store map[skill] to points. And, just with skill in the function, you will have the points just getting it from the map.

Not sure why you don't want array, they are your friends.
This code will build a table from array but only uses it for build, all the calculations are later taken from html.
This is vanilla js, could be easier/prettier with jQuery.
JS:
//This is just for building the table, you don't have to use it if you don't want array for some reason :S
var skillsArr = [{
firstSkillName: "Memory",
firstSkillValue: 15,
secondSkillName: "Logic",
secondSkillValue: 17
}, {
firstSkillName: "Dexterity",
firstSkillValue: 12,
secondSkillName: "Speedness",
secondSkillValue: 11
}];
var table = document.getElementById("tblSKills");
var tableBody = table.createTBody();
for (i = 0; i < skillsArr.length; i++) {
var row = tableBody.insertRow(i);
var cell = row.insertCell(0);
cell.innerHTML = skillsArr[i].firstSkillName + ": " + "<span>" + skillsArr[i].firstSkillValue + "</span>";
cell = row.insertCell(1);
cell.innerHTML = skillsArr[i].secondSkillName + ": " + " <span>" + skillsArr[i].secondSkillValue + "</span>";
cell = row.insertCell(2);
cell.innerHTML = "<button onclick='doMath(this)'>DO THE MATH</button>";
}
function doMath(currnetBtn) {
var currentRow = currnetBtn.parentElement.parentElement; //TD -> TR
var currentCells = currentRow.children;
var skill1 = document.getElementById("skill1");
var skill2 = document.getElementById("skill2");
var mathResult = document.getElementById("mathResult");
skill1.value = currentCells[0].innerText;
skill2.value = currentCells[1].innerText;
mathResult.value = (currentCells[0].children[0].innerText/1) * 3 + (currentCells[1].children[0].innerText/1) *2 ;//This is your *3 + *2 function or whatever you want.
//You can also make that each skill set will have its' own math function.
}
HTML:
<h1>
Welcome to my skill page!
</h1>
<h2>
Your results:
</h2>
<label id="lbl1"></label>
<input id="skill1" readonly />
<label id="lbl2"></label>
<input id="skill2" readonly />
<label>Result:</label>
<input id="mathResult" readonly />
<table id="tblSKills">
</table>
-- Fiddle --

Related

Concatenating numbers instead off adding them together

Having read for hours on the web and tried various things I am lost as to the answer to my problem. I want to be able to check a checkbox and get the value from an input box. ie If more than 1 checkbox is checked the values (both £100) would produce a sum of £200. I am getting "100100"!
My html table is produced with PHP with value '$price' from a mySQL database as a DECIMAL (10,2):
<html>
<table>
<tr>
<td><input name='payInvoice' type='checkbox' onchange='add()'></td>
<td><input id='amountToPay' value=$price></td>
</tr>
</table>
</html>
and javascript:
<script>
function add(){
var payOff = " "
document.getElementById('poff').value = "";
var payoff = document.getElementsByName("payInvoice");
for (var i=0; i<payoff.length; i++){
if (payoff[i].checked == true){
amount = document.getElementById("amountToPay");
$s = parseInt(amount.value);
payOff += ($s) ;
document.getElementById('poff').value = payOff;
}
}
}
</script>
Change var payOff = " " to var payOff = 0 and it will work.You are adding string to integers hence its not working.
So when you write payOff += $(s); you are actually doing payOff = (" " + interger) which is basically string concatenation hence you will always get a string back

How can I update the attributes of an HTML element inside a table cell?

I have a table which looks essentially like this
<!DOCTYPE html>
<html lang="en">
<body>
<table class="ui table" id="items">
<tbody>
<tr data-toggle="fieldset-entry">
<td><input id="items-0-quantity" name="items-0-quantity" type="text" value=""></td>
<td><input id="items-0-description" name="items-0-description" type="text" value=""></td>
</tr>
</body>
</html>
Using javascript, I'd like to have a button which adds a new row to the table, and I'd like the inputs in that new row to have id="items-1-xxx", and name="items-1-xxx, i.e. where there's a 0 in the original row I'd like a 1 in the new row.
I can make a new table row by cloning the old one, but I have not figured out how to modify the name and id attributes of the input.
Here's a sketch of what I've tried:
function cloneRow() {
var table = document.getElementById("items");
var original_row = table.rows[table.rows.length - 1];
var new_row = original_row.cloneNode(true);
// We have a new row and now we need to modify it as
// described in the question. The only way I've found
// is to grab the inner HTML:
var cell_contents = original_row.cells[0].innerHTML;
// Now we could do a bunch of string parsing and manipulations
// to increment the 0 to a 1 and stuff the modified HTML into
// new_row, but it seems there must be a better way.
// Finally insert the new row into the table.
original_row.parentNode.insertBefore(new_row, original_row.nextSibling);
}
What is the right way to update the input elements' id and name?
You could just build a new <td> and assign document.querySelectorAll('#items tr').length as the x in items-x-...:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length
, newitemQuantityText = 'items-' + itemcount + '-quantity'
, newitemDescriptionText = 'items-' + itemcount + '-description'
, newitem = document.createElement('tr')
, newitemQuantity = document.createElement('td')
, newitemDescription = document.createElement('td')
, newitemQuantityInput = document.createElement('input')
, newitemDescriptionInput = document.createElement('input');
newitemQuantityInput.id = newitemQuantityText;
newitemQuantityInput.name = newitemQuantityText;
newitemQuantity.appendChild(newitemQuantityInput);
newitemDescriptionInput.id = newitemDescriptionText;
newitemDescriptionInput.name = newitemDescriptionText;
newitemDescription.appendChild(newitemDescriptionInput);
newitem.appendChild(newitemQuantity);
newitem.appendChild(newitemDescription);
document.querySelector('#items').appendChild(newitem);
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items"></table>
However using good old innerHTML reads way better:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length;
items.innerHTML += '<tr><td>' +
'<input id="item-' + itemcount + '-quantity" name="item-' + itemcount + '-quantity">' +
'</td><td>' +
'<input id="item-' + itemcount + '-description" name="item-' + itemcount + '-description">' +
'</td></tr>';
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items">
</table>
You can separately reconstruct the node itself by using
createAttribute()
createElement()
Fiddle: http://jsfiddle.net/ztb9gq3d/1/
This is not the data oriented approach the question asks for, but a reasonably simple solution is
numRows = table.rows.length;
// Use a regexp so we can replace all instances of the number
// corresponding to what is currently the last table row.
var re = new RegExp((numRows - 1).toString(), "g")
for (var i = 0; i <= originalRow.cells.length - 1; i++) {
var originalHTML = originalRow.cells[i].innerHTML;
var newHTML = originalHTML.replace(re, numRows.toString());
newRow.cells[i].innerHTML = newHTML;
}
Obviously this only works if the number we replace doesn't exist elsewhere in the HTML string, so this is not a particularly good solution.
However, we could use a more complex regexp.
This solution does have the advantage that we don't need to hard-code anything except the parts we want to replace into the regexp.
Therefore, if the HTML in the table were to acquire additional parts in future development this solution will still work, up to the quality of the regexp as already mentioned.

Displaying multiple html text box values in an ascending order [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model

How to add and use a Div as a total calculator using Javascript?

I need to make a function which calculates the sum of a users input and compare it to a previously given value, returning the result to the user.
e.g. You previously said you eat 20 meals a week but you have currently listed 5 Dinners, 7 Lunches and 36 Breakfasts. This totals 48 meals.
So far I can read my inputs and add them to a variable as the respondent types it in, showing this in an already existing div. But I need to create a div to show it in for it's actual use. This is where I'm having problems as I can't get this code working.
Note I'm new to JS so some of my code might make no sense. This is everything I've got so far, the bit commented out is what is causing trouble, the rest (assuming I have a div ID'd as 'output') works fine:
<html>
<head>
<script>
var count = 0;
function summer() {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
count = num1+num2+num3;
// if(!document.getElementById("output")) {
// var newDiv = document.createElement('div');
// var divIdName = 'output';
// var myDiv = document.getElementById('buttoner');
// var content = document.createTextNode("")
// newDiv.setAttribute('id',divIdName);
// newDiv.appendChild(content);
// document.body.insertBefore(newDiv, myDiv)
// };
document.getElementById("output").innerHTML = "Your running total = "+count
};
</script>
</head>
<body>
<input type="text" id="number1" onKeyUp="summer()" name="number" />
<input type="text" id="number2" onKeyUp="summer()" name="number" />
<input type="text" id="number3" onKeyUp="summer()" name="number" />
<div id='Buttoner'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button>
</div>
<br>
</body>
</html>
Thanks!
edit: thought it might be worth noting that the 'buttoner' div is left over from a previous stage of experimenting and is now used as a placemarker for inserting the new div.
Your problem seems quite simple to me. If that is really all your HTML, your only problem is you don't have the output div.
You can solve this in some ways. Using pure JavaScript...
var output = document.createElement("div"); // Creates a <div> element
output.innerHTML = "Your running total = " + count;
document.body.appendChild(output); // Add the <div> to the end of the <body>
Another way is to put the output div in the HTML, this way you won't even need to change your script:
<div id="output"></div>
If you want the output not to be visible before the input, you can CSS it a little...
<div id="output" style="display: none;"></div>
And make it visible with Javascript whenever you want.
var output = document.getElementById('output');
output.style.display = 'block'; // or 'inline-block', or 'inline', etc. See what fits you better
As you're beginnning with Javascript, I'd recommend you start in the right path by reading on unobstrusive Javascript. I can update the answer with some unobstrusive JS if you want.
UPDATE: If you want to substitute the button div with the new output div, you can simply change the names from output to button / buttoner / whatever you want.
UPDATE 2: Seems like I didn't understand your question correctly. If you want to store the previous answer, you can do it in a variety of ways as well.
One is to store the current answer in a hidden field. For example...
<input type="hidden" id="prevAnswer" value="0" />
Then, in your Javascript, you can do it like this:
var prevAnswer = document.getElementById("prevAnswer")
var prevAnswerValue = parseFloat(prevAnswer.value) || 0;
output.innerHTML = "You previously said you eat " + prevAnswerValue + " meals a week but you have currently listed " + num1 + " Dinners, " + num2 + " Lunches and " + num3 + " Breakfasts. This totals " + count + " meals.";
prevAnswer.value = count;
So you will always have the Previous Answer whenever you calculate a new one.
Try this fiddle:
http://jsfiddle.net/Q65BT/
var pre =0;
var count = 0;
function summer(a) {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
if(a==1)
{
pre=count;
count = num1+num2+num3;
document.getElementById("output").innerHTML = "You previously said you eat "+pre+" meals a week but you have currently listed "+num1+" Dinners, "+num2+" Lunches and "+num3+" Breakfasts. This totals "+count+" meals.";
}
}
I'm not sure what behavior you are missing. When I uncomment that block, it seems to work fine. The new DIV is being created on the fly if it didn't already exist.
The code is wordier than necessary, but if as you say, you're a beginner, this is not a bad thing. Here's some possible clean-up:
if (!document.getElementById("output")) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'output');
var myDiv = document.getElementById('buttoner');
document.body.insertBefore(newDiv, myDiv)
};

Add line break to HTML from Js loop

I have a simple Js function that generates a list of random numbers based on how many the user wants. The function works fine, and logs fine, but it isn't displaying like I'd like it to. I'm new to Javascript, so I tried using the \n escape character, but it didn't do anything. Any help would be appreciated.
function generateIDs()
{
var num = document.getElementById('numberToGenerate').value;
var par = document.getElementById('numbers');
var button = document.getElementById('genButton');
button.disabled = true;
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id;
}
<form>
Auto-Generate <input type="text" name="number" id="numberToGenerate"/> IDs.
<button type="button" onclick="generateIDs()" id="genButton">Go!</button>
</form>
<p id="numbers">
</p>
\n doesn't mean much to a browser; use <br/> instead.
Example:
// snip
for (var x=0;x<num;x++)
{
var id = Math.floor((Math.random()*10000)+1);
par.innerHTML = id.toString() + '<br/>';
}
//snip
Note that this is going to overwrite the previous value on each iteration. You probably want this:
par.innerHTML += id.toString() + '<br/>';

Categories

Resources