Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a JavaScript page that creates toggle buttons when the page loads, but i cannot use those buttons independently now because the id of the button is a column name on my database table. so i cannot know it beforehand, that is why i cannot assign a method or function on each button.

This is how the toggle button is created :

JavaScript
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
  return '\n<input' + (tbID ? ' id=\'' + tbID + '\'' : '') + 
    (tbClass ? ' class=\'' + tbClass + '\'' : '') + 
    (tbType ? ' type=\'' + tbType + '\'' : '') + 
    (tbValue ? ' value=\'' + tbValue + '\'' : '') + 
    (onClick ? ' onclick=\'' + onClick + '\'' : '') + '>';

}

function DisplayButtons(cableData) {
  var newContent = '';
  $.each(cableData, function (i, item) {
    function toggle() {
      $("#tb" + item.CommonCable)
        .clicked ? $('#MyElement')
        .addClass('clickedButton');
      $("#tb" + item.CommonCable)
        .removeClass("clickedButton");
      $('#MyElement')
        .toggleClass('MyClass');
    }
    newContent += createButtons("tb" + item.CommonCable, 
          null, "submit", item.CommonCable, toggle());
  });
  $("#Categories")
    .html(newContent);
}

NOTE : Anyone who can help asap ,how can i assign each function or method to each button ? : Or any other way i can use to create my toggle buttons ?

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 6-Feb-13 4:17am
v3

1 solution

I would try using JQuery to bind the button to an event after creating it.

JavaScript
 function toggle() {
      $("#tb" + item.CommonCable)
        .clicked ? $('#MyElement')
        .addClass('clickedButton');
      $("#tb" + item.CommonCable)
        .removeClass("clickedButton");
      $('#MyElement')
        .toggleClass('MyClass');
    }

function DisplayButtons(cableData) {
  var newContent = '';
  $.each(cableData, function (i, item) {
       newContent += createButtons("tb" + item.CommonCable, 
                   null, "submit", item.CommonCable, toggle());
       $("#Categories").append(newContent);
       $("#tb" + item.CommonCable).click(function() { toggle() });
  });

}


You might have to clear out $("#Categories") first if you do this more than once, and be careful you append the buttons in the right order, but this should work. Assuming I understood what you were after.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900