Change radio button name javascript not working in IE - javascript

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>

Related

Radio button value is printing 'on' instead of value that it holds

function perform_global(tablecounter)
{
for (index = 1; index <= 2; ++index) {
var dnsname = "dns_name"+index;
oRadio = document.getElementsByName(dnsname);
alert (" radio ID " + dnsname + " " + index + "length " + oRadio.length);
for(var i = 0; i < oRadio.length; i++)
{
if(oRadio[i].checked)
{
alert( "Checked Value is " + oRadio[i].value );
}
}
}
}
<form id=globe>
<table id=x >
<THEAD><TR>
<TH> DNSNAME </TH>
</TR> </THEAD>
<TBODY id="tbody_1_1"> <TR>
<TD>
<input type='radio' name='dns_name1' value='service_name_xx' checked> service_names_xx
</TD>
<TD>
<input type='radio' name='dns_name1' value='service_name_yy' > service_name_yy
</TD>
</TR></TBODY>
</table>
<table id=y>
<THEAD><TR>
<TH> DNSNAME </TH>
</TR> </THEAD>
<TBODY id="tbody_1_2"> <TR>
<TD>
<input type='radio' name='dns_name2' value='service_name_xxx' checked> service_names_xxx
</TD>
<TD>
<input type='radio' name='dns_name2' value='service_name_yyy'> service_name_yyy
</TD>
</TR></TBODY>
</table>
<button onclick="perform_global()">
</form>
If I understand your question correctly, then one option to achieve what you require would be via the querySelectorAll() and getAttribute() methods.
First, pass the following selector to querySelectorAll() to acquire all radio input elements that are checked:
querySelectorAll('input[type="radio"]:checked')
Next, iterate the list of matching elements that this query returned, and get the corresponding value attribute (and name attribute if required) of each element via the getAttribute() method:
radio.getAttribute("value")
These ideas can be combined together as follows:
function perform_global(event) {
// Prevent button from submitting
event.preventDefault();
// Use querySelectorAll to select radio elements that are checked
for (let radio of document.querySelectorAll(`input[type="radio"]:checked`)) {
// Use getAttribute to aquire value attribute for checked radio
console.log("Checked group:" + radio.getAttribute("name") + ", value:" + radio.getAttribute("value"));
}
}
<form id=globe>
<table id=x>
<TH> DNSNAME </TH>
<TD>
<input type='radio' name='dns_name1' value='service_name_xx' checked> service_names_xx
</TD>
<TD>
<input type='radio' name='dns_name1' value='service_name_yy'> service_name_yy
</TD>
</table>
<table id=y>
<TH> DNSNAME </TH>
<TD>
<input type='radio' name='dns_name2' value='service_name_xx' checked> service_names_xx
</TD>
<TD>
<input type='radio' name='dns_name2' value='service_name_yy'> service_name_yy
</TD>
</table>
<!-- Pass event to onclick handler -->
<button onclick="perform_global(event)">Button</button>
</form>

Uncaught TypeError: Cannot read property 'value' of null HTML Form is correct

I have read this post but still have some questions. I am getting the error:
Uncaught TypeError: Cannot read property 'value' of null
On this line:
fullname = document.getElementById('namefull').value;
I am 100% sure that the field 'namefull' is on the form and I also have a value typed in the form. I actually have a check to make sure it's not null and that passes. Here is form:
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull"></td>
</tr>
The full code is below:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Microsoft FrontPage 2.0">
<title>HABLA Order Form</title>
</head>
<script language="javascript">
// Do not steal, modify, or claim these scripts as your own! Thank You.
// Alterations and additions by Gordon Smith Mearns#mearns.org.uk
index = 0;
function getFields() {
fullname = document.getElementById('namefull').value;
email = document.getElementById('email').value;
phone = document.getElementById('phone').value;
zip = document.getElementById('zip').value;
amount = document.getElementById('total').value;
type = document.getElementById('order_type').value;
seller = 'TestSeller';
specinstruct = document.getElementById('specinstr').value;
xact_num = 'StripeDummy';
};
function writeXact() {
var sendtext;
getFields();
if (fullname == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
sendtext = fullname + "||" + email + "||" + phone + "||" + zip +
"||" + amount + "||" + type + "||" + seller + "||" + specinstruct +
"||" + xact_num;
xmlhttp.open("GET","writeXact.php?q="+sendtext,true);
xmlhttp.send();
}
};
function format(val, post)
{
var decpoint;
var begin;
var end;
var valstr;
var temp_char;
valstr = "" + val;
//alert('valstr = ' + valstr);
decpoint = valstr.indexOf(".")
if (decpoint != -1) {
//alert('decpoint = ' + decpoint);
begin = valstr.substring(0,decpoint);
end = valstr.substring(decpoint+1,valstr.length);
//alert('begin = ' + begin + '\nend= ' + end);
}
else {
begin = valstr;
end = "";
}
if (end.length < post)
{while (end.length < post)
{
end += "0";
}
}
end = end.substring(0,post);
//alert('begin = ' + begin + '\nend= ' + end);
return (begin+"."+end);
};
function orderSubmit(type)
{
if (type == 'order')
{if ( ! ( (document.order.order_type.checked) ||
checkRequired() ))
{document.order.form_action.value = type;
getFields();
writeXact(fullname, email, phone, zip, amount, type, seller, specinstruct, xact_num);
document.order.submit();
return true;
}
else {
// alert('first false');
return false;
}
}
};
var infowin = null;
function checkRequired() {
if (!document.order.namefull.value.length ||
!document.order.email.value.length ||
!document.order.zip.value.length ||
!document.order.phone.value.length) {
alert('You have not completed all required fields:\n' +
'Please enter Name, Email, Phone, Zip');
return true;
}
else {
return false;
}
};
<!-- -->
</script><!-- --><a name="top"></a>
<body background="images/thisback.gif" bgcolor="#FFFFFF"
text="#000000" onLoad=parent.refresh_order_details(parent.order_details) onUnload=parent.add_order_details(parent.order_details)>
<center>
<script
language="javascript">
<!-- hide
if (self==parent){document.write('<font color=#ff000><b>This is a frame element, click <a href=shopcartindex.html> here </a>for correct page</b></font>')};
<!-- end hide -->
</script>
<p><size="6" color="black" font face="Calibri"><b>HABLA Event Order Form</b><br>
</font></p>
<!-- YOU CAN PUT YOUR EMAIL ADDRESS IN THE FORM COMMAND BELOW AND THE -->
<!-- THEN IT WILL BE SENT TO YOU AS A SIMPLE MAILTO GUESTBOOK FORM -->
<!-- IF YOU DO THAT - BE SURE TO ADD THE COMMAND enctype="plain/text" -->
<!-- IN ORDER TO DELINEATE THE MAIL FOR YOU -->
<!-- YOU CAN ALSO USE TE .PL FILE AS A CGI TO HELP WTH THE MAIL. SEE THE TUTORIAL -->
<!-- FOR MORE ON HOW THAT IS DONE -->
<form action="MAILTO:hablariverglen#gmail.com" method="POST" name="order">
<input type="hidden" name="subject"
value="Order Forms - HABLA Balie 2015"><input type="hidden"
name="recipient" value="YOUR EMAIL ADDRESS HERE"><input
type="hidden" name="redirect"
value="thanku.htm"><input
type="hidden" name="retailer" value="NAME OF YOUR BUSINESS HERE"><input
type="hidden" name="form_action" value="order">
<script
language="javascript">
<!-- hide from Browsers
document.write('<table width=400><td align=center>');
document.write('<table width=400 ><tr><tr><td align=right colspan=3 ><font face="Calibri"><b>Total Purchase $</b></td><td colspan=3> <input type=text name=total font face="Calibri" value='+ format(parent.all_order_totals(),2) + '></font></td><tr>');
if (parent.items_ordered == 0)
document.write('<font color=#000080><b>There are no items in your cart<b></font>');
if (parent.item_num > 0);
{
for (i =1;i < parent.item_num;i++)
{ if (parent.itemlist[i].quan > 0)
{index = index + 1;
document.write('<input size=10 type=text font face="Calibri" name= ' + parent.itemlist[i].code + ' value= ' + parent.itemlist[i].code + '><input size=6 type=text name= ' + parent.itemlist[i].code + ' value=' + parent.itemlist[i].price + '><input size=20 type=text name= ' + parent.itemlist[i].code + ' value= '+ parent.itemlist[i].desc + '><input size=2 type=text name= ' + parent.itemlist[i].desc + ' value= '+ parent.itemlist[i].quan + '><br>');
}
}
};
<!-- end hiding -->
</script>
<!-- Customer Info Table -->
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Email Address:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="60" name="email"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Zip:</b></td>
<td bgcolor="#CCFFFF"><input type="text" size="9"
maxlength="10" name="zip"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Phone:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="25" maxlength="15" name="phone"></td>
</tr>
</table>
<p align="center">
<table border="0" width=400>
<tr>
<td align="center" colspan="6"<b><font face = "Calibri"><b>Special Instructions</b><br></td>
</tr>
<tr>
<td colspan="6"><center><textarea name="specinstr" rows="3"
cols="40"></textarea></center></td>
</tr>
</table>
<!-- Order Method Table --> </p>
<table border="0" cellspacing="0" width=400>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><font
size="4"><b>Choose Order Method:</b></font></td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Credit Card: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Cash: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Check: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><a
href="options.htm" target=navigate>
</td>
</tr>
</table>
<p><br>
<p><br>
<! Stripe Credit Card Integration >
<form action="" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_zzzzzz"
data-amount="2000"
data-name="Demo Site"
data-description="2 widgets ($20.00)"
data-image="/128x128.png"
data-locale="auto">
</script>
</form>
<input
type="button" value="Place Order"
onclick="orderSubmit('order')"
<input type="reset" value="Reset Cart"> </p>
<b>HABLA Friends of River Glen <a href=mailto:hablariverglen#gmail.com>hablariverglen#gmail.com</a> </b>
</form>
</td></table>
</center>
</p>
</body >
</html>
Yes, I know the code is a mess, but I'm doing this for a school/charity fundraiser, so any help is much appreciated.
You are looking for an element with id="namefull", but in your html, you only specify the name attribute: <input type="text" size="30" maxlength="30" name="namefull">
Try including id="namefull" in here:
<input type="text" id="namefull" name="namefull" size="30" maxlength="30">
You'll want to follow suit on each of your inputs to specify the id, since that's what you're looking for with document.getElementById().
getElementById() get's an element by it's ID. You need to set the id for that to work.
Change your markup to:
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull" id="namefull"></td>
</tr>
Notice I added id="namefull" to the input element.

Show hide elements based on ID from select dropdown javascript

I know this is proboly the most asked question out there but I have scoured the net and tried several examples and none of them have worked. Here is my issue.
First I have no control over the TR TD structure, can't use DIV.
I need to be able to display certain TD's based on the select dropdown menu value. I have 4 different id's I am using "to", "to_field", "from", "from_field". The script I have shown is not working. Can someone help me out?
Example: If someone selects "In Use" in the dropdown then I just want all the elementID that have "from" and "from_field" to display only. If someone selects a different value then I would like to change that around.
<script type="text/javascript">
function showstuff(element){
document.getElementById("from").style.display = element=="in_use"?"visibility":"visible";
document.getElementById("to").style.display = element=="in_use"?"visibility":"hidden";
document.getElementById("from_field").style.display = element=="in_use"?"visibility":"visible";
document.getElementById("to_field").style.display = element=="in_use"?"visibility":"hidden";
document.getElementById("from").style.display = element=="relocated"?"visibility":"visible";
document.getElementById("to").style.display = element=="relocated"?"visibility":"visible";
document.getElementById("from_field").style.display = element=="relocated"?"visibility":"visible";
document.getElementById("to_field").style.display = element=="relocated"?"visibility":"visible";
}
</script>
<table>
<tr>
<td><h2>Add/Edit Parts</h2></td>
</tr>
</table>
<form action="includes/inventory_parts.php" method="post" name="myform">
<table cellpadding="10" style="border:solid 1px #000000">
<tr>
<td colspan="20"><h3>Add New Part</h3></td>
</tr>
<tr>
<td style="font-weight:bold">Printer Man Part#</td>
<td style="font-weight:bold">Part#</td>
<td style="font-weight:bold">Title</td>
<td style="font-weight:bold">Serial#</td>
<td style="font-weight:bold">Status</td>
<td id="from" style="font-weight:bold;visibility:hidden">From Printer Serial#</td>
<td id="to" style="font-weight:bold;visibility:hidden;">To Printer Serial#</td>
<td style="font-weight:bold">Submit</td>
</tr>
<tr>
<td><input type="text" name="printer_man_part_number" /></td>
<td><input type="text" name="part_number" /></td>
<td><input type="text" name="title" /></td>
<td><input type="text" name="this_part_serial_number" /></td>
<td>
<select name="status" onchange="showstuff(this.value);">
<option></option>
<option value="in_use">In Use</option>
<option value="relocated">Relocated</option>
<option value="disposed">Disposed</option>
<option value="selling">Selling</option>
</select>
</td>
<td id="from_field"><input type="text" name="from" style="visibility:hidden" /></td>
<td id="to_field"><input type="text" name="to" style="visibility:hidden" /></td>
<td><input type="submit" name="submit" value="Add Part" /></td>
</tr>
</table>
</form>
function showstuff(element) {
// first hide everything
document.getElementById("from").style.visibility = 'hidden';
document.getElementById("to").style.visibility = 'hidden';
document.getElementById("from_field").style.visibility = 'hidden';
document.getElementById("to_field").style.visibility = 'hidden';
var targets;
// select the IDs that should be unhidden based on element
switch (element) {
case 'in_use': targets = ['from', 'from_field']; break;
case 'relocated': targets = ['to', 'to_field']; break;
...
}
// now unhide the selected IDs.
for (var i = 0; i < targets.length; i++) {
document.getElementById(targets[i]).style.visibility = 'visible';
}
}

Javascript Forms Calculator with No answers

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>

function to disable/enable dynamically generated form fields

I'm no javascript expert and i'm currently trying to create a function for a form that has the same fields repeated depending on a number selected on a previous page.
There could be between 1 and 10 rows of the form fields with each having a radio button selection that will enable/disable each row.
At the moment i've written something but having trouble with concatenating form field names and variable names.
Is anyone able to point me in the right direction please.
Javascript:
var i = 1;
var iChildren = 2; //could be any number - depends what user selected.
function toggle(switchElement) {
for (i = 1; i = iChildren; i++) {
var frmSchoolSelected+i = document.getElementById('<%=c_' & i & '_selected.ClientID%>');
var frmSchoolAge+i = document.getElementById('<%=c_' & i & '_type.ClientID%>');
var frmSchoolType+i = document.getElementById('<%=c_' & i & '_type1.ClientID%>');
var frmSchoolAdditional+i = document.getElementById('<%=c_' & i & '_additional.ClientID%>');
if (switchElement.value == 'Yes') {
frmSchoolSelected+i.disabled = false;
frmSchoolAge+i.disabled = true;
frmSchoolType+i.disabled = true;
frmSchoolAdditional+i.disabled = true;
}
else {
frmSchoolSelected+i.disabled = true;
frmSchoolAge+i.disabled = false;
frmSchoolType+i.disabled = false;
frmSchoolAdditional+i.disabled = false;
}
}
}
Thanks for any help.
J.
EDITED
Example of generated form HTML.
<form method="post" action="schoolingform.aspx" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'Button1')" id="form1">
<table id="Table1" cellspacing="0" cellpadding="0" style="border-width:0px;border-collapse:collapse;">
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><span id="c_1_school_selected" onlick="javascript:toggle(this);">
<input id="c_1_school_selected_0" type="radio" name="c_1_school_selected" value="Yes" />
<label for="c_1_school_selected_0">Yes</label>
<input id="c_1_school_selected_1" type="radio" name="c_1_school_selected" value="No" />
<label for="c_1_school_selected_1">No</label>
</span></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Fred Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_1_selected" type="text" id="c_1_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_1_id" id="c_1_id" value="22" /></td>
<td><select name="c_1_type" id="c_1_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_1_type1" id="c_1_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_1_additional" rows="6" cols="30" id="c_1_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><span id="c_2_school_selected" onlick="javascript:toggle(this);">
<input id="c_2_school_selected_0" type="radio" name="c_2_school_selected" value="Yes" />
<label for="c_2_school_selected_0">Yes</label>
<input id="c_2_school_selected_1" type="radio" name="c_2_school_selected" value="No" />
<label for="c_2_school_selected_1">No</label>
</span></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Sara Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_2_selected" type="text" id="c_2_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_2_id" id="c_2_id" value="23" /></td>
<td><select name="c_2_type" id="c_2_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_2_type1" id="c_2_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_2_additional" rows="6" cols="30" id="c_2_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td align="right" colspan="5"></td>
</tr>
</table>
<input type="hidden" name="iChild" id="iChild" value="2" />
<input type="submit" name="Button1" value="Next" id="Button1" class="submitBtn" />
You are mixing .NET code and JavaScript code. Because .NET runs first, it will try to process the code as you have written it:
<%=c_' & i & '_selected.ClientID%>
and most likely generate an error message because that is invalid code.
A simpler solution might be to use a class name. Then with jQuery, you could condense all of your code into a single call:
$('.ClassName').toggle();
Illegal javascript syntax. You ARE mixing .net and JS
var frmSchoolSelected+i is not allowed.
Also your loop is assigning i instead of testing i (= versus ==)
try this
function toggle(switchElement) {
var clientId = '<%=c_1_selected.ClientID%>';
var isYes = switchElement.value == 'Yes';
for (var i=1; i==iChildren; i++) {
var frmSchoolSelected = document.getElementById(clientId.replace('_1_selected','_'+i+'_selected'));
var frmSchoolAge = document.getElementById(clientId.replace('_1_selected','_'+i+'_type'));
var frmSchoolType = document.getElementById(clientId.replace('_1_selected','_'+i+'_type1'));
var frmSchoolAdditional = document.getElementById(clientId.replace('_1_selected','_'+i+'_additional'));
frmSchoolSelected.disabled = !isYes;
frmSchoolAge.disabled = isYes;
frmSchoolType.disabled = isYes;
frmSchoolAdditional.disabled = isYes;
}
}
A few notes on your approach.
Be aware of how you're using this as it means different things in different contexts. In your case it would be better to pass in the index of the row you're toggling. Your server side code most likely knows what row it's currently generating so this should be easy to accomplish.
As others pointed out, you are mixing client side and server side. In this case i is a client side variable that you're trying to use in a '<%=c_'... which is a server side context
I'm not quite sure why you're putting a + into what should be a variable name, but using a plus sign as part of a variable name isn't legal in JavaScript
switchElement in this case isn't a CheckboxList as you're expecting it to be, it's just an html span element and as such won't have a meaningful value property. You have to look at the actual input elements inside it and see if the yes element is checked (for example).
If you were to go with a JavaScript solution you would need code along these lines
function toggle(i) {
var schoolSelected = document.getElementById('c_' + i + '_school_selected_0').checked;
// client side names of variables will be predictable so to an extent you can get away with
// hard-coding them. Not the best practice, but it'd work
var frmSchoolSelected = document.getElementById('c_' + i + '_selected');
var frmSchoolAge = document.getElementById('c_' + i + '_type');
var frmSchoolType = document.getElementById('c_' + i + '_type1');
var frmSchoolAdditional = document.getElementById('c_' + i + '_additional');
// JavaScript, like some other languages lets you chain assignments like this
frmSchoolSelected.disabled =
frmSchoolAge.disabled =
frmSchoolType.disabled =
frmSchoolAdditional.disabled = !schoolSelected;
}
If you were to approach this from jQuery side I would suggest making a few changes to your HTML as well. Your output can be thought of as a list of mini-forms so instead of having one large table with different rows corresponding to different parts, create a list (or a table with a single column if you aren't ready to give up on table based layout quite yet).
New HTML
<ul>
<li class="school1">
<!-- school information form goes here -->
...
<span id="c_1_school_selected" class="toggle" onclick='toggle("school1")'>
...
</li>
<li class="school2">
<!-- school information form goes here -->
...
<span id="c_1_school_selected" class="toggle" onclick='toggle("school2")'>
...
</li>
...
</ul>
New code
function toggle(row) {
var allInputs = $("#" + row + " :input")
.not(".toggle input:radio");
var state = $(".toggle :checked").val();
if (state == "Yes") {
allInputs.removeAttr("disabled");
} else {
allInputs.attr("disabled", "disabled");
}
}
There are two nice things about this approach:
You are no longer relying on knowing what the ClientID will be as you're dealing with input elements as input elements
You can now refactor this input form into some sort of a repeating control (like a ListView) so if you decide you'd like to change how each row is formatted, it'll be very easy to do (since it'll all be in one place).
I got there eventually, once I had worked out how to add the onclick attribute to the input tag instead of the span tag I could then concentrate on the javascript function.
Code behind
Adds onclick to input tag.
Dim newRadioYes As New RadioButton
newRadioYes.Text = "Yes"
newRadioYes.ID = "c_" & childID & "_school_selected_0"
newRadioYes.Attributes.Add("onclick", "javascript:toggle(this, " & childID & ");")
newRadioYes.Attributes.Add("value", "Yes")
newRadioYes.GroupName = "c_" & childID & "_school_selected"
Dim newRadioNo As New RadioButton
newRadioNo.Text = "No"
newRadioNo.ID = "c_" & childID & "_school_selected_1"
newRadioNo.Attributes.Add("onclick", "javascript:toggle(this, " & childID & ");")
newRadioNo.Attributes.Add("value", "No")
newRadioNo.GroupName = "c_" & childID & "_school_selected"
Generated HTML form
<form method="post" action="schoolingform.aspx" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'Button1')" id="form1">
<table id="Table1" cellspacing="0" cellpadding="0" style="border-width:0px;border-collapse:collapse;">
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><input id="c_1_school_selected_0" type="radio" name="c_1_school_selected" value="Yes" onclick="javascript:toggle(this, 1);" />
<label for="c_1_school_selected_0">Yes</label>
<input id="c_1_school_selected_1" type="radio" name="c_1_school_selected" value="No" onclick="javascript:toggle(this, 1);" />
<label for="c_1_school_selected_1">No</label></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Fred Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_1_selected" type="text" id="c_1_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_1_id" id="c_1_id" value="26" /></td>
<td><select name="c_1_type" id="c_1_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_1_type1" id="c_1_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_1_additional" rows="6" cols="30" id="c_1_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td><strong>School Selected</strong></td>
<td colspan="4"><input id="c_2_school_selected_0" type="radio" name="c_2_school_selected" value="Yes" onclick="javascript:toggle(this, 2);" />
<label for="c_2_school_selected_0">Yes</label>
<input id="c_2_school_selected_1" type="radio" name="c_2_school_selected" value="No" onclick="javascript:toggle(this, 2);" />
<label for="c_2_school_selected_1">No</label></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th>Child</th>
<th style="border-right:1px solid #dddddd;">School Name</th>
<th>School Type</th>
<th>School Type</th>
<th>Additional Information</th>
</tr>
<tr valign="top">
<td><strong>Sara Wilkinson</strong></td>
<td style="border-right:1px solid #dddddd;"><input name="c_2_selected" type="text" id="c_2_selected" disabled="disabled" class="aspNetDisabled" style="width:190px;" />
<input type="hidden" name="c_2_id" id="c_2_id" value="27" /></td>
<td><select name="c_2_type" id="c_2_type" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="Primary">Primary</option>
<option value="Secondary">Secondary</option>
<option value="Higher Education">Higher Education</option>
</select></td>
<td><select name="c_2_type1" id="c_2_type1" disabled="disabled" class="aspNetDisabled">
<option selected="selected" value="State">State</option>
<option value="Independent">Independent</option>
</select></td>
<td><textarea name="c_2_additional" rows="6" cols="30" id="c_2_additional" disabled="disabled" class="aspNetDisabled" style="width:190px;"></textarea></td>
</tr>
<tr>
<td align="right" colspan="5"></td>
</tr>
</table>
<input type="hidden" name="iChild" id="iChild" value="2" />
<input type="submit" name="Button1" value="Next" id="Button1" class="submitBtn" />
Javascript function
function toggle(switchElement, childID) {
var frmSelected = document.getElementsByName('c_' + childID + '_school_selected');
var frmSchoolSelected = document.getElementById('c_' + childID + '_selected');
var frmSchoolAge = document.getElementById('c_' + childID + '_type');
var frmSchoolType = document.getElementById('c_' + childID + '_type1');
var frmSchoolAdditional = document.getElementById('c_' + childID + '_additional');
if (switchElement.value == 'Yes') {
frmSchoolSelected.disabled = false;
frmSchoolAge.disabled = true;
frmSchoolType.disabled = true;
frmSchoolAdditional.disabled = true;
}
else {
frmSchoolSelected.disabled = true;
frmSchoolAge.disabled = false;
frmSchoolType.disabled = false;
frmSchoolAdditional.disabled = false;
}
}
Thanks to those who pointed me in the right direction, much appreciated.

Categories