3

I have a javascript function that adds table rows when a button is clicked.

when adding rows, in one of the cells it uses:

var linkCell = row.insertCell(1);
var elLink = document.createElement('a');
var href='http://www.domain.co.uk/';
elLink.href = href;
elLink.innerHTML = 'Choose Product '+i;
linkCell.appendChild(elLink);

to add a HTML a href to each row but I want to be able to used onClick rather than a href

I have tried:

var linkCell = row.insertCell(1);
var elLink = document.createElement('a');
var href='javascript:void(0);';
var onClick=window.open('/admin/chooseproduct.php?c='+i,'Popup','width=550,height=500,left=150,top=200,toolbar=1,status=1,');
elLink.href = href;
elLink.innerHTML = 'Choose Product '+i;
linkCell.appendChild(elLink);

but that does not open the popup window as it should - how can I do this?

1
  • 1
    You don't appear to actually assign the onClick variable to anything. Try elLink.onclick = onClick; Commented Nov 5, 2013 at 10:49

3 Answers 3

8

Two problems:

First, you are not every applying the onclick method to the element: you are only defining it as a variable.

var onClick = ...     // won't work
elLink.onclick = ...  // will work

Second, you are not creating an onclick handler with the code you're writing. onClick = window.open(...) doesn't say "open a window when the element is clicked". Rather it says "open a window right now, and set onClick to be a reference to that window".

You need to create a new function. This function will be assigned as the event handler and only executed when the link is clicked. It will itself call window.open.

elLink.onclick = function() {
    window.open('/admin/chooseproduct.php?c='+i,'Popup','width=550,height=500,left=150,top=200,toolbar=1,status=1,');
};
Sign up to request clarification or add additional context in comments.

Comments

0

Here is your solution:

var linkCell = row.insertCell(1);
        var elLink = document.createElement('a');
        var href='javascript:void(0);';
        elLink.href = href;
        elLink.innerHTML = 'Choose Product '+i;
        linkCell.appendChild(elLink);
        elLink.onclick= function() {
        window.open('/admin/chooseproduct.php?
       c='+i,'Popup','width=550,height=500,left=150,top=200,toolbar=1,status=1,'); //Attach event here
       };

Comments

0

Been using jQuery for too long. But still I suppose you need to assign the onClick function you defined to the elLink element for it to trigger. At present, that does not seem to be happening.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.