i have a datatable with checkbox and a button add, i want when i click on button add, console display salaire and prime and sold which calculate like that sold = (salaire / 24) + prime.
index.php
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div id="form2">
<table class="table table-bordered" id="mytable">
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>nom</th>
<th>salaire</th>
<th>adresse</th>
<th>prime</th>
</tr>
<tr>
<td><input type="checkbox" class="checkbox"></td>
<td>najib</td>
<td>5000</td>
<td>tihit</td>
<td><input type="text" name="prime" class="form-control prime" value="0"></td>
</tr>
<tr>
<td><input type="checkbox" class="checkbox"></td>
<td>adil</td>
<td>4000</td>
<td>tagmast</td>
<td><input type="text" name="prime" class="form-control prime" value="0"></td>
</tr>
</table>
<div class="form-group col-md-offset-5 ">
<button class="btn btn-success " type="submit" id="add">Pointage men</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(){
var items = [];
$("tr").each(function(i,r){
let salaire = r.cells[2].innerText;
let prime = $(r).find(".prime").val();
let sold = ((salaire)/24) + prime;
if ( i > 0 && $(r).find("input").first().prop("checked")){
items.push({ "salaire" : salaire , "prime" : prime , "sold" : sold });
}
})
console.log(items);
})
})
</script>
This happens since variables salaire and prime are actually returned in code as string and thus when you do this:
console.log( ('5000'/24) + '100' )
then answer is also returned as a string like "208.33333333333334100"
So, you just need to convert them to integer first and it should work fine like:
let salaire = '5000'
let prime = '100'
let sold = ((+salaire) / 24) + +prime;
console.log(sold)
Related
I am trying to get the date and department info stored into an array, when a user inputs a value into my HTML. When I look at the console, I see it is being saved as E.fn.init. Here is my HTML code:
<form>
<p><b>Date:</b><input id="date_out" type='date' required /></p>
<p><b>Department:</b><input id='department_out' type='text' required /></p>
<button class="btn btn-primary" type="submit" id='submit' >SUBMIT</button>
</form>
And here is my Javascript Code:
let count = 1;
// Handler to Submit Data
$('#submit').click(() =>{
$('form').on('submit', function(e){
e.preventDefault();
const date_out = $("#date_out").val();
const department_out = $("#department_out").val();
let data = [];
// Iterate over all rows and store data
for (let i = 1; i <= count; i++){
// Skip Row if it was Removed
if (!$(`tr[index=${i}]`).length) continue;
// Store all Info from this row
let assetInfo = {
date_out: $(`#date_out${i}`).val(date_out),
department_out: $(`#department_out${i}`).val(department_out),
}
data.push(assetInfo);
console.log(data);
}
});
});
And the console prints the array as; date_out: E.fn.init, department_out: E.fn.init. How do I get it to save whatever the user inputs in the array?
I am not quite sure what is your HTML structure but as I understand, you have a table and you want to store each row in a data,
here is how I advise you to do it:
In my Table called depTable, I have each row with a unique ID like this:
date_out_1
department_out_1
so, when I want to access that, I just want to create that ID which is an easy task while I can get how many rows I have in that table, like this:
// Get ROW COUNT FROM TABLE
var count = $('#depTable tr').length;
Now, if you combine in For loop you will get all IDs
for (let i = 1; i <= count; i++){
var idDate = "#date_out_" + i;
var idDep = "#department_out_" + i;
}
here is my all code, hope I helped to solve your problem.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stack21</title>
<script src="js/jquery-3.6.0.min.js"></script>
</head>
<body>
<table id="depTable">
<thead>
<tr>
<td>Date</td>
<td>Department</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input id="date_out_1" type='date' required />
</td>
<td>
<input id='department_out_1' type='text' required />
</td>
</tr>
<tr>
<td>
<input id="date_out_2" type='date' required />
</td>
<td>
<input id='department_out_2' type='text' required />
</td>
</tr>
<tr>
<td>
<input id="date_out_3" type='date' required />
</td>
<td>
<input id='department_out_3' type='text' required />
</td>
</tr>
<tr>
<td>
<input id="date_out_4" type='date' required />
</td>
<td>
<input id='department_out_4' type='text' required />
</td>
</tr>
</tbody>
</table>
<Button onclick="storeUserData()">Test me</Button>
<script>
let data = [];
function storeUserData(){
// Get ROW COUNT FROM TABLE
var count = $('#depTable tr').length;
console.log("Row Count: " + count)
for (let i = 1; i <= count; i++){
var idDate = "#date_out_" + i;
var idDep = "#department_out_" + i;
let assetInfo = {
date_out: $(idDate).val(),
department_out: $(idDep).val()
}
data.push(assetInfo);
}
console.log(data);
}
</script>
</body>
</html>
Demo code here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stack21</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- MY OFFLINE <script src="js/jquery-3.6.0.min.js"></script> -->
</head>
<body>
<table id="depTable">
<thead>
<tr>
<td>Date</td>
<td>Department</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input id="date_out_1" type='date' required />
</td>
<td>
<input id='department_out_1' type='text' required />
</td>
</tr>
<tr>
<td>
<input id="date_out_2" type='date' required />
</td>
<td>
<input id='department_out_2' type='text' required />
</td>
</tr>
<tr>
<td>
<input id="date_out_3" type='date' required />
</td>
<td>
<input id='department_out_3' type='text' required />
</td>
</tr>
<tr>
<td>
<input id="date_out_4" type='date' required />
</td>
<td>
<input id='department_out_4' type='text' required />
</td>
</tr>
</tbody>
</table>
<Button onclick="storeUserData()">Test me</Button>
<script>
let data = [];
function storeUserData(){
// Get ROW COUNT FROM TABLE
var count = $('#depTable tr').length;
console.log("Row Count: " + count)
for (let i = 1; i <= count; i++){
var idDate = "#date_out_" + i;
var idDep = "#department_out_" + i;
let assetInfo = {
date_out: $(idDate).val(),
department_out: $(idDep).val()
}
data.push(assetInfo);
}
console.log(data);
}
</script>
</body>
</html>
I am working on a form to create an invoice.
so basically, i have a button to create a table row where I can enter the code, name of product, notes, qty, price and discount. then automatically add the total price, by multiply the qty and subtracting the discount.
The problem I am having is to get the row index where the addition need to be worked. The first row it works but the second, third, etc... doesn't work.
I am asking here maybe there is some one that can find the problem. I am a beginner when it comes to javascript and basically learning while working on it, so any help it is really appreciated.
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" id="qty" value="${p_qty}" oninput="calculate()" /></td>
<td><input type="text" id="price" step="0.01" min="0.00" value="${p_price1}" oninput="calculate()" /></td>
<td><input type="text" id="discount" value="${p_discount}" oninput="calculate()" /></td>
<td><input type="number" id="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
function calculate() {
var calc_qty = document.getElementById('qty').value;
var calc_price = document.getElementById('price').value;
var discount = document.getElementById('discount').value;
var result = document.getElementById('net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
Don't use id's in your generated code, id's have to be unique. I changed them to classes. I also changed the calculate function so the target element is given as a parameter. In the calculate function the correct elements are found based on the element in the parameter.
But it's a pretty ugly way of handling this. I recommend rewrite it so you do event delegation on your table like in the function below. If you don't want that then see the bottom snippet.
//Event delgation from the table as replacement of the calculate function
document.querySelector('#list-table').addEventListener('input', function(e) {
//Element that triggered
let target = e.target;
//check if the target has the class of one of our input elements that we want to use for (re)calculation
if (target.classList.contains('qty') ||
target.classList.contains('price') ||
target.classList.contains('discount') ||
target.classList.contains('net_price')
) {
//(re)calculate
var targetRow = target.parentElement.parentElement;
var calc_qty = targetRow.querySelector('.qty').value;
var calc_price = targetRow.querySelector('.price').value;
var discount = targetRow.querySelector('.discount').value;
var result = targetRow.querySelector('.net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
});
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" class="qty" value="${p_qty}" /></td>
<td><input type="text" class="price" step="0.01" min="0.00" value="${p_price1}" /></td>
<td><input type="text" class="discount" value="${p_discount}" /></td>
<td><input type="number" class="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
Original answer:
// Item Counter
var ic = 1;
// Remove an entry
function RemoveEntryFromList(entry) {
document.getElementById(entry).remove();
}
// Adds an entry into the "Added Items" list
function addEntryToList(p_code, p_name, p_sn, p_qty, p_price, p_discount, p_url, p_costPrice, p_qtyAvailable) {
var entry = document.createElement("tr");
entry.id = ("item-" + String(ic));
document.getElementById("list-table").tBodies[0].appendChild(entry);
p_price1 = parseFloat(p_price).toFixed(2);
p_costPrice1 = parseFloat(p_costPrice).toFixed(2);
entry.innerHTML = `<td><input value="${p_code}" /></td>
<td><input value="${p_name}" /></td>
<td><input value="${p_sn}" /></td>
<td><input type="text" class="qty" value="${p_qty}" oninput="calculate(this)" /></td>
<td><input type="text" class="price" step="0.01" min="0.00" value="${p_price1}" oninput="calculate(this)" /></td>
<td><input type="text" class="discount" value="${p_discount}" oninput="calculate(this)" /></td>
<td><input type="number" class="net_price" readonly /></td>
<td style="text-align: center;"><button onclick="RemoveEntryFromList('${entry.id}')"> X </button></td>
<td style="text-align: center; cursor: pointer;"><i class="fas fa-ellipsis-v"></i></td>`;
ic++;
}
function calculate(element) {
var calc_qty = element.parentElement.parentElement.querySelector('.qty').value;
var calc_price = element.parentElement.parentElement.querySelector('.price').value;
var discount = element.parentElement.parentElement.querySelector('.discount').value;
var result = element.parentElement.parentElement.querySelector('.net_price');
var calc_discount = calc_price * (discount / 100);
var calc_result = (calc_price - calc_discount) * calc_qty;
result.value = calc_result;
}
<div id="container">
<div id="list-sect">
<button id="add-custom-item-btn" onClick="addEntryToList('', '', '', '1', '0.00', '0');" style="height: 30px;">
<i class="fas fa-box-open"></i> Add New Entry
</button>
</div>
<table id="list-table">
<tr class="list-entry" style="height: 21px;">
<th width="80px">Code</th>
<th>Name</th>
<th>notes</th>
<th width="60px">Qty</th>
<th width="76px">Price</th>
<th width="65px">Disc.(%)</th>
<th width="76px">Total Price</th>
<th colspan="2">Remove</th>
</tr>
</table>
</div>
in order for your code to work using document.getElementById("list-table").tBodies[0].appendChild(entry); you need to enclose your rows (<tr>) inside a <tbody> </tbody>.
also i'd change your entry.innerHTML = (...) to add each td as a new createElement() inside entry.
I am unsure of what I have done wrong in my simple sales tax calculator. When I press submit I want a dollar amount of the item cost plus sales tax to be shown but instead I see total tip $functionround(){[native code]}.
//calculation
var total = (itemCost * salesTax + itemCost);
total = Math.round
total = Math.round
In the line above you are assigning the value of the function Math.round to the variable total. Instead you probably want to assign the value returned by the function Math.round to your total variable like this:
total = Math.round(total)
You should consider those codes on the calculation. Here is a simple tax calculator and it works well:
function fmtPrice(value) {
result="$"+Math.floor(value)+".";
var cents=100*(value-Math.floor(value))+0.5;
result += Math.floor(cents/10);
result += Math.floor(cents%10);
return result;
}
function compute() {
var unformatted_tax = (document.forms[0].cost.value)*(document.forms[0].tax.value);
document.forms[0].unformatted_tax.value=unformatted_tax;
var formatted_tax = fmtPrice(unformatted_tax);
document.forms[0].formatted_tax.value=formatted_tax;
var cost3= eval( document.forms[0].cost.value );
cost3 += eval( (document.forms[0].cost.value)*(document.forms[0].tax.value) );
var total_cost = fmtPrice(cost3);
document.forms[0].total_cost.value=total_cost;
}
function resetIt() {
document.forms[0].cost.value="19.95"; // cost of product
document.forms[0].tax.value=".06"; // tax value
document.forms[0].unformatted_tax.value="";
document.forms[0].formatted_tax.value="";
document.forms[0].total_cost.value="";
}
<CENTER>
<FORM>
<TABLE BORDER=2 WIDTH=300 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Cost</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Tax</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="cost" VALUE="19.95" SIZE=10>
<TD align="center"><INPUT TYPE="text" NAME="tax" VALUE=".06" SIZE=10>
</TR>
</TABLE>
<BR>
<TABLE BORDER=1 WIDTH=600 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Unformatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Formatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>TOTAL COST</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="unformatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="formatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="total_cost" SIZE=15>
</TR>
</TABLE>
<BR>
<TABLE BORDER=0 WIDTH=400 CELLPADDING=5>
<TR>
<TD align="center"><INPUT TYPE="reset" VALUE="RESET" onClick="resetIt()">
<TD align="center"><INPUT TYPE="button" VALUE="COMPUTE" onclick="compute()">
</TR>
</TABLE>
</CENTER>
As noted you need to return the total of hte Math.round - but you also need to parse the values into numbers) and then you also have to remember that the sales tax is a percentage - so it has to be divided by 100.
I have amended your logic to
a) parse the values of the inputs into numbers using parseInt()
b) resolve the math.round() issue
c) get the sales tax value by multiplying the item cost by the sales tax percentage ... itemCost * (salesTax/100)
d) add the sales tax value to the item cost ... item cost + (itemCost * (salesTax/100))...
//Function
function calculateTip() {
var itemCost = parseInt(document.getElementById("itemCost").value);
var salesTax = parseInt(document.getElementById("salesTax").value);
//enter values window
if (itemCost === "" || salesTax == "") {
window.alert("Please enter the values!");
return;
}
//calculation
var total = Math.round(itemCost + (itemCost * salesTax/100));
//display amount
document.getElementById("totalTip").style.display = "block";
document.getElementById("amount").innerHTML = total;
}
//Hide Tip Amount and call our function with a button
document.getElementById("totalTip").style.display = "none";
document.getElementById("submit").onclick = function() {
calculateTip();
};
</head>
<body id="color">
<div class="container" id="contain">
<div class="text-center">
<h1>Sales Tax Calculator</h1>
<p> Amount Before Tax?</p>
$ <input id="itemCost" type="text" placeholder="item cost">
<p>Sales Tax Percentage?</p>
<input id="salesTax" type="text" placeholder="sales tax percent"><br><br>
<button type="submit" id="submit">submit</button>
</div>
<div class="container" ID="totalTip">
<div class="text-center">
<p>Total Tip</p>
<sup>$</sup><span id="amount">0.00</span>
</div>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</body>
I am very new to really writing javascript (borrowing and editing, not so new). So with a little help from google and code guru and adobe cookbook, I have come up with this simple form to be embedded into an iPad publication (this is just my test, not the final product). I have gotten it this far with no errors if the debug console and it seems to pass W3C compliance, but it also doesn't do anything! It doesn't generate the answers??? I am hoping someone can help me out or steer me in the right direction. the code for the page is below: Thanks in advance...
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.innerHTML = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.innerHTML = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.innerHTML = + (TotalsCost1 - TotalsCost2);
}
};
</script>
</body>
btn.onclick = (function(){...})();
You need to put onclick events inside self-calling code, or what are called closures. Move your entire btn.onclick function inside of this bit of code: (...)() in order to make it work.
Good attempt, a few small things wrong but pretty close!
I have made a few changes here.
As mentioned in a comment, I wrapped the function with brackets (function() {...});
I also changed innerHTML to be value as we are updating text inputs, and your savings calculation should be input.value, which I have updated for you.
Let me know how you get on!
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = (function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.value = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.value = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.value = + (TotalsCost1.value - TotalsCost2.value);
}
});
</script>
</body>
I have a few radiobuttons in a jsp page. I run a javascript method once the page is loaded that seeks for certain radio buttons and change its name so they work like a radio group.
I'm doing it this way because the radio buttons are inside jsf table and I have no access to the name property when coding and I want all of the radio buttons work like a radio group.
Anyways the script run without problems and the radio buttons' names are changed properly.
But while this works in FF 3 (the work like a radio group) it doesn't work in IE 6 or IE7 though they have the same 'name' property. Does anyone know how can I solve this?
function setRadioGroup (nombreRadio){
var listaRadios = document.getElementsByTagName('input');
var tam = listaRadios.length;
for (i = 0; i < tam; i++){
if (listaRadios[i].type == 'radio' && listaRadios[i].title == 'Seleccionar'){
listaRadios[i].name = nombreRadio;
}
}
}
EDIT: Added the code output of the webpage:
<form id="formulario" name="formulario" method="post"
action="/serequp/faces/administracion/articulosPv.jspx"><input
type="hidden" id="formulario:hidRegTablaArticulos"
name="formulario:hidRegTablaArticulos" value="">
<div class="dr-pnl rich-panel " id="formulario:ContFormularios">
<div class="dr-pnl-h rich-panel-header cabeceraFormulario"
id="formulario:ContFormularios_header">LISTADO DE GRUPOS DE
EQUIPAMIENTOS</div>
<div class="dr-pnl-b rich-panel-body cuerpoFormularios"
id="formulario:ContFormularios_body">
<table id="formulario:botones">
<tbody>
<tr>
<td class="estiloColumnas"><input id="formulario:j_id66"
name="formulario:j_id66"
onclick="A4J.AJAX.Submit('_viewRoot','formulario',event,{'parameters':{'formulario:j_id66':'formulario:j_id66'} ,'actionUrl':'/serequp/faces/administracion/articulosPv.jspx','similarityGroupingId':'formulario:j_id66'} );return false;"
value="Crear" type="button"></td>
<td class="estiloColumnas"><input id="formulario:j_id67"
name="formulario:j_id67"
onclick="A4J.AJAX.Submit('_viewRoot','formulario',event,{'parameters':{'formulario:j_id67':'formulario:j_id67'} ,'actionUrl':'/serequp/faces/administracion/articulosPv.jspx','similarityGroupingId':'formulario:j_id67'} );return false;"
value="Modificar" type="button"></td>
<td class="estiloColumnas"><input id="formulario:j_id68"
name="formulario:j_id68"
onclick="A4J.AJAX.Submit('_viewRoot','formulario',event,{'parameters':{'formulario:j_id68':'formulario:j_id68'} ,'actionUrl':'/serequp/faces/administracion/articulosPv.jspx','similarityGroupingId':'formulario:j_id68'} );return false;"
value="Borrar" type="button"></td>
<td></td>
</tr>
</tbody>
</table>
<table class="dr-table rich-table " id="formulario:tablaArticulos"
border="0" cellpadding="0" cellspacing="0">
<colgroup span="3"></colgroup>
<thead class="dr-table-thead">
<tr class="dr-table-subheader rich-table-subheader ">
<th class="dr-table-subheadercell rich-table-subheadercell "
scope="col" id="formulario:tablaArticulos:j_id69header">
<div id="formulario:tablaArticulos:j_id69header:sortDiv">Nombre</div>
</th>
<th class="dr-table-subheadercell rich-table-subheadercell "
scope="col" id="formulario:tablaArticulos:j_id71header">
<div id="formulario:tablaArticulos:j_id71header:sortDiv">Nombre</div>
</th>
<th class="dr-table-subheadercell rich-table-subheadercell "
scope="col" id="formulario:tablaArticulos:j_id75header">
<div id="formulario:tablaArticulos:j_id75header:sortDiv">DescripciĆ³n</div>
</th>
</tr>
</thead>
<tbody id="formulario:tablaArticulos:tb">
<tr class="dr-table-firstrow rich-table-firstrow ">
<td class="dr-table-cell rich-table-cell center "
id="formulario:tablaArticulos:0:j_id69">
<table id="formulario:tablaArticulos:0:radioGroup1">
<tr>
<td><input id="formulario:tablaArticulos:0:radioGroup1:0"
type="radio" name="formulario:tablaArticulos:0:radioGroup1"
value="1" onclick="updateSelected('hidRegTablaArticulos', '1');"
title="Seleccionar"><label
for="formulario:tablaArticulos:0:radioGroup1:0"></label></td>
</tr>
</table>
</td>
<td class="dr-table-cell rich-table-cell center "
id="formulario:tablaArticulos:0:j_id71">fff</td>
<td class="dr-table-cell rich-table-cell center "
id="formulario:tablaArticulos:0:j_id75">PRUEBA SDS</td>
</tr>
<tr class="dr-table-firstrow rich-table-firstrow ">
<td class="dr-table-cell rich-table-cell center "
id="formulario:tablaArticulos:1:j_id69">
<table id="formulario:tablaArticulos:1:radioGroup1">
<tr>
<td><input id="formulario:tablaArticulos:1:radioGroup1:0"
type="radio" name="formulario:tablaArticulos:1:radioGroup1"
value="1" onclick="updateSelected('hidRegTablaArticulos', '2');"
title="Seleccionar"><label
for="formulario:tablaArticulos:1:radioGroup1:0"></label></td>
</tr>
</table>
</td>
<td class="dr-table-cell rich-table-cell center "
id="formulario:tablaArticulos:1:j_id71">dd</td>
<td class="dr-table-cell rich-table-cell center "
id="formulario:tablaArticulos:1:j_id75">PRUEBA SDS</td>
</tr>
</tbody>
</table>
<script>
setRadioGroup('radioGroup1');
</script></div>
</div>
<table id="formulario:botonera">
<tbody>
<tr>
<td><input id="formulario:j_id80" name="formulario:j_id80"
onclick="A4J.AJAX.Submit('_viewRoot','formulario',event,{'parameters':{'formulario:j_id80':'formulario:j_id80'} ,'actionUrl':'/serequp/faces/administracion/articulosPv.jspx','similarityGroupingId':'formulario:j_id80'} );return false;"
value="Grabar" type="button"></td>
</tr>
</tbody>
</table>
<input type="hidden" name="formulario" value="formulario"><input
type="hidden" name="autoScroll" value=""><input type="hidden"
name="formulario:j_idcl" value=""><input type="hidden"
name="formulario:_link_hidden_" value=""><script
type="text/javascript">function clear_formulario() {
_clearJSFFormParameters('formulario','',['formulario:j_idcl','formulario:_link_hidden_']);
}
function clearFormHiddenParams_formulario(){clear_formulario();}
function clearFormHiddenParams_formulario(){clear_formulario();}
clear_formulario();</script><input type="hidden" name="javax.faces.ViewState"
value="!40dc077b"></form>*
I finally got the answer!
The solution come from this blog, but with some modification (the blog, as many others, solve the problem for create a new element, not to modify an existant one).
The problem is that Internet Explorer does not allow some attributes modification during the run time. One of these is the attribute name. As it can not be modified, the behaviour is not what you're expecting. The solution is to create a new element, remove the old one and replace it by the new one.
Here the solution (work with Firefox 3 and IE 7):
<script>
function setRadioGroup (name){
var listaRadios = document.getElementsByTagName('input');
var tam = listaRadios.length;
for (i = 0; i < tam; i++){
cur = listaRadios[i];
if (cur.type == 'radio' ){
try {
// if not IE, raise an error and go to catch.
element = document.createElement('<input onclick="alert(this.name + this.value);" type="radio" name="' + name + '" value="' + cur.value + '">');
parentNode = cur.parentNode;
parentNode.insertBefore(element, cur);
parentNode.removeChild(cur);
} catch (err ) {
cur.setAttribute('name', name);
cur.setAttribute('onclick', 'alert(this.name + this.value);');
}
}
}
}
</script>
<html>
<head>
<title>My Page</title>
</head>
<body onload="setRadioGroup('test')">
<form name="myform" action="http://www.mydomain.com/myformhandler.cgi" method="POST">
<div align="center"><br>
<input type="radio" value="Milk"> Milk<br>
<input type="radio" value="Butter" > Butter<br>
<input type="radio" value="Cheese"> Cheese
<hr>
<input type="radio" value="Water"> Water<br>
<input type="radio" value="Beer"> Beer<br>
<input type="radio" value="Wine" > Wine<br>
</div>
</form>
</body>
</html>