I have a code like this...
<html>
<head>
<title>test</title>
<script type="text/javascript">
var counter = 2;
var idCounter= 3;
function addNew() {
if(counter<=5){
// Get the main Div in which all the other divs will be added
var mainContainer = document.getElementById('mainContainer');
// Create a new div for holding text and button input elements
var newDiv = document.createElement('div');
newDiv.id='divs'+counter;
// Create a new text input
var newText = document.createElement('input');
var newText1 = document.createElement('input');
newText.type = "input";
newText.id="ans"+(idCounter);
idCounter++;
newText1.type = "input";
newText1.id="ans"+(idCounter);
idCounter++;
// newText.value = counter;
// Create a new button input
var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = "Remove";
// Append new text input to the newDiv
newDiv.appendChild(newText);
newDiv.appendChild(newText1);
// Append new button input to the newDiv
newDiv.appendChild(newDelButton);
// Append newDiv input to the mainContainer div
mainContainer.appendChild(newDiv);
counter++;
// Add a handler to button for deleting the newDiv from the mainContainer
newDelButton.onclick = function() {
mainContainer.removeChild(newDiv);
counter--;
}
}
else{
alert('Only 5 rows are allowed');
}}sss
function removeRow(divId){
mainContainer.removeChild(divId);
counter--;
}
</script>
</head>
<body >
<div id="mainContainer">
<div><input type="button" value="Add New Row" onClick="addNew()"></div>
<div id="div1"><input type="text" id="ans1"><input type="text" id="ans2"><input type="button" value="Remove" onClick ="javascript:removeRow(div1);"></div>
</div>
</body>
</html>
I want to achieve the same using jQuery.I also need the values entered in each of these textboxes.Please help.
Okay, because I had nothing better to do, and, to be honest, I was curious, I put this together. As implied in my comment, above, I didn't particularly like the way you had it laid out, so I used the following (x)html:
<form action="#" method="post">
<fieldset id="rows">
<ul>
<li>
<input type="text" id="ans1" name="ans1" />
<input type="text" id="ans2" name="ans2" />
</li>
</ul>
</fieldset>
<fieldset id="controls">
<button id="addRow">add</button>
<button id="removeRow" disabled>remove</button>
</fieldset>
</form>
With the following jQuery (although I've clearly not optimised, or refined it, but it should meet your requirements):
$(document).ready(
function(){
$('#addRow').click(
function() {
var curMaxInput = $('input:text').length;
$('#rows li:first')
.clone()
.insertAfter($('#rows li:last'))
.find('input:text:eq(0)')
.attr({'id': 'ans' + (curMaxInput + 1),
'name': 'ans' + (curMaxInput + 1)
})
.parent()
.find('input:text:eq(1)')
.attr({
'id': 'ans' + (curMaxInput + 2),
'name': 'ans' + (curMaxInput + 2)
});
$('#removeRow')
.removeAttr('disabled');
if ($('#rows li').length >= 5) {
$('#addRow')
.attr('disabled',true);
}
return false;
});
$('#removeRow').click(
function() {
if ($('#rows li').length > 1) {
$('#rows li:last')
.remove();
}
if ($('#rows li').length <= 1) {
$('#removeRow')
.attr('disabled', true);
}
else if ($('#rows li').length < 5) {
$('#addRow')
.removeAttr('disabled');
}
return false;
});
});
JS Fiddle demo of the above
I'm not, however, sure what you mean by:
I also need the values entered in each of these textboxes.
If you can explain what that means, or how you want them to be available (and, ideally, why they're not already available to you) I'll do my best to help.
I have a solution which will help you use here is the code
<script type="text/javascript" src="js/jquery.js"></script>
<script type = 'text/javascript'>
var newRowNum = 1;
var project_id ;
$(function() {
$('#addnew').click(function()
{
newRowNum++; // This is counter
//var i = 0;
///////// <a> <td> <tr>
var addRow = $(this).parent().parent();
///////// In the line below <tr> is created
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html();
$('td:last-child', newRow).html('<a href="" class="remove span">Remove<\/a>');
var newID = 'project'+newRowNum;
var add = 'description'+newRowNum;
newRow.children().children().first('input').attr('id', newID).attr('name', newID);
newRow.children().children().eq(1).attr('id', add).attr('name', add);
$('#table').find('tr:last').after(newRow);
$('a.remove', newRow).click(function()
{
newRowNum--;
$('#table').find('tr:last').remove();
return false;
});
return false;
});
});
</script>
<table width="75%" border="0" align = "center" id = 'table'>
<tr>
<td align = "center">Project </td>
<td align = "center">Description</td>
<td align = "center">Add Row</td>
</tr>
<tr>
<td align = "center"><input type = 'text' size = '35'name = 'project[]' id="project" ></td>
<td align = "center"><input type = 'text'size = '55' name = "description[]" id = 'description'></td>
<td width = '10%'><a id="addnew" href= "" class = 'span'>Add</a></td>
</tr>
</table>
You can also give each text box unique name if you change code like this and changing these two variables
var newID = 'project'+newRowNum;
var add = 'description'+newRowNum;
if you use the first method i shown here it will be easy to post data using array. That's all.
Related
I want multiple textarea(ck editor) where user can input multiple data in it , i tried various function and methods of jquery like clone() and appendTo but the problem is they are cloning the textarea but ckeditor is not working, after cloning the textarea i am unable to wrote anything in it
Please help me with it.
This is what i tried
test1
http://jsfiddle.net/FADxv/793/
test2
http://jsfiddle.net/kbqjnecx/3/
Thanks
Add an id to each new textarea and manually initialize the editor using
CKEditor.replace(id [,config])
Something like:
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
var editorId = 'editor_' + x;
$(wrapper).append('<div> <textarea id="'+editorId+'" class="ckeditor" name="ck[]"></textarea>Remove</div>'); //add input box
CKEDITOR.replace(editorId, { height: 200 });
}
});
DEMO
Check this for cloning ckeditor.
Check this fiddle : http://jsfiddle.net/manektech/47htysb5/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.ckeditor.com/4.5.4/standard/ckeditor.js"></script>
</head>
<body>
<div class="row hide_mail_id_domain">
<div class="col-sm-12">
<table class="table">
<thead>
<tr>
<th>Option</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<textarea class="ckeditor" required="" name="question_option_1" ></textarea>
</td>
<td></td>
</tr>
</tbody>
</table>
Add More
</div>
</div>
<script>
var REMOVE = '';
var i=1;
$(document).ready(function () {
$('.add_more').click(function () {
var oneplus=i+1;
var tr_object = $('tbody').find('tr:first').clone();
// getting and renaming existing textarea by name.
$(tr_object).find('textarea[name="question_option_1"]').attr("name", "question_option_"+oneplus+"");
$(tr_object).find('input').val('');
$(tr_object).find('td:last').html('Remove');
$('tbody').append(tr_object);
//replace code
CKEDITOR.replace("question_option_"+oneplus+"");
// when i were clicking on add more during my testing , then extra cke-editor id also appending to DOM. so for removing other then first
// included below code
$('#cke_question_option_1').each(function() {
var $ids = $('[id=' + this.id + ']');
if ($ids.length > 1) {
$ids.not(':first').remove();
}
});
i=i+1;
oneplus++;
});
$(document).on('click', '.remove_more', function () {
var id = $(this).closest('tr').find('.id').val();
if (id != '') {
if (REMOVE != '') {
REMOVE = REMOVE + ',' + id;
} else {
REMOVE = id;
}
$('#id').val(REMOVE);
}
$(this).closest('tr').remove();
});
});
</script>
</body>
</html>
I'm attempting to create a page where the user is able to customize the form to their needs by adding in extra divs or nested divs (as many layers deep as they'd like). Within each div I'd like to have text input and a button which adds another div on the same level and a button that nests a div within it. Both divs should again have a text input and a button which does the same thing.
However I've gotten a bit stuck. When I attempt to create a nested div I always end up adding it at the very bottom instead of inside its parent.
<html>
<script type="text/javascript">
var counter = 1;
function addNode() {
var newDiv = document.createElement('div');
counter++;
newDiv.innerHTML = "Entry " + counter + " <br><input type='text' name='myInputs'>";
document.getElementById("dynamicInput").appendChild(newDiv);
var newButton = document.createElement('button');
newButton.type = "button";
newButton.onclick = addSub;
document.getElementById("dynamicInput").appendChild(newButton);
}
function addSub() {
var newDiv = document.createElement('div');
counter++;
newDiv.innerHTML = "Entry " + counter + " <br><input type='text' name='myInputs' style='margin:10px'>";
document.getElementById("subInput").appendChild(newDiv);
}
</script>
<form class="form" method="POST">
<div id="dynamicInput" name="dynamicInput" multiple="multiple">
Entry 1<br><input type="text" name="myInputs">
<div id="subInput" name="subInput" multiple="multiple">
<input type="button" value="add nested" onClick="addSub();">
</div>
</div>
<input type="button" value="Add another text input" onClick="addNode();" >
<input type="submit" value = "answer" multiple="multiple"/>
</form>
</html>
Here is a complete solution for you keep in mind that if you need to bind extra events on your produced inputs and buttons you ll have to do it inside the functions addNode or addSub as i did for the click event on the buttons.
Working example : https://jsfiddle.net/r70wqav7/
var counter = 1;
function addNode(element) {
counter++;
var new_entry="Entry "+counter+"<br><input type='text' name='myInputs'><br>";
element.insertAdjacentHTML("beforebegin",new_entry);
}
function addSub(element) {
counter++;
var new_sub_entry="<div class='block'>"
+"Entry "+counter+"<br><input type='text' name='myInputs'><br>"
+"<div class='buttons'>"
+"<input class='add_sub_button' type='button' value='add nested'>"
+"<input class='add_button' type='button' value='Add another text input' >"
+"</div>"
+"</div><br />"
+"</div>";
element.insertAdjacentHTML("beforebegin",new_sub_entry);
var blocks=element.parentNode.getElementsByClassName("block");
blocks[blocks.length-1].getElementsByClassName("add_sub_button")[0].addEventListener("click",function(){
addSub(this.parentNode);
});
blocks[blocks.length-1].getElementsByClassName("add_button")[0].addEventListener("click",function(){
addNode(this.parentNode);
});
}
var buttons=document.getElementsByClassName("add_button");
for(i=0;i<buttons.length;i++){
buttons[i].addEventListener("click",function(){
addNode(this.parentNode);
});
}
var nested_buttons=document.getElementsByClassName("add_sub_button");
for(i=0;i<buttons.length;i++){
nested_buttons[i].addEventListener("click",function(){
addSub(this.parentNode);
});
}
div.block{
padding:5px;
border:2px solid #000;
}
<form class="form" method="POST">
<div class="block">
Entry 1<br><input type="text" name="myInputs"><br>
<div class="buttons">
<input class="add_sub_button" type="button" value="add nested">
<input class="add_button" type="button" value="Add another text input" >
</div>
</div><br />
<input type="submit" value = "answer" multiple="multiple"/>
</form>
EDITED : There was an error binding the click event on nested items updated to work properly
Here's another worked example which makes use of the concepts I mentioned in an earlier comment. I've moved the Add-Item button outside the form and altered the method used to determine the text for each new item added. Rather than keep a counter, I count the number of existing items in the document and increment it, using this as as the n in the string "Entry n"
I should have added(appended) the sub-item before the button that creates new ones, but was lazy and just called appendChild on the button after the other new element was added - the end result is the same, but it's less efficient and will cause slower performance/shorter battery life.
I was going to use the .cloneNode method of the .dynamicInput div, when clicking "Add new item", however this will copy all subitems of the chosen target and we still need to call addEventListener for the button anyway, so I've opted to simply create each input-item added with the "Add new item" button instead.
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('addNewInputBtn').addEventListener('click', myAddNewItem, false);
var subItemBtn = document.querySelectorAll('.dynamicInput button')[0];
subItemBtn.addEventListener('click', myAddSubItem, false);
}
function makeNewItem(titleStr)
{
var div = newEl('div');
div.className = 'dynamicInput';
var heading = newEl('h3');
heading.innerText = titleStr;
div.appendChild(heading);
var input = newEl('input');
div.appendChild(input);
var btn = newEl('button');
btn.innerText = 'Add sub-items';
btn.addEventListener('click', myAddSubItem, false);
div.appendChild(btn);
return div;
}
function myAddNewItem(evt)
{
var numAlreadyExisting = allByClass('dynamicInput').length; // count number of divs with className = dynamicInput
var newNum = numAlreadyExisting + 1;
var newInputPanel = makeNewItem('Entry ' + newNum);
byId('myForm').appendChild(newInputPanel);
return false;
}
function myAddSubItem(evt)
{
evt.preventDefault(); // stops this button causing the form to be submitted
var clickedBtn = this;
var inputDiv = clickedBtn.parentNode;
var newInput = newEl('input');
inputDiv.appendChild(newInput);
inputDiv.appendChild(clickedBtn);
}
</script>
</head>
<body>
<form id='myForm'>
<div class='dynamicInput'>
<h3>Entry 1</h3>
<input type='text'/><button>Add sub-item</button>
</div>
</form>
<button id='addNewInputBtn'>Add new item</button>
</body>
</html>
I have made a custom chrome extension - a bookmark manager. It's working fine, but I am having problems with deleting the links: If 3 links are given, and delete button is clicked on the 2nd one, both 2 and 3 will be removed.
html + js here: http://jsfiddle.net/6Txr9/
Since this is an extension, inline javascript is not available, and it has to be done with an event listener.
the counter and linkContainer are saved locally. This allows for data to persist between ext launches and ensures that all #id are going to be unique. The idea is that indexDeleters() will add a unique eventlistener to each button each time it's called, which will cause it to delete only that row.
Any input is appreciated!
Code as requested (same as in link above):
js
function addCats()
{
var linkCounter = localStorage['counter']
var catsList = document.getElementById('catsList');
var linkName = document.getElementById('linkName');
var a = document.createElement('a');
var linkContainer = document.getElementById('linkContainer');
a.appendChild(document.createTextNode(document.getElementById('linkName').value));
a.setAttribute('href', 'http://google.com/');
a.setAttribute('target', '_blank');
var deleteLink = document.createElement('img');
deleteLink.setAttribute('src', 'red_x.png');
deleteLink.setAttribute('align', 'right');
deleteLink.setAttribute('id', linkCounter);
var tr = document.createElement('tr');
var linkCell = document.createElement('td');
var xCell = document.createElement('td');
linkCell.appendChild(a);
xCell.appendChild(deleteLink);
xCell.setAttribute('align', 'right');
tr.appendChild(linkCell);
tr.appendChild(xCell);
linkContainer.appendChild(tr);
catsList.value = '';
linkName.value = '';
localStorage['container'] = JSON.stringify(linkContainer.innerHTML);
indexDeleters();
linkCounter ++;
localStorage['counter'] = linkCounter;
}
document.getElementById('addToList').onclick = addCats;
function indexDeleters()
{
var Xs = document.getElementsByTagName('img');
var arr = []
for (var i=0; i<Xs.length; i++)
{
arr.push(Xs[i]);
}
for (var i=0; i<arr.length; i++)
{
var Id = arr[i].getAttribute('id');
arr[i].addEventListener('click', function(){removeRow(Id);}, false);
}
}
function removeRow(Id)
{
console.log('Call to remove id at ' + Id)
var Table = document.getElementById('linkContainer');
var Tr = document.getElementById(Id).parentNode.parentNode
Tr.parentNode.removeChild(Tr);
localStorage['container'] = JSON.stringify(document.getElementById('linkContainer').innerHTML);
}
window.onload = function()
{
if (localStorage.getItem('counter') == null)
{
localStorage['counter'] = 0
}
document.getElementById('linkContainer').innerHTML = JSON.parse(localStorage['container']);
indexDeleters();
}
html
<body>
<h2 align="center">Bookmark Manager</h2>
<table>
<tr>
<td colspan="5">
<table id="linkContainer" width="100%"></table>
</td>
</tr>
<tr>
<td nowrap>Display Name:</td>
<td>
<input type="text" id="linkName"/>
</td>
<td nowrap>Cat IDs:</td>
<td>
<input type="text" id="catsList"/>
</td>
<td>
<button type="button" id="addToList">Add</button>
</td>
</tr>
</table>
<script src="popup.js"></script>
</body>
See JavaScript closure inside loops – simple practical example for an explanation of the problem.
In your case, you can directly access the DOM element in the event handler, so that it doesn't depend on any loop variable.
arr[i].addEventListener('click', function(){removeRow(this.id);}, false);
Hey guys I'm still fairly new to js and JQuery so I really need some help. I've tried several ways to do this. I basically need the value of my text box increased by 1 when a user clicks the plus button, and decreased by 1 when they click the minus button. I haven't coded for the minus as I haven't figured out the plus. My $('#itemQuant1').val(+1); call works, but stops at 1. Here is my js:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var current_count = $('#itemQuant1').val();
var plus_count = current_count + 1;
var minus_count = current_count - 1;
//var minusCount = document.getElementById('minusItem').value;
$("#plusItem1").on('click', function(){
current_button = $(this);
if (current_button.attr('id') == "plusItem1")
{
$('#itemQuant1').val(+1);
//current_count.val() + plus_count;
//plus_count.val() + 1;
//$('#itemQuant1').value = current_count.value + 1;
}
});
});
</script>
Here is the html:
<body>
<div>
<table style= "border:solid;border-width:thin;">
<tr>
<td style= "border:solid;border-width:thin;"><p><input class"comfirmItem" type="checkbox">1-FLUE CONNECTOR ASSEMBLY PACKAGE (0005812) +$665.10<button id="plusItem1" class="more_Item" style="float:right;">+</button><button id="minusItem" class="less_Item" style="float:right;">-</button><input id="itemQuant1" class"itemCount" type="textbox" value=0 style="width:30px;text-align:center;margin-left:5px;margin-right:5px;float:right;"></p></td>
</tr>
<tr>
<td style= "border:solid;border-width:thin;"><p><input class"comfirmItem" type="checkbox">2-DUCT BOX ASSEMBLY (0005875) +$305.01<button id="plusItem" class="more_Item" style="float:right;">+</button><button id="minusItem" class="less_Item" style="float:right;">-</button><input id="itemQuant2" class"itemCount" type="textbox" style="width:30px;text-align:center;margin-left:5px;margin-right:5px;float:right;"></p></td>
</tr>
</table>
</div>
</body>
</html>
You just need to do this - http://jsfiddle.net/jayblanchard/rCM5d/
$('#itemQuant1').val( parseInt($('#itemQuant1').val()) + 1);
For up and down buttons it might be an idea to wrap all the button logic together like so: http://jsbin.com/kikitule/1/edit
Your HTML would look like this:
<button class="items-button" data-sum="1" data-target="#itemQuant1">+</button>
<button class="items-button" data-sum="-1" data-target="#itemQuant1">-</button>
<input id="itemQuant1" class="itemCount" type="textbox" value=0>
And JQuery like this:
$(document).ready(function(){
$(".items-button").on('click', function(){
var $button = $(this);
var $quantity = $($button.attr('data-target'));
var sum = parseInt($button.attr('data-sum'), 10);
var total = parseInt($quantity.val(), 10) + sum;
if (total < 0) {
total = 0;
}
$quantity.val(total)
});
});
I have some tables here, and using this javascript below, I made them hide and show every time a user click on their buttons. What I want to add in to this script, is when someone click on a table's button to show-up, all the other to be hidden. Any idea how can I do this? Thank you in advance!
This is my html code:
<table id="SC1_TH_" class="header_op"><tr><td>
<div id="SC1_BSH_" onClick="SC[1]();" class="hide_button">*</div>OPTION ONE
</td></tr></table>
<div id="SC1_BO_" style="display:dlock;">BLAH BLAH</div>
<table id="SC2_TH_" class="header_cl"><tr><td>
<div id="SC2_BSH_" onClick="SC[2]();" class="show_button">*</div>OPTION ONE
</td></tr></table>
<div id="SC2_BO_" style="display:none;">BLAH BLAH</div>
<table id="SC3_TH_" class="header_cl"><tr><td>
<div id="SC3_BSH_" onClick="SC[3]();" class="show_button">*</div>OPTION ONE
</td></tr></table>
<div id="SC3_BO_" style="display:none;">BLAH BLAH</div>
This is my javascript:
<script type="text/javascript">
var SC = [];
for (var i = 1; i < 10; i++) {
SC[i] = (function(i){
return function(){
var SC_TH = document.getElementById('SC'+i+'_TH_');
var SC_BSH = document.getElementById('SC'+i+'_BSH_');
var SC_BO = document.getElementById('SC'+i+'_BO_');
if (SC_BO.style.display == 'block' || SC_BO.style.display == ''){
SC_TH.className = 'header_cl';
SC_BSH.className = 'show_button';
SC_BO.style.display = 'none';}
else {SC_TH.className = 'header_op';
SC_BSH.className = 'hide_button';
SC_BO.style.display = 'block';}
}})(i);}
</script>
EDIT: In other words, I need something to say, if this button that clicking right now is something all the other to be hidden!!!
Here's a working example with some very simple jQuery (recommended) code.
HTML:
<table><tr><td>
<div class="toggle-button">*</div>OPTION ONE
</td></tr></table>
<div class="toggle">BLAH BLAH</div>
<table><tr><td>
<div class="toggle-button">*</div>OPTION ONE
</td></tr></table>
<div class="toggle">BLAH BLAH</div>
<table><tr><td>
<div class="toggle-button">*</div>OPTION ONE
</td></tr></table>
<div class="toggle">BLAH BLAH</div>
JS:
$(function() {
$('div.toggle').hide();
$('.toggle-button').click(function(){
$('div.toggle').hide();
$(this).closest('table').next('div.toggle').show();
});
});
As #StephenByrne mentioned, I also strongly recommend using an existing component such as jQuery Accordian. It takes minutes to implement and comes with a whole host of themes to chose from and is fully customisable. You could spend hours or days writing your own. Unless it's a learning exercise, it's simply a waste of time. No need to reinvent the wheel.
As you have indicated a strong push towards js-only, here's a working js-only solution.
HTML:
<table id="SC1_TH_" class="header_op"><tr><td>
<div id="SC1_BSH_" onclick="toggle(this);" class="hide_button">*</div>OPTION ONE
</td></tr></table>
<div id="SC1_BO_" style="display:block;">BLAH BLAH</div>
<table id="SC2_TH_" class="header_cl"><tr><td>
<div id="SC2_BSH_" onclick="toggle(this);" class="show_button">*</div>OPTION ONE
</td></tr></table>
<div id="SC2_BO_" style="display:none;">BLAH BLAH</div>
<table id="SC3_TH_" class="header_cl"><tr><td>
<div id="SC3_BSH_" onclick="toggle(this);" class="show_button">*</div>OPTION ONE
</td></tr></table>
<div id="SC3_BO_" style="display:none;">BLAH BLAH</div>
JS:
function toggle(src) {
var id = src.id;
var index = id.substring(2, 3);
var i = 1;
var toggleItem = document.getElementById('SC' + i.toString() + '_BO_');
while (toggleItem != null) {
var bShow = index == i;
var button = document.getElementById('SC' + i.toString() + '_BSH_');
var table = document.getElementById('SC' + i.toString() + '_TH_');
if (bShow) {
toggleItem.style.display = 'block';
toggleItem.className = 'setitemclassname';
button.className = 'setbuttonclassname';
table.className = 'settableclassname';
}
else {
toggleItem.style.display = 'none';
toggleItem.className = 'setitemclassname';
button.className = 'setbuttonclassname';
table.className = 'settableclassname';
}
toggleItem = document.getElementById('SC' + (++i).toString() + '_BO_');
}
}
Inside the while loop when index == i evaluates to true, you know you have the item to show. Add extra logic there to change your class names.
A cleaner solution involves altering your HTML a bit as well - getting rid of the onclick and replacing it with a class (toggleItem) that will allow the javascript to identify the items to be toggled. I also make sure that all the buttons have the class button so they can be identified.
<table id="SC1_TH_" class="header">
<tr>
<td>
<div id="SC1_BSH_" class="button">*</div>OPTION ONE</td>
</tr>
</table>
<div id="SC1_BO_" class="toggleItem">BLAH BLAH</div>
<table id="SC2_TH_" class="header">
<tr>
<td>
<div id="SC2_BSH_" class="button">*</div>OPTION ONE</td>
</tr>
</table>
<div id="SC2_BO_" class="toggleItem">BLAH BLAH</div>
<table id="SC3_TH_" class="header">
<tr>
<td>
<div id="SC3_BSH_" class="button">*</div>OPTION ONE</td>
</tr>
</table>
<div id="SC3_BO_" class="toggleItem">BLAH BLAH</div>
Then in the javascript:
var buttons = document.getElementsByClassName('button'),
toggleItems = document.getElementsByClassName('toggleItem'),
tables = document.getElementsByClassName('header');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = getFunction(toggle, i);
}
// getFunction is needed for reasons to do with variable scope
function getFunction(f, p) {return function() {f(p)}}
function toggle(selected) {
for (var i = 0; i < toggleItems.length; i++) {
toggleItems[i].style.display = i == selected ? '' : 'none';
tables[i].className = i == selected ? 'header open' : 'header closed';
buttons[i].className = i == selected ? 'button show' : 'button hide';
}
}
toggle(0); // initially show only the first one
(This does assume that the buttons and toggle items will be in the same order. If that is not the case you will have to revert to checking their IDs or find some other way to associate the items and buttons.)
(EDITED to include changing class of tables and buttons)
Just hide all of them, then show the one that should become toggled open. This script is not the elegantest solution, but integrates directly in your coding style:
for (var i = 1; i < 10; i++) {
SC[i] = (function(i){
var SC_TH = document.getElementById('SC'+i+'_TH_'),
SC_BSH = document.getElementById('SC'+i+'_BSH_'),
SC_BO = document.getElementById('SC'+i+'_BO_');
return function(action) {
if (!action) action = SC_BO.style.display=="none" ? "show" : "hide";
if (action == "show") {
for (var i=0; i<SC.length; i++)
SC[i]("hide");
SC_TH.className = 'header_op';
SC_BSH.className = 'hide_button';
SC_BO.style.display = '';
} else {
SC_TH.className = 'header_cl';
SC_BSH.className = 'show_button';
SC_BO.style.display = 'none';
}
};
})(i);
}