javascript getting reference to control in same cell of table - javascript

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.

Related

Increasing number in number input from checking a box in another?

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>

How can I set default and change price with checkboxes?

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

Javascript works in IE 8, but not Firefox 30

The below function does what I want it to in IE 8 but not Firefox 30. The intent is that checking the skill box should enable the user to modify the quantity textbox, and that unchecking it should restore the original value and make it readonly again.
function updateQuantity(refNum) {
var quantity = 'quantity' + refNum;
var startQuantity = 'startQuantity' + refNum;
var skill = 'skill' + refNum;
if (!document.getElementById(skill).checked){
document.getElementById(quantity).disabled = true;
document.getElementById(quantity).readOnly = true;
document.getElementById(quantity).style.color = "rgb(192,192,192)";
document.getElementById(quantity).value = document.getElementById(startQuantity).value;
} else {
document.getElementById(quantity).disabled = false;
document.getElementById(quantity).readOnly = false;
document.getElementById(quantity).style.color = "rgb(0,0,0)";
}
}
Here is an HTML snippet that exercises the functions.
<tr><td>Toughness</td>
<td></td>
<td>10 ^ (100 total)</td>
<td><input type="checkbox" name="skill8" value="Toughness" onclick="updateQuantity(8);updateTotal(8);">
<input style="color:rgb(192,192,192);" disabled readonly type="text" name="quantity8" maxlength="2" size="2" value="4" onclick="updateTotal(8);">
<input type="hidden" name="startQuantity8" value="4"></td></tr>
<tr style="background:rgb(80,30,30);"><td>Light Armor</td>
<td></td>
<td>20</td>
<td><input type="checkbox" name="skill9" value="Light Armor" onclick="updateQuantity(9);updateTotal(9);">
<input style="color:rgb(192,192,192);" disabled readonly type="text" name="quantity9" maxlength="2" size="2" value="1" onclick="updateTotal(9);">
<input type="hidden" name="startQuantity9" value="1"></td></tr>
I've tried moving the script definition to the end of the section, but that doesn't resolve the problem. I'm getting the error in the Firefox debugger that document.getElementById(skill) is null when I'm trying to evaluate it in the if statement. Any thoughts?
Well, Firefox is correct, there is no element with such an ID. From the MSDN documentation:
In IE7 Standards mode and previous modes, this method performs a case-insensitive match on both the ID and NAME attributes, which might produce unexpected results. For more information, see Defining Document Compatibility.
And look at your HTML, that seems what is happening:
<input type="checkbox" name="skill8" ... />
Possible solutions:
Add an id attribute to all the elements you wish to refer to via getElementById.
Use getElementsByName instead.

Jquery selecting inputs with adjacent asterisk

Using jquery, I'm trying to select those inputs that have an asterisk adjacent to them.
HTML
<form name="checkout">
<table width="100%" border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="FirstName" value="" />*</td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="LastName" value="" /></td>
</tr>
</table>
</form>
Jquery
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
Result of elems should be 1 but it's not working, i.e. the form submits in spite of a return false in the handler so can't seem to catch the error details. What am I doing wrong?
var elems = $("td:contains('*') input");
This is selector for the input elements that you need.
elems.length will give you 1 in this case
Ha Ha,
Missing the onReady().
Use this one,
$(function(){
var elems = $("form[name='checkout'] :input").filter(function(index) {
var str = $(this).parents('td').html()
return (str.indexOf("*")!=-1)
}).length;
console.log(elems);
});
That should do. Cheers :).
I suggest you to use CSS :after pseudo element
<style>
.mandatory:after{
content:"*";
}
</style>
<span class="mandatroy">
<input type="text" name="FirstName" value="">
</span>
<script>
$("form[name='checkout'] .mandatory > :input")
</script>
It would be easier, if you added a class to the inputs which have an asterisk after them:
<td><input type="text" name="FirstName" class="required" />*</td>
Then you could select them by their class and do whatever you wish to them.
$("input.required").length();
Given the explicit requirement:
$('input').filter(function () {
return (this.nextSibling && this.nextSibling.nodeValue.indexOf('*') > -1) || (this.previousSibling && this.previousSibling.nodeValue.indexOf('*') > -1);
}).css('border-color','#f00');
JS Fiddle demo.

need to select atleast one checkbox using javascript

I am using this javascript code. and on button click I want that atleast one checkbox selection is required. do anyone have idea what I am doing wrong. I don't want to use jquery.
function check()
{
var flag = false;
for(var i=1;i<=4;i++)
{
var checkb = document.getElementById("check"+i);
if(checkb.checked)
{
flag = true;
break;
}
}
if(!flag)
alert("What is your interest \n(select at least one option)");
return flag;
}
</script>
Button Click Code is
<input type="submit" name="submit" value="Submit" onclick="return check();">
The code works fine. Do hou have id="check1" set on your checkbox tags?
Yes, your code works fine as noted by the comments above. However, you could do your check for...checks a little more cleanly - you're expecting "check0" - "check4" for the IDs. You could just grab them all and not worry about a set limit (odds are your code isn't working because at least one of the IDs you're using doesn't exist).
<input type="checkbox" id="check0" />
<input type="checkbox" id="check1" />
<input type="checkbox" id="check2" />
<input type="checkbox" id="check3" />
<hr/>
<input type="button" onclick="checkIt();" value="Check the Checks">
And some JS:
checkIt = function()
{
var checks = document.getElementsByTagName('input');
var hasCheck = false;
for(i in checks)
{
// Could also check for a classname here to narrow
// your result set.
if(checks[i].type == 'checkbox')
hasCheck |= checks[i].checked;
}
if(!hasCheck)
alert('You should check one!');
return hasCheck;
}

Categories