function to disable/enable dynamically generated form fields - javascript

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.

Related

Calculate column on row add for all rows

I have developed a code to build out salary costs for a project. The problem is that only the first row is calculating.
I have searched and found a few forums discussing the same problem but every approach/code looks completely different. Also, I have copied whole coding examples from youtube videos/forums to replicate a solution and none seems to work. I know there may be issues with ID/class but being new to coding, everything just confuses me. Help!
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name='vetCosting'>
<h3> Salaries </h3>
<table ID="salaries">
<tr>
<th>Classification</th>
<th>Hourly rate</th>
<th>Hours</th>
<th>Cost</th>
<th>Comments</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
<tr>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onFocus="startCalc();" onBlur="stopCalc()"></td>
<td><input type="number" name="salaryHours" value="" onFocus="startCalc();" onBlur="stopCalc()"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="ob_adRows.addRow(this)"></td>
<td><input type="button" value="-" ; onclick="ob_adRows.delRow(this)"></td>
</tr>
</table>
</form>
<script>
function startCalc() {
interval = setInterval("calc()", 2);
}
function calc() {
hrRate = document.vetCosting.hourlyRate.value;
salHours = document.vetCosting.salaryHours.value;
document.vetCosting.salaryCost.value = ((hrRate * 1) * (salHours * 1));
}
function stopCalc() {
clearInterval(interval);
}
</script>
<script>
function adRowsTable(id) {
var table = document.getElementById(id);
var me = this;
if (document.getElementById(id)) {
var row1 = table.rows[1].outerHTML;
function setIds() {
var tbl_id = document.querySelectorAll('#' + id + ' .tbl_id');
for (var i = 0; i < tbl_id.length; i++) tbl_id[i].innerHTML = i + 1;
}
me.addRow = function (btn) {
btn ? btn.parentNode.parentNode.insertAdjacentHTML('afterend', row1) :
table.insertAdjacentHTML('beforeend', row1);
setIds();
}
me.delRow = function (btn) {
btn.parentNode.parentNode.outerHTML = '';
setIds();
}
}
}
var ob_adRows = new adRowsTable('salaries');
</script>
</body>
</html>
I would like to be able to add and remove rows with calculations computing correctly for every row based on data inputs.
My first step would be to change your code from using setInterval() because that is running every 2 milliseconds even when there is no change in the input and the user is simply sitting there. I'd change it to a onKeyUp event that fires much less frequently.
That's done by simply changing your inputs to this:
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc();"></td>
So we get rid of the startCalc() and stopCalc() functions.
Now, once we have multiple rows, we need a way to identify each row. So we give your first row an id of 'row_0' and also pass it through your calc() functions as follows:
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_0');"></td>
We then update your calc() method to this, so that it can use each row individually:
function calc(id) {
var row = document.getElementById(id);
var hrRate = row.querySelector('input[name=hourlyRate]').value;
var salHours = row.querySelector('input[name=salaryHours]').value;
row.querySelector('input[name=salaryCost]').value = ((hrRate * 1) * (salHours * 1));
}
Next, upon clicking the buttons, this error is fired:
Uncaught ReferenceError: ob_adRows is not defined at HTMLInputElement.onclick
To change this, we'll change the function that you've written. Let's first prepare a template for each row, and then simply append it to the innerHTML of the table. However, this won't work because it will also refresh the entire table, hence wiping out data from our existing rows too. So we use this to make a new HTML node with of a row with the id 'row_x':
function newRowTemplate(rowCount) {
var temp = document.createElement('table');
temp.innerHTML = `<tr id='row_${rowCount}'>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp = "calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>`;
return temp.firstChild;
}
We directly make our new functions:
function addRow() {
var newRow = newRowTemplate(rowCount);
table.appendChild(newRow);
rowCount += 1;
}
function removeRow(el) {
el.parentNode.parentNode.remove();
rowCount -= 1;
}
And finally, we use these new functions in our original elements as follows:
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
Here's the final result:
function calc(id) {
var row = document.getElementById(id);
var hrRate = row.querySelector('input[name=hourlyRate]').value;
var salHours = row.querySelector('input[name=salaryHours]').value;
row.querySelector('input[name=salaryCost]').value = ((hrRate * 1) * (salHours * 1));
}
var table = document.getElementById('salaries');
var rowCount = 1;
function newRowTemplate(rowCount) {
var temp = document.createElement('table');
temp.innerHTML = `<tr id='row_${rowCount}'>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp = "calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>`;
return temp.firstChild;
}
function addRow() {
var newRow = newRowTemplate(rowCount);
table.appendChild(newRow);
rowCount += 1;
}
function removeRow(el) {
el.parentNode.parentNode.remove();
rowCount -= 1;
}
<body>
<form name="vetCosting">
<h3> Salaries </h3>
<h3> Salaries </h3>
<table id="salaries">
<tr>
<th>Classification</th>
<th>Hourly rate</th>
<th>Hours</th>
<th>Cost</th>
<th>Comments</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
<tr id="row_0">
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_0');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp="calc('row_0');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>
</table>
</form>
</body>
I just realized a bug in my code. Once row_x is created, and I delete and add another row, it'll create row_x again because the rowCount returns to x. You can fix this by removing the decrement in the remove row function.

Submit button is not getting enabled after checking all the fields

I have a sign up form where I have taken some basic details of the customer and a Submit button.
I have validate all the fields using ajax but confirm password field using javascript. When I write code only using Ajax and not validating Confirm password field it is running perfectly but the problem is when I am validation it using JS submit button is not getting enable.
Sign up form:
<html>
<head>
<title> Registration Form </title>
<script language="javascript">
var flag = false;
function validate(element)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new Activexobject("Microsoft.XMLHTTP");
}
var myField = element;
xmlhttp.open('GET', 'validate.php?' + myField.id + "=" + myField.value, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function ()
{
//alert("Hello");
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var response = xmlhttp.responseText.split("||");
//alert("H2");
}
var divname = "err" + myField.id.substring(3);
var mydiv = document.getElementById(divname);
if (!eval(response[0]))
{
//alert("Fail");
//alert("Value: "+response);
mydiv.innerHTML = response[1];
myField.valid = false;
}
else
{
//alert("Success");
myField.valid = true;
mydiv.innerHTML = "";
}
var btn = document.getElementById("btnSubmit");
btn.disabled = !isValidForm();
}
}
;
function password()
{
var pass = document.getElementById("txtpswd").value;
var Confirm_pass = document.getElementById("txtConfirmpassword").value;
alert("Pass " + pass);
alert("Confirm: " + Confirm_pass);
if (pass == Confirm_pass)
{
flag = true;
alert("True");
document.getElementById("errConfirmpassword").innerHTML = "";
}
else
{
alert("False");
flag = false;
document.getElementById("errConfirmpassword").innerHTML = "Password does not Match";
}
}
;
function isValidForm()
{
var f1 = document.getElementById("txtfname");
var f2 = document.getElementById("txtlname");
var f3 = document.getElementById("txtaddress");
var f4 = document.getElementById("txtzip");
var f5 = document.getElementById("txtnumber");
var f6 = document.getElementById("txtmail");
var f7 = document.getElementById("txtpswd");
var f8 = document.getElementById("txtConfirmpassword");
return(f1.valid && f2.valid && f3.valid && f4.valid && f5.valid && f6.valid && f7.valid && f8.valid);
}
;
</script>
</head>
<body>
<center>
<h1><font color="red"> New User Registration Form </font></h1>
<form name="SignUpForm" method="POST" action="function_customer.php?val=insert">
<table>
<tr>
<td id=q> <font face="Century Schoolbook"> First Name :</font></td> <br>
<td> <input type=text name=txtfname id="txtfname" placeholder=First_name onchange="validate(this);" valid=false> </td>
<td><div id="errfname"/></td>
</tr>
<tr>
<td id=q> Last Name :</td>
<td> <input type=text name=txtlname id="txtlname" placeholder=Last_Name onchange="validate(this);" valid=false> </td>
<td><div id="errlname"/></td>
</tr>
<tr>
<td id=q>Address : </td><br>
<td> <textarea rows=5 cols=20 name="txtaddress" id="txtaddress" onchange="validate(this);" valid=false>
</textarea>
</td>
<td><div id="erraddress"/></td>
</tr>
<tr>
<td id=q> Contact no : </td>
<td> <input type=text name="txtnumber" id="txtnumber" onchange="validate(this);" valid=false> </td>
<td><div id="errnumber"/></td>
</tr>
<tr>
<td id=q> Gender </td>
<td> <select name="txtcity" id="gender">
<option value="Male"> Male </option>
<option value="Female"> Female </option>
</select>
</td>
</tr>
<tr>
<td id=q> City </td>
<td>
<select name="txtcity" id="txtcity">
<option> City </option>
<option value="Vadodara"> Vadodara </option>
<option value="Ahmedabad"> Ahmedabad </option>
<option value="Surat"> Surat </option>
<option value="Rajkot"> Rajkot </option>
<option value="Bhavnagar">Bhavnagar</option>
<option value="Jamnagar">Jamnagar</option>
<option value="Nadidad">Nadidad</option>
<option value="Morvi">Morvi</option>
<option value="Gandhidham">Gandhidham</option>
<option value="Adipur">Adipur</option>
<option value="Anand">Anand</option>
<option value="Baruch">Baruch</option>
<option value="Godhra">Godhra</option>
<option value="Veraval">Veraval</option>
<option value="Navsari">Navsari</option>
</select>
</td>
</tr>
<tr>
<td id=q> ZIP : </td>
<td> <input type=text name=txtzip id="txtzip" onchange="validate(this);" valid=false> </td>
<td><div id="errzip"/></td>
</tr>
<tr>
<td id=q> Email Id : </td>
<td> <input type="email" name=txtmail placeholder=someone#exe.com id="txtmail" onchange="validate(this);" valid=false> </td>
<td><div id="errmail"/></td>
</tr>
<tr>
<td id=q> New Password : </td>
<td> <input type="password" name="txtpswd" id="txtpswd" onchange="validate(this);" valid=false>
</td>
<td><div id="errpswd"/></td>
</tr>
<tr>
<td id=q>Confirm Password : </td><td><input type="password" name=txtConfirmpassword id="txtConfirmpassword" onchange="password();" valid=false>
</td>
<td><div id="errConfirmpassword"/></td>
</tr>
<tr>
<td></td><td><input type=reset name=reset value=Reset>
</td>
</tr>
<tr>
</tr>
</table>
</form>
<br>
<br>
<br>
<br><br>
</center>
</body>
</html>
What should I do to validate all the fields and enabling the Submit Button?
First of all I suggest you read up on the latest HTML elements and use CSS for centering or styling your elements and avoid usage of obsolete elements like <font> and <center>.
Having said that, the issue in your code is that you're not calling validate() to check if the form is valid after password & confirm password fields match, so change your password() like below.
function password(){
var btn = document.getElementById("btnSubmit");
var pass = document.getElementById("txtpswd").value;
var confirm_pass = document.getElementById("txtConfirmpassword").value;
var pwdErrorElement = document.getElementById("errConfirmpassword");
if (pass === confirm_pass){
flag = true;
pwdErrorElement.innerHTML = "";
btn.disabled = !isValidForm();
}else{
flag = false;
pwdErrorElement.innerHTML = "Password does not Match";
btn.disabled = true;
}
}
Also I suggest you to make use of value property on each field to do the validations on client side rather than making a server call for every field change. You can use field values for validations by changing the last statement in your isValidForm() like below.
function isValidForm(){
// get all the field references
return(f1.value && f2.value && f3.value && f4.value
&& f5.value && f6.value && f7.value && f8.value);
}
Once you're done with the JS validations, you can enable the submit button and do validations for all fields at once on your server side on form submit. I mean that's the very purpose of doing client side validations using JS. You don't want to ask for feedback (valid or not) for every field change.
Here's a working Pen with all the above changes.

Java Script not Executing on Wordpress Page (this was a typo in code)

This Question was a Typo
I am Working on a Wordpress 4.0 site and wanted to add a custom calculator on the Home Page. To help customers calculate their savings. The URL of the Home Page is https://northerncrushing.co.uk . I have tested the same code in a normal HTML page and it works fine. But just when I use in a wordpress page, it stops working. I am using Alterna Theme from themeforest with WooCommerce and Booking System Pro from CodeCanyon. This block is bottom right of my homepage above footer.
The HTML is
<div><form>
<table>
<tbody>
<tr>
<td>Crusher Hire Rate :</td>
<td>£ <input id="hireRate" disabled="disabled" name="hireRate" type="number" value="160" /></td>
</tr>
<tr>
<td>Tons Crushed per Job :</td>
<td>   <input id="tonesCrushed" name="tonesCrushed" type="number" value="16" /></td>
</tr>
<tr>
<td>No. of skips SAVED :</td>
<td>   <input id="skipsSaved" disabled="disabled" name="skipsSaved" type="number" value="2" /></td>
</tr>
<tr>
<td>Skip Rate :</td>
<td>£ <input id="skipRate" name="skipRate" type="number" value="145" /></td>
</tr>
<tr>
<td>Skip Saving :</td>
<td>£ <input id="skipSaving" disabled="disabled" name="skipSaving" type="number" value="290" /></td>
</tr>
<tr>
<td>Aggregate cost per tonne :</td>
<td>£ <input id="aggregateCost" name="aggregateCost" type="number" value="10" /></td>
</tr>
<tr>
<td>Aggregate SAVED :</td>
<td>£ <input id="aggregateSaving" disabled="disabled" name="aggregateSaving" type="number" value="160" /></td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
</form></div>
<hr />
<strong>Total SAVING : </strong>£ <input id="totalSaving" disabled="disabled" name="totalSaving" type="number" value="290" />
Calculate
Now the Script is :
<script>
function calculateSavings4000(){
var hr = document.getElementById("hireRate4000").value;
var ton = document.getElementById("tonesCrushed4000").value;
var skiprate = document.getElementById("skipRate4000").value;
var act = document.getElementById("aggregateCost4000").value;
var noskips = Math.ceil(ton/8);
var skipsaving = noskips * skiprate;
var agrsaved = act * ton;
var saving = ((agrsaved + skipsaving) - hr);
var noskip_val = document.getElementById("skipsSaved4000");
noskip_val.value = noskips;
var skipsaving_val = document.getElementById("skipSaving4000");
skipsaving_val.value = skipsaving;
var agrsaved_val = document.getElementById("aggregateSaving4000");
agrsaved_val.value = agrsaved;
var total = document.getElementById("totalSaving4000");
total.value = saving;
}
</script>
Already spent many hours without any luck.
All the help is much appreciated.
The problem is your ID selectors are not set correctly, for instance:
var hr = document.getElementById("hireRate4000").value;
An element with that ID does not exist, I think you want this instead:
var hr = document.getElementById("hireRate").value;
Same thing with your other selectors:
var ton = document.getElementById("tonesCrushed").value;
var skiprate = document.getElementById("skipRate").value;
var act = document.getElementById("aggregateCost").value;
var noskip_val = document.getElementById("skipsSaved");
var skipsaving_val = document.getElementById("skipSaving");
var agrsaved_val = document.getElementById("aggregateSaving");
var total = document.getElementById("totalSaving");

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';
}
}

Change radio button name javascript not working in IE

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>

Categories