I'm working on a DnD character creator and am trying to increase certain ability scores based on race. I have a checkbox input next to every race that looks like so:
<td>
<input
type="checkbox"
id="dragonbornRace"
onchange="updateRace();"
/>
</td>
<td>Dragonborn</td>
I also already have a section for ability score that looks like this:
<td>
<input
type="number"
value="10"
id="strScore"
onchange="updateMods()"
/>
</td>
My goal is to make it so that when dragonborn checkbox is checked, the strength increases by 2. So far I have this code, but it doesn't seem to work:
function updateRace() {
var strScore = document.getElementById("strScore").value;
if (document.getElementById("dragonbornRace").checked == true) {
strScore = strScore + 2;
}
}
When I go to test, nothing occurs when I check the box. I am probably missing something obvious, but any help would be appreciated!
The reason is that you need to assign the new score value to strScore elememt.
Also,you need to pay attention to use strScore = Number(strScore) + 2; to get the expected result
function updateRace() {
var scoreEle = document.getElementById("strScore")
var strScore = scoreEle.value;
if (document.getElementById("dragonbornRace").checked == true) {
strScore = Number(strScore) + 2;
scoreEle.value = strScore;
}
}
function updateMods(){
}
<table>
<tr>
<td>
<input
type="checkbox"
id="dragonbornRace"
onchange="updateRace();"
/>
</td>
<td>Dragonborn</td>
<td>
<input
type="number"
value="10"
id="strScore"
onchange="updateMods()"
/>
</td>
</tr>
<table>
Related
I am trying to create an interface of a website which has a varying price dependent on whether check boxes are checked and which has a default value if none are selected.
The varying value is in a table which has the id 'Level1Price' which I want to default to a value of '£5.11' if neither of the two check boxes are checked and the value to chage if either one or both are selected and where the two chekc boxes on their own would hold a different value each.
The two check boxes have the id's 'partner' and 'children'. When no checkboxes are checked (for the purpose of this demonstartion) the value of 'Level1Price in the table should be 5.
If just the 'partner' checkbox is checked the value of 'Level1Price' is 10.
If just the 'children' checkbox is checked the value of 'Level1Price' is 12.
If both checkboxes are checked the value of 'Level1Price' is 20.
var partner = document.getElementById("partner");
var children = document.getElementById("children");
function calc()
if (!partner.checked && !children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 5;
} else if (partner.checked && !children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 10;
} else if (!partner.checked && children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 12;
} else if (partner.checked && children.checked)
{
document.getElementById('Level1Price')element.innerHTML = 20;
}
This is the code that I thought would work and i'm struggling. I apologies if I have made rookie mistakes i'm quite new to this and couldn't find any working resolutions anywhere.
Thanks in advance.
These are the chekcboxes that I want to help change the vale in the table.
<div class="addition">
<label for="partner">+ Partner:</label>
<input type="checkbox" name="partner" id="partner" value="partner" required>
</div>
<div class="addition">
<label for="children">+ Children:</label>
<input type="checkbox" name="children" id="children" value="children" required>
</div>
</div>
This is the Table data I want to be able to populate
<tr>
<td scope=col id="Level1Price" value="5.11"> <b></b> <br/> per month</td>
<td scope=col id="Level2Price" value="9.97"> <b></b> <br/> per month</td>
<td scope=col id="Level3Price" value="14.06"> <b></b> <br/> per month</td>
</tr>
Is it possible to automatically update without the need for a 'calculate' button?
Provided your HTML looks like:
<span id="Level1Price"></span>
then:
document.getElementById('Level1Price').innerHTML = 20;
will result in your HTML being:
<span id="Level1Price">20</span>
Basically you just have a syntax problem (remove the erroneous 'element' text).
There is a small syntax error in your code. for better understanding, I have attached a fully functional code to meet your requirement.
Kindly refer the following code.
var partner = document.getElementById("partner");
var children = document.getElementById("children");
function calc() {
var val = 5;
if (partner.checked && !children.checked) {
val = 10;
} else if (!partner.checked && children.checked) {
val = 12;
} else if (partner.checked && children.checked) {
val = 20;
}
document.getElementById('Level1Price').innerHTML = val;
}
Partner: <input type="checkbox" id="partner" /> <br /> Children: <input type="checkbox" id="children" /> <br /> Level1 Price:
<span id="Level1Price"></span>
<br />
<button onClick="calc()">Calculate</button>
If still you find any issue or have any doubt feel free to comment, I will update my answer. TIA
I got a web page with some input controls, p.e. for a subtraction.
<table>
<tr>
<td><b>Value 1</b></td>
<td />
<td><b>Value 2</b></td>
<td><b>Result</b></td>
</tr>
<tr>
<td>
<%-- step="0.01" because of Firefox-browser --%>
<input type="number" id="value11" oninput="SubtractionWithParameters(document.getElementById('value11').value, document.getElementById('value21').value, 'result', 2)" step="0.01" />
</td>
<td> - </td>
<td>
<input type="number" id="value21" oninput="SubtractionWithParameters(document.getElementById('value11').value, document.getElementById('value21').value, 'result', 2)" step="0.01" />
</td>
<td>
<input type="number" id="result" step="0.01" />
</td>
</tr>
</table>
For the subtraction i defined the JavaScript function SubtractionWithParameters which calls the function Subtraction.
While entering numbers, dots and/or commas in the input controls "value11" and "value21" the function SubtractionWithParameters is called and calculates the result at once.
//Subtracts the given parameters and displays the result in the input-Control with the given controlname.
function SubtractionWithParameters(value1, value2, resultControlName, decimalNumber) {
decimalNumber = typeof decimalNumber == 'undefined' ? 0 : decimalNumber;
document.getElementById(resultControlName).value = Subtraction(value1, value2).toFixed(decimalNumber);
}
//Subtracts the given parameters and returns the result.
function Subtraction(value1, value2) {
if (isNaN(value1) || value1 == "") { value1 = 0; }
if (isNaN(value2) || value2 == "") { value2 = 0; }
var result = parseFloat(value1) - parseFloat(value2);
return result;
}
Now the problem is that IE and Firefox expecting different inputs for a floatnumber.
IE: 0.36 (with dot)
Firefox: 0,36 (with comma)
When i use Firefox and input in one of my input controls a floatnumber which contains a dot, nothing happens.
How can i handle this in my function Subtraction?
Thanks in advance!
Thanks a lot! Adding ".replace(',','.')" when giving the values to the function helps.
I have a row in a table that can be duplicated by javascript. In the first row I have a javascript code that makes a calculation.
After duplicating a new row the calc javascript is not working for the new row..
What i do wrong?
table row:
<table class="Parameter" id="new">
<form action="ProjectParameterNewRecord.php" method="post">
<tr>
<td>
<input type="text" id="Parameters" name="TypeOfOut" />
</td>
<td>
<?php include "ExchangeRates.php"?>
</td>
</td>
<td>
<input id="Cost" type="number" value="" class="ee105" name="Cost" onchange="changeCost()">
</td>
<td>
<input id="Amount" type="number" value="" class="ee105" name="Amount" onchange="changeAmount()">
</td>
<td><span id="minisum" name="minisum" onchange="changeminisum()"></span>
</td>
<td id="system">
<input type="hidden" id="ParameterID" name="ParameterID"></input>
</td>
<td id="system">
<input type="hidden" id="ProjectID" name="ProjectID" value="3"></input>
</td>
<td>
<input type="submit" value="Submit">
</td>
</form>
</tr>
</table>
code to create a new row:
<script>
var counter = 1;
jQuery('img.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery(' <tr class="Parameters" id="AA"><td><input type="text" id="Parameters" name="TypeOfOut"/></td><td><select id="Unit" type="text" value=" " class="ee105" name="Unit" onchange="changeUnit(this.value)"><option value="2">KM</option><option value="4">euro</option><option value="3">$</option><option value="25">WorkHour</option><option value="3">dollar</option><option value="25">WorkHour</option> </select</td></td><td><input id="Cost" type="number" value="" class="ee105" name="Cost" onchange="changeCost()"></td><td><input id="Amount" type="number" value="" class="ee105" name="Amount" onchange="changeAmount()"></td><td><span id="minisum" name="minisum" onchange="changeminisum()"></span></td><td id="system"><input type="hidden" id="ParameterID" name="ParameterID' + counter +'"></input></td><td id="system"><input type="hidden" id="ProjectID" name="ProjectID" value="3"></input></td><td><input type="submit" value="Submit"></td></tr>');
jQuery('table.Parameter#new').append(newRow);
});
</script>
javascript code to calculate:
function CalcUnitValue() {
var U = document.getElementById("Unit").value;
var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
document.getElementById("minisum").innerHTML = SUM;
document.getElementById("minisum").readOnly = true;
}
function changeCost() {
var C = document.getElementById("Cost").value;
var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
document.getElementById("minisum").innerHTML = SUM;
document.getElementById("minisum").readOnly = true;
}
function changeAmount() {
var C = document.getElementById("Amount").value;
var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
document.getElementById("minisum").innerHTML = SUM;
document.getElementById("minisum").readOnly = true;
}
function changeUnit() {
var C = document.getElementById("Amount").value;
var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
document.getElementById("minisum").innerHTML = SUM;
document.getElementById("minisum").readOnly = true;
}
function minisum() {
var SUM = -1 * ((((($('#Amount').val())) * (((($('#Cost').val())) * (($('#Unit').val())))))));
return alert(document.getElementById('minisuminput').innerHTML);
thank you :)
Your HTML is invalid. You have an extra closing </td> in the middle. You also need to put the form outside the table.
You can't have duplicate IDs in a HTML page and expect to reference anything except the first one. Use classes instead.
Don't use inline event handlers with jQuery. Use delegated jQuery handlers if you have dynamically added elements.
Use an element hidden in the page to hold your template. If you store it in the HTML, and not code, you would have noticed your </select> was missing and replaced by an extra </td>.
You mix JavaScript selectors with jQuery. Just stick to jQuery selectors. They are shorter.
None of the extra parenthesis are required for a * b * c * d equations.
inputs and img elements are meant to be self-closing, not have end tags.
All your calculations are exactly the same, so reuse the code.
Get into the habit on using consistent case (upper/lower/mixed) for variables and classes.
Use delegated event handlers like this:
$(document).on('change', '.cost,.amount,.unit,.parameters', function() {
var $tr = $(this).closest('tr');
var sum = -1 * $('.Amount', $tr).val() * $('.cost', $tr).val() * $('.Unit', $tr).val();
$(".minisum", $tr).html(sum);
}
Re templating: you can store your template row in a dummy script block, with unknown type (I use text/template) and it will be ignored by the browser.
e.g.
<script id="template" type="text/template">
<tr class="Parameters" id="AA">
<td>
<input type="text" class="Parameters" name="TypeOfOut" />
</td>
<td>
<select class="Unit ee105" type="text" value=" " name="Unit">
<option value="2">KM</option>
<option value="4">euro</option>
<option value="3">$</option>
<option value="25">WorkHour</option>
<option value="3">dollar</option>
<option value="25">WorkHour</option>
</select>
</td>
<td>
<input class="cost" type="number" value="" name="Cost">
</td>
<td>
<input class="amount ee105" type="number" value="" name="Amount">
</td>
<td><span class="minisum" name="minisum"></span></td>
<td class="system">
<input type="hidden" class="ParameterID" name="ParameterID{counter}" />
</td>
<td class="system">
<input type="hidden" class="ProjectID" name="ProjectID" value="3" />
</td>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</script>
You will note a {counter} placeholder where you wanted to insert a new value. Use it as the HTML source to create new rows.
e.g.
$('table.Parameter#new').append($('#template').html().replace('{counter}', counter));
JSFiddle to play with ( most of this functional): https://jsfiddle.net/TrueBlueAussie/33e9ptgu/
It looks like your problem is coming from having duplicate ids. When there are duplicate ids, the behavior of document.getElementById() is undefined. Each browser will try to do something reasonable, but there's no way to know which element will be returned (though it's usually the first element).
One option is to change the duplicated ids to class, and then when creating a new row, give the row it's own unique id using your counter:
var newRow = jQuery(' <tr class="Parameters" id="' + counter + '"><td>.....</td></tr> ');
This will allow you to access whichever row you want for calculation, as well as it's children using jquery:
Instead of $('#Cost') or document.getElementById("minisum"), use $('#' + [number of rowid]).find('.Cost'); or $('#' + [number of rowid]).find('.minisum');
A couple of other tips:
To get the value of an <input> into your functions, simply pass it as a parameter like so: onchange="changeCost(value)". Now you can delete 3 of your 4 identical functions as well as remove the first line of the remaining one.
You don't need closing </input> tags (see here)
There are two </td> tags on your second column
Make sure you have correct tag nesting on your </tr> and </form> tags
I need to implement Google Analytics (Universal/analytics.js) on a 20-something part AJAX-based questionnaire. The questionnaire works something like a choose-your-own-adventure, whereas the follow-up questions are all determined by the preceding answers.
Each input has a name and an ID. I'm interested in pulling the value from this field and setting it as a global variable in a dataLayer. Everything has a unique ID and Name, which I've started collecting in a database.
Here's an example of the HTML:
<table id="ctl00_ContentPlaceHolder1_2_Table1" class="CompSSRadio" cellpadding="1" cellspacing="1">
<tr>
<td class="CompSSRadioLabel">
</td>
</tr>
<tr>
<td class="CompSSRadioResponses">
<table id="ctl00_ContentPlaceHolder1_2_1_48_1" class="CompSSRadioResponses" border="0">
<tr>
<td><input id="ctl00_ContentPlaceHolder1_2_1_48_1_0" type="radio" name="ctl00$ContentPlaceHolder1$2$1_48_1" value="4" /><label for="ctl00_ContentPlaceHolder1_2_1_48_1_0"><SPAN style="FONT-FAMILY: Museo 500"><SPAN style="FONT-SIZE: 14pt"><SPAN style="FONT-FAMILY: Museo 500"></SPAN>Test answer 1</SPAN></SPAN></label></td>
</tr><tr>
<td><input id="ctl00_ContentPlaceHolder1_2_1_48_1_1" type="radio" name="ctl00$ContentPlaceHolder1$2$1_48_1" value="5" /><label for="ctl00_ContentPlaceHolder1_2_1_48_1_1"><SPAN style="FONT-FAMILY: Museo 500"><SPAN style="FONT-SIZE: 14pt"><SPAN style="FONT-FAMILY: Museo 500"></SPAN>Test answer 2</SPAN></SPAN></label></td>
</tr>
</table>
</td>
</tr>
</table>
Here is the "next" button:
<input type="image" name="ctl00$ContentPlaceHolder1$btnNext2" id="ctl00_ContentPlaceHolder1_btnNext2" src="../App_Themes/Images/Right.gif" onclick="javascript: pageTracker._trackPageview('//forward.html');window.document.getElementById('ctl00_ContentPlaceHolder1_btnNext').disabled=true;window.document.getElementById('ctl00_ContentPlaceHolder1_btnNext2').disabled=true;__doPostBack('ctl00$ContentPlaceHolder1$btnNext2','');" style="border-width:0px;" />
And here is a script which does something with the form info:
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
I don't know if I need to hook into that or anything, since that's what's submitting information. Obviously I'm clueless. I feel like this is a fairly simple task, it's just my lack of javascript knowledge preventing me from crafting the necessary script.
Thanks ahead of time!
IF you are using radios to select one of multiple values, all radio elements must have the same name. For example, if you have:
<input type="radio" name="sex" value="Male" id="radio_male">
<label for="radio_male">Male</label>
<input type="radio" name="sex" value="Female" id="radio_female">
<label for="radio_female">Female</label>
You will only be able to select "Male" or "Female", but not both.
Taking that in consideration, the way to access the selected value, in Javascript, should be:
var elements = document.getElementsByName("sex");
for (i = 0; i < elements.length; i++) {
var el = elements[i];
if ( el.checked ) {
alert("Checked value: " + el.value);
break; // Because only one radio from the group will be checked, there's no point in checking the rest of them, if there are more
}
}
About Data Layer, I have no clue, but it sounds like you are having problems getting the values, if I'm understanding it well.
If you're open to jQuery, an even simpler method would be:
var dataObj = {};
// Get the name / value pair of the checked radio button
jQuery('input:checked').each(
function() {
dataObj[$(this).attr("name")] = $(this).val();
}
);
etc.
There's several techniques you could use to move through the fields in order. With a bit more context in the question (as in what the behavior is from one question to the next - can you get the next element ID from your ajax call, for example?), a more robust answer could get you pointed in the right direction.
I have a table which is generated from data from a datbase. It might have 3 rows and 2 cells.
Each cell has a checkbox in it and 2 hidden form fields.
So, a typical row might look like this:
<tr>
<td>
<input type="checkbox" id="Assign" onclick="setchanged(this);">
<input type="hidden" id="hfChanged" value="0">
<input type="hidden" id="hfAgentID value="272">
</td>
<td>
<input type="checkbox" id="Assign" onclick="setchanged(this);">
<input type="hidden" id="hfChanged" value="0">
<input type="hidden" id="hfAgentID value="324">
</td>
</tr>
The requirement is - when a checkbox is clicked, it should set the value of the hfChanged hidden field in the same cell to 1.
This works in Internet Explorer:
function setchanged(me)
{
me.parentElement.all("hfChanged").value = 1;
}
How can I set the value of hfChanged in Standards Compliant browsers like Firefox or Chrome?
Use repeating classes instead of IDs
<tr>
<td>
<input type="checkbox" class="Assign" onclick="setchanged(this);">
<input type="hidden" class="hfChanged" value="0">
<input type="hidden" class="hfAgentID value="272">
</td>
<td>
<input type="checkbox" class="Assign" onclick="setchanged(this);">
<input type="hidden" class="hfChanged" value="0">
<input type="hidden" class="hfAgentID value="324">
</td>
</tr>
Then change your function to select by class name, and iterate the result.
function setchanged(me) {
var changed = me.parentNode.querySelectorAll(".hfChanged");
for (var i = 0; i < changed.length; i++) {
changed[i].value = 1;
}
}
The .querySelectorAll method will not work in IE6/7 if that matters to you. If it does, it's not hard to adjust a little for greater compatibility.
I see now that there's only one in the same cell. In that case, you can do this instead.
function setchanged(me) {
me.parentNode.querySelector(".hfChanged").value = 1;
}
You can use the following function to find out the next element as given in this answer
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
Working demo here.
Code:
function setchanged(me){
next(me).value = me.checked == true ? 1 : 0;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
This code is not tested, but could give you a starting point.
$("input[type=checkbox]").change(function(){
$(this).siblings(".hfChanged").prop("value", this.checked ? 1 : 0);
});
Note: Change id to class.