How check condition of checkbox when uncheck/check with id of HTML - javascript

I'm using css and javascript to check condition of value of partner Code is null and 01
If user checks checkbox is PARTNER, value of partnerName '01 - Elite' and value of partnerCode is '01' will send when submit
If user unchecks checkbox is PARTNER, value of partnerName is 'NULL' and value of partnerCode is 'NULL' will send when submit
This is my code:
<tr>
<th scope="row">Partner</th>
<td colspan="0" style="margin-top: 4px;">
<input id="parnerNameCheck" name="parnerNameCheck" type="checkbox"/><span>PARTNER</span>
</td>
<td>
<select id="partnerName" name="partnerName" disabled>
<option value="" selected>Choose One</option>
<option>01 - Elite</option>
</select>
</td>
<td>
<input id="partnerCode" name="partnerCode" type="hidden" value="01" />
</td>
</tr>
<script>
$('#parnerNameCheck').click(function() {
console.log('parnerNameCheck checked:' + $("#parnerNameCheck").is(":checked"));
$('#partnerName').prop("disabled", !$(this).prop("checked"));
$('#partnerCode').prop("disabled", !$(this).prop("checked"));
});
</script>
UPDATED:
$('#parnerNameCheck').click(function() {
console.log('parnerNameCheck checked:' + $("#parnerNameCheck").is(":checked"));
$('#partnerName').prop("disabled", !$(this).prop("checked"));
$('#partnerCode').prop("disabled", !$(this).prop("checked"));
$("#partnerCode").val('');
});
But when I uncheck checkbox is PARTNER, value of partnerCode is 01 still sending when submit.
So how to fix the problem? thank a lot

set $("#partnerCode").val('');
$('#parnerNameCheck').click(function() {
console.log('parnerNameCheck checked:' + $("#parnerNameCheck").is(":checked"));
$('#partnerName').prop("disabled", !$(this).prop("checked"));
$('#partnerCode').prop("disabled", !$(this).prop("checked"));
$("#partnerCode").val('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<th scope="row">Partner</th>
<td colspan="0" style="margin-top: 4px;">
<input id="parnerNameCheck" name="parnerNameCheck" type="checkbox"/><span>PARTNER</span>
</td>
<td>
<select id="partnerName" name="partnerName" disabled>
<option value="" selected>Choose One</option>
<option>01 - Elite</option>
</select>
</td>
<td>
<input id="partnerCode" name="partnerCode" type="hidden" value="01" />
</td>
</tr>

I believe you are missing the ability to toggle the value of partnerCode. Your updated code would only set the value of parnetCode to null and that's it.
Below is the code that would switch the values for partnerCode:
$('#parnerNameCheck').click(function() {
console.log('parnerNameCheck: ' + $("#partnerCode").val());
$('#partnerName').prop("disabled", !$(this).prop("checked"));
$('#partnerCode').prop("disabled", !$(this).prop("checked"));
// Declare variables
var partnerCode = $("#partnerCode");
var partnerCodeVal = partnerCode.val();
// Apply condition to $("#partnerCode").val()
// that will switch between values
partnerCode.val(partnerCodeVal === "01" ? "" : "01");
});
Working example - https://jsfiddle.net/ma4orbnw/1/

Related

How to assign value and disable box when selected value from dropdown using jquery

I want to make a validation on the dropdown list. The dropdown list I'm getting from database and I set the option value as GUID because later on I want to save into database. How can I assign an entry type for the each of the selected value in client side and disable the box?
For example:
When I select account 1, the credit textbox will be disabled and only allow user to input in debit textbox.
When I select account 2, the debit textbox will be disabled and only allow user to input in credit textbox.
Result that I want
Account | Debit | Credit |
Account 1| input | disable| //entry type in db is 10, so user allow input in debit and disable credit
Account 2| disable | input | //entry type in db is 20, so user allow input in credit and disable debit
Account 3| input | disable|
Account 4| disable | input |
Account 5| input | disable|
My database column, entry type 10 = debit, 20 = credit
Guid | Account | Entry Type |
19B267DD-FB65-4CD7-AF72-24B3213062B0| Account 1| 10 |
C4A96735-3FE2-447E-9B28-74937B98AC60| Account 2| 20 |
9F55079D-1A55-47C9-81D3-971C60FA790A| Account 3| 10 |
9902E1F6-D6A6-4755-B77D-AE639499536C| Account 4| 20 |
454F9B88-10F9-4179-A830-46C098B689F9| Account 5| 10 |
$('#addrow').click(function() {
addRow();
});
$(document).on('click', '.delete-row', function() {
$(this).parents('.acc-row').remove();
});
$(document).on('keyup', '.row-dr, .row-cr', function(e) {
var dr = 0;
cr = 0;
total_cr = 0,
total_dr = 0;
var $row = $(this).closest("tr");
$(".acc-row").each(function() {
total_dr += $(this).find(".row-dr").val() != "" ? parseFloat($(this).find(".row-dr").val()) : 0
total_cr += $(this).find(".row-cr").val() != "" ? parseFloat($(this).find(".row-cr").val()) : 0
})
$("#debit").val(total_dr.toFixed(2))
$("#credit").val(total_cr.toFixed(2))
});
function addRow() {
var addRows =
'<tr class="acc-row">' +
'<td><a class="delete-row" href="javascript:; ">Delete</i></a></td>' +
'<td><select class="form-control select2" id="ddlAccount"><option label>Account</option><option value="19B267DD-FB65-4CD7-AF72-24B3213062B0">Account 1</option><option value="C4A96735-3FE2-447E-9B28-74937B98AC60">Account 2</option><option value="9F55079D-1A55-47C9-81D3-971C60FA790A">Account 3</option><option value="9902E1F6-D6A6-4755-B77D-AE639499536C">Account 4</option><option value="454F9B88-10F9-4179-A830-46C098B689F9">Account 5</option></select></td>' +
'<td><input class="form-control tx-right row-dr" type="text"></td>' +
'<td><input class="form-control tx-right row-cr" type="text"></td>' +
'</tr>'
$(".acc_table").append(addRows);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="example-input" class="table table-bordered text-nowrap">
<thead>
<tr>
<th class="wd-5p"></th>
<th class=" wd-20p"> </th>
<th class="wd-10p tx-right">Debit</th>
<th class="wd-10p tx-right">Credit</th>
</tr>
</thead>
<tbody class="acc_table">
<tr class="acc-row">
<td>
<a id="delete" href="javascript:;" title="Remove row">Delete</i></a></td>
<td>
<select class='form-control select2' id="ddlAccount">
<option label>Account</option>
<option value="19B267DD-FB65-4CD7-AF72-24B3213062B0">Account 1</option>
<option value="C4A96735-3FE2-447E-9B28-74937B98AC60">Account 2</option>
<option value="9F55079D-1A55-47C9-81D3-971C60FA790A">Account 3</option>
<option value="9902E1F6-D6A6-4755-B77D-AE639499536C">Account 4</option>
<option value="454F9B88-10F9-4179-A830-46C098B689F9">Account 5</option>
</select>
</td>
<td>
<input class="form-control tx-right row-dr" type="text" value=""></td>
<td>
<input class="form-control tx-right row-cr" type="text" value=""></td>
</tr>
</tbody>
<tfoot>
<tr id="hiderow">
<td colspan="6" class="tx-center tx-15"><b><a id="addrow" href="javascript:;" title="Add a row"><i class="fe fe-plus-circle"></i>Add a Row</a></b></td>
<br>
</tr>
<tr>
<td class="valign-middle"></td>
<td class="tx-right">Total</td>
<td class="tx-right">
<input class="form-control tx-right" type="text" placeholder="0.00" id="debit" disabled></td>
<td class="tx-right">
<input class="form-control tx-right" type="text" placeholder="0.00" id="credit" disabled></td>
</tr>
</tfoot>
</table>
<button id="btnAddAccount" type="button">Count </button>
Get all information from your database and turn them into javascript object array.
Fill the select by options.
Create listener for select change which found selected option with more informations and disable the inputs.
// find elements
const selectOptions = [
{
id: '19B267DD-FB65-4CD7-AF72-24B3213062B0',
account: 'Account 1',
entryType: 10
},
{
id: 'C4A96735-3FE2-447E-9B28-74937B98AC60',
account: 'Account 2',
entryType: 20
},
{
id: '9F55079D-1A55-47C9-81D3-971C60FA790A',
account: 'Account 3',
entryType: 10
}
];
// fill all select options
for(let i=0; i<selectOptions.length; i++)
$('select').append(`<option value="${selectOptions[i].id}">${selectOptions[i].account}</option>`);
// create listener for select change
$('select').change(function(e) {
const id = $(this).val(); // get selected id
const foundObjInOption = selectOptions.find(v => v.id === id); // find object in js object array by selected id
// disable input
if(foundObjInOption !== undefined) {
// row explain: get current -> find closest TR in DOM tree -> find element by name -> set values/props
$(this).closest('tr').find('[name="credit"]').prop('disabled', foundObjInOption.entryType === 10).val(null);
$(this).closest('tr').find('[name="debit"]').prop('disabled', foundObjInOption.entryType === 20).val(null);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select class='form-control select2' id="ddlAccount">
<option value="">Select account...</option>
</select>
</td>
<td>
<input class="form-control tx-right row-dr" type="text" value="" name="debit">
</td>
<td>
<input class="form-control tx-right row-dr" type="text" value="" name="credit">
</td>
</tr>
</table>

How to enable Dropdownlist by Checkbox in multirow table using JavaScript HTML

I want to control the dropdownlist to be enabled when the checkbox is checked by respective rows.
My current progress I manage to enable and disable the dropdownlist but its not controlled by the respective rows.
Whenever the checkbox is checked, all dropdownlist were enabled.
the php code is partly from html:
<td>
<select class="selection" name="lotDist[]" >
<option></option>';
==== sql queries in here ====
while ($row2 = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
echo '
<option value="'.$row["LotNo"].' / '.$row2["Grouping"].' - '.$row2["InBulkForm"].'">
'.$row2["Grouping"].' - '.$row2["InBulkForm"].'</option> ';
}
echo '
</select>
</td>
<td>'.$row["LoadingWeek"].'</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row["LotNo"].'" '.$check.'>
</td>
<script>
$(document).ready(function() {
$('.selection').attr('disabled', 'disabled');
var $checkBox = $('.chkBox');
$checkBox.on('change', function(e) {
//get the previous element to us, which is the select
var $select = $('.selection')
if (this.checked) {
$select.removeAttr('disabled');
} else {
$select.attr('disabled', 'disabled');
}
});
});
</script>
With $(this).closest('tr').find('.selection'); you can find the corresponding select box the belongs to the row of the changed checkbox.
The closest() function finds the first parent that matches the selector. Since you are using a table we can select the row with the tr selector and find the corresponding select element within the row.
Also changed the way the select box is enabled and disabled. It's better to change the property then the attribute. and code is shorter too. However your method works as well.
$(document).ready(function() {
$('.selection').attr('disabled', 'disabled');
var $checkBox = $('.chkBox');
$checkBox.on('change', function(e) {
var $select = $(this).closest('tr').find('.selection');
$select.prop('disabled', !this.checked);
/* This works too but its better to change the property and the code is shorter when using the this.checked boolean.
if (this.checked) {
$select.removeAttr('disabled');
} else {
$select.attr('disabled', 'disabled');
}
*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<select class="selection" name="lotDist[]">
<option>1</option>
<option>2</option>
</select>
</td>
<td>week</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
</td>
</tr>
<tr>
<td>
<select class="selection" name="lotDist[]">
<option>1</option>
<option>2</option>
</select>
</td>
<td>week</td>
<td>
<input type="checkbox" class="chkBox" id="chkBox" name="cBox[]" value="'.$row[" LotNo "].'" '.$check.'>
</td>
</tr>
</table>

Change all the dropdown option' s value when the checkbox is checked

I'm wondering when i check the checkbox (Select all), can all the dropdowns be forced to select "Y"
if it's unchecked, all the dropdowns will be forced to select "N"
Many thanks.
var check = $('#check');
check.onclick(function(){
$('.option') = "Y";
})
<table id="table">
<th>
select all <input type="checkbox" id="check">
</th>
<tr>
<td>
<select class="option status">
<option>Y</option>
<option>N</option>
</select>
</td>
</tr>
<tr>
<td>
<select class="option status">
<option>Y</option>
<option>N</option>
</select>
</td>
</tr>
Orginally i have a table that show the total amount needs to be paid and payment in arrears
$(document).ready(function() {
$("#table").on('input', '.txtCal, .status', function() {
calculate();
});
function calculate() {
var calculated_total_sum = 0;
var to_be_paid = 0;
$("#table tr").each(function() {
var get_textbox_value = $('.txtCal', this).val();
var get_payment_status = $('.status', this).val();
if (get_textbox_value && get_payment_status) {
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
if (get_payment_status === 'N') {
to_be_paid += parseFloat(get_textbox_value);
}
}
});
$(".total_sum_value").html(calculated_total_sum);
$(".arrears").html(to_be_paid);
}
calculate();
});
HTML
<div class="col-lg-6 result">
<div class="input-group">
<p>
<span class="input-group-addon">Total Payment</span>
<span class="input-group-addon">$HKD</span>
<span class="input-group-addon total_sum_value"></span></p>
<br><br><br>
<p>
<span class="input-group-addon">In Arrears</span>
<span class="input-group-addon">$HKD</span>
<span class="input-group-addon arrears"></span></p>
</div>
Each table row will have a select dropdown that consists of two option "Y" and "N". Originally, i have to manually change its table row option, and the payment in arrears will change accordingly.
For example, if the dropdown is "Y" which means paid, the amount of payment in arrears will decrease automatically.
Now after adding the select all function, to force all dropdowns to select "Y",for some reason the calculate function fail to work.
Any ideas
Add a common class to all the select and value to the option. Trigger a function on checking the checkbox which will select all Y option.Use jquery 'prop' method to add the property
function selectAll(elem) {
if ($(elem).prop('checked')) {
$('.selOptions option[value=Y]').prop('selected', true);
} else {
$('.selOptions option[value=N]').prop('selected', true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<th>
select all <input type="checkbox" onchange="selectAll(this)">
</th>
<tr>
<td>
<select class="selOptions">
<option value = "Y">Y</option>
<option value = "N">N</option>
</select>
</td>
</tr>
<tr>
<td>
<select class="selOptions">
<option value = "Y">Y</option>
<option value = "N">N</option>
</select>
</td>
</tr>
</table>
Using vainilla JS
<table>
<th>
select all <input id="selectAll" type="checkbox" />
</th>
<tr>
<td>
<select>
<option>Y</option>
<option>N</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option>Y</option>
<option>N</option>
</select>
</td>
</tr>
</table>
<script>
var selectAll = document.getElementById('selectAll');
var options = document.getElementsByTagName('select');
selectAll.addEventListener( 'change', function() {
if(this.checked) {
for(var i=0; i < options.length; i++) {
options[i].selectedIndex = 0;
}
}
});
</script>
First determine when the checkbox is checked or not.
$('#check').on('change', function() { if ($(this).is(':checked')) {...
Then you could use a selector based on an option's text content (you don't have a value attribute which you should but it's still functional.)
$('option:contains(Y)')...
Then use .prop() method to programmatically change it's selected state.
.prop('selected', true);
Demo
$('#check').on('change', function() {
if ($(this).is(':checked')) {
$('option:contains(Y)').prop('selected', true);
} else {
$('option:contains(N)').prop('selected', true);
}
});
<table>
<th>
select all <input type="checkbox" id="check">
</th>
<tr>
<td>
<select class="option">
<option>--</option>
<option>Y</option>
<option>N</option>
</select>
</td>
</tr>
<tr>
<td>
<select class="option">
<option>--</option>
<option>Y</option>
<option>N</option>
</select>
</td>
</tr>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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.

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