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
Related
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 --
I have an app for making questionnaires. Users have index.php page where they create the questions and choose minimum number of answers, then they have process.php page where they can enter their answers or add more answers.
PROBLEM: When user clicks add more button, it creates textarea of the particular question but with the wrong name. The add more button should add a textarea and change its name according to the minimum of the defined textareas. So if you for ex. have 4 defined textareas in question2, the next textareas should be like odg25, odg26, odg27, odg28 etc...
The problem is in variable $k (process.php) - because it is not defined in addmore function, but I don't know how to pass somehow in this part of code to make it happen.
THIS IS THE TESTING LINK
INDEX.PHP
<input id="btntxt" type="submit" value="TEXT" onclick="addtxt();" /><br/><br/>
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
PROCESS.PHP
<script type="text/javascript">
<?php $chars = $_POST['chars']; ?>
function addmore(index) {
var textarea = document.createElement("textarea");
textarea.name = "odg" + index + //WHAT SHOULD I ADD HERE???;
textarea.rows = 3;
textarea.setAttribute('maxlength',<?php echo $chars ?>);
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
<body>
<?php
$bla = "";
$pitanje = $_POST['question'];
$length = count($_POST['question']);
$req = $_POST['req'];
$requiem = '';
$min = $_POST['min'];
$area = array("","","","","","","","","","","","","","","");
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
if(($min[$j])!="") {
for($k=1;$k<=$min[$j];$k++) {
$area[$j] .= '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea><br/>';}}
if(($min[$j])=="") {
$area[$j] = '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea>';}
$addmore = '<input type="button" name="more" value="Add more" onClick="addmore('.$j.');">';
$bla .= $j.') '.$pitanje[$j].'<br/>'.$area[$j].'<div id="inner'.$j.'"></div>'.$addmore.'<br/>';}}
echo $bla;
?>
FNCS.JS
var n = 1;
function addtxt() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var required = document.createElement("input");
required.type = "checkbox";
required.name = "req[" + n + "]";
var minimum = document.createElement("input");
minimum.type = "text";
minimum.name = "min[" + n + "]";
var div = document.createElement("div");
div.innerHTML = n + ". Question: " + "<br />" + textarea.outerHTML + "<br />" + "Required: " + required.outerHTML + "<br />" + "Min: " + minimum.outerHTML + "<br /><hr/><br/>";
document.getElementById("brain1").appendChild(div);
n++;
}
I did the same kind of dev.
I had a globalized counter (cpt) in the javascript is incremented by 1 each duplication
My variables were duplicated like this id = "foo_" + cpt.
I added a hidden field for the counter <input type="hidden" id = "cpt"> and its value was changed for each replication.
Php side, I recovered the counter and then a loop to iterate through all the duplicate fields.
// For example
$cpt = $_POST['cpt'];
for ($i = 1; $i <= $cpt; $i++) {
$foo[$i] = $_POST['foo_' . $i];
}
I hope it will help.
You're mixing JavaScript and PHP. PHP is doing some part of the question generation and then JavaScript has to pick up where it left off.
The problem with that approach is that you'll find you end up duplicating a lot of functionality.
The answer the quesiton WHAT SHOULD I ADD HERE??? is "odg" + $j + $k
If instead you start by doing:
var questions = <?php echo json_encode($_POST["question"]);?>;
You now have all your question data available in JavaScript. You can move the for loop from PHP to JavaScript and have j and k there.
What you're going to have to do is make $k able to be passed into process.php.
That is accomplished with something like this:
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input id="numRows" type="hidden" name="numRows" value="1"/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
notice I've added a new <input> element with the name "numRows" which will be passed via POST to process.php. I've given it an arbitrary default value of 1, you can set this however you wish.
Now, when a user clicks the "add more" button, within fncs.js do this:
document.getElementById("numRows").value++;
and finally, in your process.php you need to read in the value of this, as $k:
<?php $k = isset($_POST['numRows']) ? urldecode($_POST['numRows']) : 1; ?>
within process.php you may do as you wish, then, with that value $k.
You need to store last text area value in hidden variable and always increment that
first step: At start set value of hidden variable and your counter
'n' same
second step : at each step where you are adding new text area ,
overwrite the hidden value by new counter value of text area
Remember Textarea counter should be always fetched from hidden value
I think this may help you to solve your problem
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)
};
for ( i = 1; i <= NumOfText; i++ ) {
var ipBoxName="MyInput"+i;
var txtBoxAutoNumbering="<input type='text' name='textbx[]' id='TxtBx' style='width:50px;' value="+i+" /> ";
$('#NewlyCreatedSelectBoxes').append(txtBoxAutoNumbering);
var txtBox="<input type='text' name='textbx[]'/> "
$('#NewlyCreatedSelectBoxes').append(txtBox);
var Select_SelectionOptions="<select id='SelectOption'><option>Text_Box</option> <option>Text_Area</option><option>Radio_Button</option></select> ";
$('#NewlyCreatedSelectBoxes').append(Select_SelectionOptions);
var c = document.getElementById("TxtBx").value;
alert(c);
var Select_For_Multiple_Choices="<button type='button' onclick='ChildTxtBoxes()' id='Child_Btn'"+i+">Click for child selections</button><br><br>";
$('#NewlyCreatedSelectBoxes').append(Select_For_Multiple_Choices);
}
Here I have put an alert to print the value of the textbox represents by "var txtBoxAutoNumbering" variable. Bt it always prints 1 though it runs. y is that?
You are creating multiple elements with the same ID. This is invalid HTML. As a side effect, when you try to get them by ID, you will only get the first one you created.
Try the following instead:
var txtBoxAutoNumbering="<input type='text' name='textbx[]' id='TxtBx" + i +"' style='width:50px;' value="+i+" /> ";
And
var c=document.getElementById("TxtBx" + i).value;
I have this script
$('table#preview td.price').each(function(){
var price = parseInt($(this).html());
var total;
if(price == ''){
price = 0;
}
total += price;
alert(total);
});
What it does is get the column that has the class price then supposedly adds it all up.
However, all I get from this code is NaN. I don't get what's wrong with the code.
Please note the script if(price == ''). I've done this because initially there are no contents in the table.
Edit: Here the html
<table>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<tr>
<td>pen</td>
<td class="price>6</td>
<td>paper</td>
<td class="price>8</td>
</tr>
</table>
Try using the .text() method instead of .html() method, it should hopefully help get rid of the NaN errors. You'll want to declare the total outside the scope of each iteration so it doesn't get reset each time. Try giving this a go, I've simplified it slightly to also include a check against the number price:
var total = 0;
$('table#preview td.price').each(function()
{
var price = parseInt($(this).text());
if (!isNaN(price))
{
total += price;
}
});
alert('The total is: ' + total);
Update
Here's a jsFiddle. N.B. .html() should also work.