setAttribute function in IE

Discussion in 'JavaScript' started by Danielz, Dec 12, 2008.

  1. #1
    Hi,

    I am facing problems with setAttribute function in IE. I understand from what I read on the net that IE doesn't support it and will never support it. I would like to understand if there is a solution for what I want to do that works both in IE (at least version 7 onwards) and Firefox.

    My requirement is:

    I am dynamically generating fields by using Javascript. I need to assign properties like classes, names, IDs, events dynamically to these. I am currently using setAttribute to do this.

    Below is a sample code where I am using an alternate solution by hiding and showing hyperlinks. While I can afford to do it for this example, I cannot in many places in the rest of my code.

    So, if I can get help on satisfying my requirement in the below code without the alternate solution I am currently using, it will help me fix the rest of my code.

    this HTML
    <a href="javascript:void(0)" id="edit" onclick="companyEdit();" >Edit</a>

    is calling the function defined here:

    <script language="javascript">
    function companyEdit()
    {
    alert('edit company');
    document.getElementById('edit').innerHTML="Save";
    document.getElementById('edit').setAttribute("onclick", "saveCompany('save company');");
    }
    function saveCompany(msg)
    {
    alert(msg);
    }
    </script>

    I want to change companyEdit() to saveCompany() dynamically using setAttribute.
    Above example is not working IE only.

    For this I have one alternative solution

    I have another hyperlink like
    <a href="javascript:void(0)" style="display:none" id="save" onclick="saveCompany('save company');" >save</a>

    when somebody cick on edit link I am changing display:none to display:block.

    Please help me. Thanks in advance.:)
     
    Danielz, Dec 12, 2008 IP
  2. lp1051

    lp1051 Well-Known Member

    Messages:
    163
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Hi,
    if I understand, you want to attach onclick event to element and call function with parameter 'save company'??
    If so, you can either use window.atachEvent (IE)/addEventListener (DOM) or simply :
    document.getElementById('edit').onclick = function() { saveCompany('save company') };
     
    lp1051, Dec 12, 2008 IP
  3. Danielz

    Danielz Peon

    Messages:
    115
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you lp1051 :)
     
    Danielz, Dec 14, 2008 IP