I have a table in which there are checkboxes, some checkboxes are disabled. I want to add an onclick attribute to all disabled checkboxes using JavaScript or jQuery.
HTML
<table class="docs_table" id="myTable2">
<tr id="node-22" class="disabled_element">
<td title="Document can't be selected.">
<input type="checkbox" name="docs" id="/root/docname" value="/root/docname" disabled />
</td>
</tr>
<tr id="node-23" class="">
<td title="">
<input type="checkbox" name="docs" id="/root/docname2" value="/root/docname2" />
</td>
</tr>
<tr id="node-24" class="disabled_element">
<td title="Document can't be selected.">
<input type="checkbox" name="docs" id="/root/docname3" value="/root/docname3" disabled />
</td>
</tr>
</table>
In above code the docname input box should get below as onclick.
onclick="javascript:if(confirm('Press OK to confirm')){ document.location='/pathtoscript?command=dosomething&name=docname'};return false;"
and docname3 should get the below
onclick="javascript:if(confirm('Press OK to confirm')){ document.location='/pathtoscript?command=dosomething&name=docname3'};return false;"
What I tried
$('table tr td input[type="checkbox"]').each(function () {
if ($( this ).prop('disabled')) {
$( this ).closest('tr').addClass('lineThrough');
$( this ).attr('onClick','onclick="javascript:if(confirm('Press OK to confirm')){ document.location='/pathtoscript?command=dosomething&name=docname'};return false;"');
}
});
But it doesn't work, and also I wonder how to deal with different docname because in onclick statement name=docname will be different for each input box.
Fiddle
I did it using this answer.
<table class="docs_table" id="myTable2">
<tr id="node-22" class="disabled_element">
<td title="Document is being edited by someone.">
<div style="display:inline-block; position:relative;">
<input type="checkbox" name="docs" id="/root/docname" value="/root/docname" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>
</td>
</tr>
<tr id="node-23" class="child">
<td title="">
<input type="checkbox" name="docs" id="/root/docname2" value="/root/docname2" />
</td>
</tr>
<tr id="node-22" class="disabled_element">
<td title="Document is being edited by someone.">
<div style="display:inline-block; position:relative;">
<input type="checkbox" name="docs" id="/root/docname3" value="/root/docname3" disabled />
<div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>
</td>
$('table tr td input[type="checkbox"] + div').each(function () {
if ($(this).prev('input[disabled]')) {
$(this).closest('tr').addClass('lineThrough');
$(this).click(function () {
if (confirm('Press OK to confirm')) {
var docname = $(this).prev('input[disabled]').prop('value');
docname = docname.substring(docname.lastIndexOf('/') + 1);
document.location = '/pathtoscript?command=dosomething&name=' + docname;
}
});
}
});
Disabled elements don't generate mouse events. So basically what I did is added a div around the disabled inputs and added some JS to match it.
JSFiddle
In case, it is not possible for you to change your existing HTML structure and want to perform the action on click of the closest <td> element, please use the below code.
Javascript (jQuery)
$(document).ready(function(){
$('table tr td input[type="checkbox"]').each(function () {
if ($( this ).prop('disabled')) {
$( this ).closest('tr').addClass('lineThrough');
var valStr = $(this).val();
$( this ).closest('td').attr('onClick', 'clickFn("'+valStr+'");');
//console.log($( this ).closest('td').attr('onClick'));
}});
});
function clickFn(valStr){
if(confirm('Press OK to confirm')){
valStr = valStr.substring(valStr.lastIndexOf('/') + 1);
newHref = '/pathtoscript?command=dosomething&name=' +valStr;
//console.log(newHref);
document.location = newHref;
}
}
Demo
Related
function disableField()
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$("input").not('.DeleteButton').prop('disabled', false);
}else{
$("input").prop('disabled', false);
}
}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').not('.DeleteButton').val('').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField()" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
I have a table with a drop-down column in it. Whenever i change the values of drop-down my corresponding fields get enabled. The problem i am getting is if i change the values of my drop-down of previous row the columns of current row also get enabled.Any help will be appreciated. Thanks.
Edit:I have added 'Add Row' function too in my code.
I have added some changes in your disableField function. Pass parameter(this) disableField(this) in that function on chnage event.
function disableField(elem)
{
var Count = $('#dataTable tr').length;
if (Count == 2){
$(elem).closest('tr').find("input").not('.DeleteButton').prop('disabled', false);
}
else{
$(elem).closest('tr').find("input").prop('disabled', false);
}}
//--------------------------------------------------
var regex = /^([a-zA-Z0-9 _-]+)$/;
var cindex = 0;
var quicklink = '' ;
$(document).on('click','.Buttons', function(addrow) {
var count = $('table tr:last input:text').filter((_,el) => el.value.trim() == "").length;
if(count || !$('.id_100 option[value=code]').attr('selected','selected')){
alert("Please fill the current row");
return false;
}
var $tr = $('#dataTable tbody tr:last');
var $clone = $tr.clone(true);
cindex++;
$clone.find(':input').not('select').attr('disabled', true);
$clone.attr('id', 'id'+(cindex) ); //update row id if required
//update ids of elements in row
$clone.find("*").each(function() {
var id = this.id || "";
if(id != ""){
var match = id.match(regex) || [];
if (match.length == 2) {
this.id = this.name + (cindex);
}
}
});
$tr.after($clone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0" id="mainbox" class="mainbox"><tr><td>
<div class="toppanel"><ul><li></li></ul></div>
<div class="abcd"> <!--mainbox middlepanel start-->
<table cellspacing="0" cellpadding="0" border="0" id="maintable" class="maintable">
<tr>
<td valign="top">
<div id="pageheadingpanel">
<div id="pageheading">Quick Link Widget Configuration</div>
<div id="pageheadingdate"><xsl:call-template name="formatted_date"/></div>
</div>
</td>
</tr>
<tr>
<td height="100%" valign="top">
<div class="y_scroll" id="contentarea">
<div class="contentarea"><!--contentarea start-->
<span id="box" class="box"> <!--rounded curve/border start-->
<div class="middlepanel"> <!--contentarea box middlepanel start-->
<div style="display:block" id="textBox1" >
<span id="box1" class="box">
<div class="toppanel"><ul><li></li></ul></div>
<div class="middlepanel">
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField(this)" >
<option value="">Select</option>
<xsl:for-each select="values from local db">
<xsl:sort order="ascending" select="description"/>
<option value="{description}">
<xsl:value-of select="description"/>
</option>
</xsl:for-each>
</select>
</div> </td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="{//RESPONSE}" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="35" value="{//RESPONSE}" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="15" disabled="true" class="objinputtext3" size="35" value="{//RESPONSE}" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>
<div class="buttonarea">
<ul>
<li><input tabindex="6" id="Button3" value="Add New Row" class="Buttons" name="Button3" type="button" /></li>
</ul>
</div>
All in all there is to much extraneous code so the following answer has different code yet can be applied to the clunky code provided in question. I recommend that your code be more streamlined like the following demo provided in this answer.
Here's some suggestions:
If you are using multiple form controls (ex. <button>, <input>, <textarea>, <select>, etc), wrap everything into a <form>
If you have multiple tags (aka elements) that the user can click, submit, reset, change, input, etc register the events to the <form>
In order to find the exact form control that was clicked, changed, etc. use the Event.target property to find it or this keyword and the Event.data parameter.
$('form selector').on('event type', Event.data, callback function)
The #id and [name] attributes are unnecessary unless you are using certain Web APIs such as HTMLFormControlsCollection or HTMLFormElement
Never use event attributes (ex onchange="callback()") when using jQuery. Use the proper jQuery method or .on() method.
// jQuery method
$(selector).click(callback)
// .on() method
$(selector).on('click', callback)
Minor details:
The [type] attribute does not apply to the <select> tag.
Use <th> instead of <td> within <thead>
[maxlength] of 500 is ridiculous. Use <textarea> instead of <input>
Details are commented in demo
/*
Register form.io to the 'submit', 'click', and 'change' events
Note the callback function does not have `()` suffixed because it would be
interpreted as: "run function now"
The callback function doesn't run immediately it runs when a registered event is triggered.
*/
$('.io').on('submit click change', eventHandler);
// Define the counter
let counter = 0;
// Always pass the Event Object when defining a callback function
function eventHandler(event) {
// The Event Object has several properties...
// Get the type of event triggered (ie submit, change, or click)
let eType = event.type;
/*
Get the origin element of event
if 'submit' target will be <form>
if 'click' target will be <button>
if 'change' target will be <select>
*/
let eNode = event.target;
// Pass the event type through a switch() function...
switch (eType) {
// if type is 'submit'...
case 'submit':
// Create a deep clone of the first row
let clone = $('.grid tr:first-child').clone(true, true);
// Add clone as the last child of the <tbody>
$('.grid').append(clone);
// On .each() elment with class '.data' found within the clone...
clone.find('.data').each(function(i) {
// disable it
this.disabled = true;
// remove its value
this.value = '';
});
// Increment the counter by 1
counter++;
// Dereference the clone and assign id as row+counter
clone[0].id = `row${counter}`;
/*
Prevent default behavior:
Reset <form>
Send data to a server
*/
event.preventDefault();
// Stop event from bubbling any further up the event chain
event.stopPropagation();
// ...otherwise skip this case and continue onto the next case
break;
// if type is 'click'...
case 'click':
// if the clicked element (ie <button>) has class: '.del'...
if ($(eNode).hasClass('del')) {
// Get the clicked <button>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if that <tr> is NOT the first <tr>...
if (row.index() !== 0) {
// remove the <tr>
row.remove();
}
}
event.stopPropagation();
break;
// if type is 'change'...
case 'change':
// if changed element (ie <select>) class is '.type'...
if ($(eNode).hasClass('type')) {
// Get the changed <select>'s ancestor <tr>
let row = $(eNode).closest('tr');
// if changed <select>'s value is NOT "X" return true otherwise return false
let pick = eNode.value !== "X" ? true : false;
/*
On .each() element with class .data within the <tr>
disable the .data if <select>'s value is "X"
Otherwise enable the .data
and then remove the .data value
*/
row.find('.data').each(function(i) {
this.disabled = !pick;
this.value = '';
});
}
event.stopPropagation();
break;
default:
event.stopPropagation();
break;
}
}
:root {
font: 400 3vw/1.2 Arial
}
form {
width: max-content;
margin: 10px auto
}
table {
table-layout: fixed;
border-collapse: separate;
border-spacing: 4px;
width: 90vw
}
th:first-of-type {
width: 20%
}
th:nth-of-type(2) {
width: 35%
}
th:nth-of-type(3) {
width: 35%
}
th:last-of-type {
width: 10%
}
td {
padding: 0 8px
}
select,
textarea,
button {
display: block;
min-width: 97%;
min-height: 1.2rem;
font-size: initial;
}
select {
padding: 2px 0 2px 2px
}
textarea {
resize: vertical;
overflow-y: auto;
overflow-x: hidden
}
<form class='io'>
<table>
<thead>
<tr>
<th>Type</th>
<th>Desciption</th>
<th>Image/URL</th>
<th><button>➕</button></th>
</tr>
</thead>
<tbody class='grid'>
<tr>
<td>
<select class='type'>
<option value="X" default></option>
<option value="GDS">Guides</option>
<option value="PRO">Promos</option>
<option value="TEM">Templates</option>
<option value="VID">Videos</option>
</select>
</td>
<td><textarea class='desc data' rows='1' cols='20' disabled></textarea></td>
<td><textarea class='urls data' rows='1' cols='20' disabled></textarea></td>
<td><button class='del' type='button'>❌</button></td>
</tr>
</tbody>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have to clone my <tr> and I have list of checkbox like code below and when I add new row with list of checkbox and then I click on check box to show value in textbox field_resultsthe value not show only on first textbox not yet clone.
How when I add new tr and then when I click on which list of checkbox in which tr they will show value of my click in the same tr.
$("#add-new").on("click", function () {
$tr = $(this).closest("tr").next().clone(true);
$tr.insertAfter($(this).closest("tr"));
});
$(document).ready(function () {
$checks = $('#mych_box :checkbox');
$checks.on('change', function () {
var string = $checks.filter(":checked").map(function (i, v) {
return this.value;
}).get().join(",");
console.log(string);
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<button type="button" id="add-new">Add New</button>
</td>
</tr>
<tr>
<td>
<input type="text" id="field_results" name="field_results[]"/><br>
<div class="multiselect" style="height: 100px;width: auto;" id="mych_box">
<label>
<input type="checkbox" id="virt_software_chb1" name="virt_software[]" value="White"/>White
<input type="checkbox" id="virt_software_chb2" name="virt_software[]" value="Red"/>Red
<input type="checkbox" id="virt_software_chb3" name="virt_software[]" value="Blue"/>Blue
</label>
</div>
</td>
</tr>
As defined above use true in clone to bind default events and use class instead of id to group element
$(".virt_software_chb").on('change', function () {
var string = $(this).closest('td').find('.virt_software_chb').filter(":checked").map(function (i, v) {
return this.value;
}).get().join(",");
$(this).closest('td').find('.field_results').val(string);
});
$("#add-new").on("click", function () {
$tr = $(this).closest("tr").next().clone(true);
$tr.insertAfter($(this).closest("tr"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<button type="button" id="add-new">Add New</button>
</td>
</tr>
<tr>
<td>
<input type="text" class="field_results" name="field_results[]"/><br>
<div class="multiselect" style="height: 100px;width: auto;" id="mych_box">
<label>
<input type="checkbox" class="virt_software_chb" name="virt_software[]" value="White"/>White
<input type="checkbox" class="virt_software_chb" name="virt_software[]" value="Red"/>Red
<input type="checkbox" class="virt_software_chb" name="virt_software[]" value="White"/>White
</label>
</div>
</td>
</tr>
</table>
withDataAndEvents (default: false)
A Boolean indicating whether event handlers should be copied along with the elements. As of jQuery 1.4, element data will be copied as well. - clone()
Try passing in true and see what you get.
$tr = $(this).closest("tr").next().clone(true);
I have the below code in my ASP (CLassic) page (part of a page with dozens of checkboxes set from the db):
<tr height="30px">
<td class="summarytext">Show Gender Pay Gap Options</td>
<td class="formtext">
<input class="checkbox" type="checkbox" name="chkDisplayGPGOptions" <%if g_blnchkDisplayGPGOptions = True then Response.Write("checked")%>>
</td>
<td colspan="7"> </td>
<td>
<input type="button" class="help" align="left" id="Button3" onmousemove="javascript:DisplayHelp(150,-160, 10, 'HELP', 'Select if you want to exclude this pay type in netpay for attachment calculations.', this)" onmouseout="javascript:HideHelp()" WIDTH="16px" HEIGHT="16px">
</td>
<DIV id="divGPGOptiona" style="display:none">
<table>
<tr height="30px">
<td class="summarytext">Include Bonus in calculation for GPG reporting</td>
<td class="formtext">
<input class="checkbox" type="checkbox" name="chkIncludeBonusInGPG" <%if g_blnchkDisplayGPGOptions = True then Response.Write("checked")%>>
</td>
</tr>
<tr height="30px">
<td class="summarytext">Include Gross Pay in calculation for GPG reporting</td>
<td class="formtext">
<input class="checkbox" type="checkbox" name="chkIncludeGrossPayInGPG" <%if g_blnchkDisplayGPGOptions = True then Response.Write("checked")%>>
</td>
</tr>
</table>
</DIV>
</tr>
what I'd like to do is show and hide the DIV divGPGOptiona when the checkbox chkDisplayGPGOptions is checked...
Is there was some way of using just CSS for this, or will I need to do this with JavaScript and the DOM?
Create a class that represents "hide" state and toggle it when checkbox changes.
See how:
var checkbox = document.querySelector('input[name="check"]');
var div = document.querySelector('#container');
checkbox.addEventListener('change', function (e) {
if (div.classList.contains('is-hide')) {
div.classList.remove('is-hide');
} else {
div.classList.add('is-hide');
}
});
.is-hide {
display: none;
}
<input type="checkbox" name="check" />
<div id="container">Here goes the content.</div>
One possible solution is to toggle the display with JavaScript. You don't need jQuery for this. It can be done in native JavaScript.
var checkBox = document.getElementById("check-box");
var myDiv = document.getElementById("my-div");
myDiv.style.display = "none";
checkBox.addEventListener("click", function() {
if (myDiv.style.display == "none") {
myDiv.style.display = "block";
}
else {
myDiv.style.display = "none";
}
});
<div id="my-div">This is a div</div>
<p>The div above is hidden by default. Click the checkbox to toggle on and off</p>
<input id="check-box" type="checkbox" />
CSS Code:
.hidden{
display: none;
}
html Code:
<DIV id="divGPGOptiona" class="hidden" >
Jquery Code:
$(".checkbox").on('click',function(){
if($(".checkbox").prop("checked")){
$("#divGPGOptiona").removeClass("hidden");
}
else{
$("#divGPGOptiona").addClass("hidden");
}
});
Pure CSS using the siblings + selector.
So this can be done if you have the div as a sibling of the checkbox. In order for you to replicate, you would need to change your HTML structure. Which is advised, because you are placing a div inside a table row <tr>, without a table cell. Why?
.checkboxSibling {
display: none;
}
/*.checkbox:checked + .checkboxSibling {
display: block;
}*/
input[name="chkDisplayGPGOptions"]:checked + .checkboxSibling {
display: block;
}
<div>
Input 1 -
<input class="checkbox" name="chkDisplayGPGOptions" type="checkbox"/>
<div class="checkboxSibling">Checkbox Checked</div>
</div>
<div>
Input 2 -
<input class="checkbox" name="someOtherName" type="checkbox"/>
<div class="checkboxSibling">Checkbox Checked</div>
</div>
Below is my HTML and jQuery code. jQuery displays the hidden elements, except for the #image4 and #video4 elements, which stay hidden with if I select image or video. All the other elements get displayed correctly.
Any idea why those two won't show?
JS:
$(document).ready(function(){
var fields = jQuery('#image_type');
var select = this.value;
fields.change(function () {
if ($(this).val() == 'image') {
alert($(this).val());
$('#images_pop_up').show();
$('#video1').hide();
$('#video2').hide();
$('#video3').hide();
$('#video4').hide();
$('#image1').show();
$('#image2').show();
$('#image3').show();
$('#image4').show();
$(' #image5').show();
}
else {
$('#images_pop_up').show();
$('#image1').hide();
$('#image2').hide();
$('#image3').hide();
$('#image4').hide();
$('#image5').hide();
$('#video1').show();
$('#video2').show();
$('#video3').show();
$('#video4').show();
$('#image5').show();
}
});
});
HTML:
<div id ="images_pop_up" style="display:none;">
<span id="image1" style="display:none;" ><img src="/uploads/commerce/images/large/easton-163135-wheeled-bag.jpg" border="0" alt="easton-163135-wheeled-bag.jpg" title=" easton-163135-wheeled-bag.jpg " class="productimage"><input type="hidden" name="products_previous_image_lrg" value="easton-163135-wheeled-bag.jpg"><br>Nice bag</span>
<span id ="video1" style="display:none;"></span></td>
<td class="textSmall" valign="top">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<span id="image3" style="display:none;"><input type="hidden" name="products_previous_image_lrg" value="easton-163135-wheeled-bag.jpg"><input type="hidden" name="products_previous_image_lrg_caption" value="Nice bag"></span>
<span id ="video3"><input type="hidden" name="products_previous_video_embed"><input type="hidden" name="products_previous_video_embed_caption"></span>
<td class="textSmall" valign="top"><span id="image4" style="display:none;">New Image File: <input type="text" name="products_image_lrg" value="easton-163135-wheeled-bag.jpg"><br>Image Caption: <input type="text" name="products_image_lrg_caption" value="Nice bag"></span>
<span id ="video4" style="display:none;">Video Embed field: <input type="text" name="products_video_embed"><br>Video Image Caption: <input type="text" name="products_video_embed_caption"></span>
</td>
<td><span id="image5" style="display:none;"> </span></td>
</tr>
<tr>
<td colspan="2">
<div id='div_img_lrg'></div>
</td>
</tr>
</table>
</td>
</div>
What sticks out most to me is that you're copy pasting when you could be putting CSS to work for you by giving them all the same class (or the appropriate groups of elements the same class at least) and then hiding and showing them based on that.
Your bug is probably caused by a slight typo somewhere in the selectors or the place where you're setting the ids in the markup.
try like this
$(document).ready(function () {
var fields = jQuery('#image_type');
var select = this.value;
$('#image_type').change(function () {
if ($(this).val() == 'image') {
alert($(this).val());
$("[id^=image]").show();
$("[id^=video]").hide();
} else {
$("[id^=video]").show();
$("[id^=image]").hide();
}
});
});
All,
I have the following code. How can I fix it so that the category checkbox for each category is checked only if all the items under that are checked?
Thanks
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
</script>
<script language="JavaScript">
function toggleTableRows()
{
$(document).ready(function() {
$('img.parent')
.css("cursor","pointer")
.toggle(
function() {
$(this).attr("title","Click to Collapse")
$(this).attr("src","arrow_expanded.gif");
$('tr').siblings('#child-'+this.id).toggle();
},
function() {
$(this).attr("title","Click to Expand");
$(this).attr("src","arrow_collapsed.gif");
$('tr').siblings('#child-'+this.id).toggle();
}
);
initCheckBoxes();
});
}
function toggleCheckboxes(current, form, field) {
$(document).ready(function() {
$("#"+ form +" :checkbox[name^='"+ field +"[']").attr("checked", current.checked);
});
}
function toggleParentCheckboxes(current, form) {
var checked = ($("#"+ form +" :checkbox[name='"+ current.name +"']").length == $("#"+ form +" :checkbox[name='"+ current.name +"']:checked").length);
// replace '[anything]' with '' instead of just '[]'
$("#"+ form +" :checkbox[name='"+ current.name.replace(/\[[^\]]*\]/, "") +"']").attr("checked", checked);
}
function initCheckBoxes(form) {
$("#"+ form +" :checkbox:checked").each(function() {
if (this.name.match(/chk[0-9]\[.*\]/)) {
toggleParentCheckboxes(this, form);
}
});
}
</script>
<script language="JavaScript">toggleTableRows();</script>
</head>
<body>
<form name="frmDinnerMenu" id="frmDinnerMenu" method="POST" action="">
<table border=1>
<tr>
<td><img class="parent" id="0" src="arrow_collapsed.gif" title="Click to Expand">Category - Fruits</td>
<td><input type="checkbox" name="chk0" onclick="toggleCheckboxes(this, 'frmDinnerMenu', 'chk0');"/></td>
</tr>
<tr style="display: none;" id="child-0">
<td> Apple</td>
<td><input type="checkbox" value="0" name="chk0[1]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr style="display: none;" id="child-0">
<td> Banana</td>
<td><input type="checkbox" checked value="0" name="chk0[2]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr style="display: none;" id="child-0">
<td> Orange</td>
<td><input type="checkbox" checked value="0" name="chk0[5]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td>
</tr>
<tr><td><img class="parent" id="1" src="arrow_collapsed.gif" title="Click to Expand">Category - Vegetables</td><td><input type="checkbox" name="chk1" onclick="toggleCheckboxes(this, 'frmDinnerMenu', 'chk1');"/></td></tr>
<tr style="display: none;" id=child-1><td> Cabbage</td><td><input type="checkbox" checked value="0" name="chk1[21]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td></tr>
<tr style="display: none;" id=child-1><td> Tomatoes</td><td><input type="checkbox" value="0" name="chk1[26]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td></tr>
<tr style="display: none;" id=child-1><td> Green Peppers</td><td><input type="checkbox" checked value="0" name="chk1[29]" onclick="toggleParentCheckboxes(this, 'frmDinnerMenu');"/></td></tr>
</table>
</form>
</body>
</html>
gave it a try + some notes which you really should apply too
Some things I fixed to be able to work with this thing
missing title attribute in head (added)
Both img-tags have invalid numeric-only id (changed to make a valid id)
Multiple tr's with id child-0 (made ids unique but still based on img id)
Multiple tr's with id child-1 (made ids unique but still based on img id)
alt attribute on both img-tags missing (added)
too-many inline javascript onclick handlers (removed/ replaced with jQuery bindings and jQuery to find right parameters)
too-many inline css on some tr's (removed/replaced with css class)
missing type attribute on the script tags (added)
initcheckboxes is called without parameter, thus won't work as selector (added param to toggleTableRows)
made some of the jQuery foo more flexible and robust
Fixed HTML + javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html;charset=ascii">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
</script>
<script type="text/javascript" language="JavaScript">
function toggleTableRows(form) {
$(document).ready(function() {
$('img.parent')
.css("cursor","pointer")
.toggle(function() {
var x = $(this);
x.attr("title","Click to Collapse")
.attr("src","arrow_expanded.gif");
x.parents("tr").eq(0).siblings("[id^=child-"+x.attr("id")+"]").toggle();
}, function() {
var x = $(this);
x.attr("title","Click to Expand")
.attr("src","arrow_collapsed.gif");
x.parents("tr").eq(0).siblings("[id^=child-"+x.attr("id")+"]").toggle();
});
initCheckBoxes(form);
});
}
function toggleCheckboxes(current, form, field) {
$(document).ready(function() {
$("#"+ form +" input:checkbox[name^='"+ field +"[']").attr("checked", current.checked);
});
}
function toggleParentCheckboxes(current, form) {
var name = current.name.replace(/\[[^\]]*\]/, "");
var selected = $("input:checkbox[name^='" + name + "[']");
var checked = (selected.size() == selected.filter(":checked").size());
$("#"+ form +" :checkbox[name='" + name + "']").attr("checked", checked);
}
function initCheckBoxes(form) {
$("#"+ form +" input:checkbox:checked").each(function() {
if (this.name.match(/chk[0-9]\[.*\]/)) {
toggleParentCheckboxes(this, form);
}
});
}
</script>
<script type="text/javascript" language="JavaScript">toggleTableRows("frmDinnerMenu");</script>
<script type="text/javascript">
$(document).ready(function() {
$("tr:not([id]) input").click(function() {
var ele = $(this);
toggleCheckboxes(this, ele.parents("form").eq(0).attr("name"), ele.attr("name"));
ele=null;
});
$("tr[id] input").click(function() {
toggleParentCheckboxes(this, $(this).parents("form").eq(0).attr("name"))
});
});
</script>
<style type="text/css">tr.c1 {display: none;}</style>
</head>
<body>
<form name="frmDinnerMenu" id="frmDinnerMenu" method="post" action="">
<table border="1">
<tr>
<td><img class="parent" id="i0" src="arrow_collapsed.gif" alt="fruits" title="Click to Expand" name="0">Category - Fruits</td>
<td><input type="checkbox" name="chk0"></td>
</tr>
<tr class="c1" id="child-i00">
<td>Apple</td>
<td><input type="checkbox" value="0" name="chk0[1]"></td>
</tr>
<tr class="c1" id="child-i01">
<td>Banana</td>
<td><input type="checkbox" checked value="0" name="chk0[2]"></td>
</tr>
<tr class="c1" id="child-i02">
<td>Orange</td>
<td><input type="checkbox" checked value="0" name="chk0[5]"></td>
</tr>
<tr>
<td><img class="parent" id="i1" src="arrow_collapsed.gif" alt="vegetable" title="Click to Expand" name="1">Category - Vegetables</td>
<td><input type="checkbox" name="chk1"></td>
</tr>
<tr class="c1" id="child-i10">
<td>Cabbage</td>
<td><input type="checkbox" checked value="0" name="chk1[21]"></td>
</tr>
<tr class="c1" id="child-i11">
<td>Tomatoes</td>
<td><input type="checkbox" value="0" name="chk1[26]"></td>
</tr>
<tr class="c1" id="child-i12">
<td>Green Peppers</td>
<td><input type="checkbox" checked value="0" name="chk1[29]"></td>
</tr>
</table>
</form>
</body>
</html>
So I'm going to try and answer this question (hey, it's a challenge!).
First let me point out why people don't like your question though:
Duplicate ids: id=child-1 appears multiple times, as do others. Ids should be unique, otherwise you'll run into selector problems (getElementById really doesn't like it)
Inline javascript: It's hard to determine from looking at the code what actions happen when. You should isolate all functionality in a separate script file. This will make maintenance significantly easier in the future, and allow the browser to cache functionality.
     .... consider using "padding-left: 15px". Do it for us.
That all being said, consider using a more targeted selector. In this example, notice name^=
function toggleParentCheckboxes(current, form) {
var name = current.name.replace(/\[[^\]]*\]/, "");
var selector = ":checkbox[name^='" + name + "[']";
var checked = ($(selector).length == $(selector + ":checked").length);
$("#"+ form +" :checkbox[name='" + name + "']").attr("checked", checked);
}