Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a button, with onclick function, via javascript/jquery

I'm struggling to find the correct syntax for adding a button via javascript/jquery that has a function attached.

Right now I am trying:

list.append("<button onclick='getFeed('http://open.live.bbc.co.uk/weather/feeds/en/PA2/3dayforecast.rss, showFeedResults')'>ButtonTest</button>");

But it returns:

<button onclick="getFeed(" http:="" open.live.bbc.co.uk="" weather="" feeds="" en="" pa2="" 3dayforecast.rss,="" showfeedresults')'="">ButtonTest</button>

Essentially, I want to be able to create

<button onclick="getFeed('http://open.live.bbc.co.uk/weather/feeds/en/B1/3dayforecast.rss', showFeedResults)" class="ui-btn-hidden">

In javascript, But can't figure out how..`

And I seem to be having trouble wrapping my head around creating html elements that use both single and double qoutation marks.

Any advice would be greatly appreciated.

like image 640
Shuma Avatar asked Dec 04 '22 11:12

Shuma


2 Answers

Append a button with click event listener assigned

Using pure JavaScript

const NewEL = (tag, prop) => Object.assign(document.createElement(tag), prop);

// Use like:
const EL_btn = NewEL("button", {
  textContent: "Test button",
  onclick() { console.log(this); /* getFeed etc... */ },
});

document.body.append(EL_btn);

Or using the jQuery library

http://api.jquery.com/on/

list.append("<button>ButtonTest</button>");

list.on("click", "button", function(){
    getFeed('http://open.live.bbc.co.uk/weather/feeds/en/PA2/3dayforecast.rss, showFeedResults');
});

For dynamically generated elements use .on() method like above.

like image 62
Roko C. Buljan Avatar answered Dec 06 '22 23:12

Roko C. Buljan


While I think using an on handler on the entire list is better, it's also perfectly acceptable to just bind events to disconnected DOM elements before adding them to the DOM:

button = $("<button>Button Test</button>");

button.click(function () {
  getFeed('http://open.live.bbc.co.uk/weather/feeds/en/PA2/3dayforecast.rss, showFeedResults');
});

list.append(button);
like image 22
meagar Avatar answered Dec 07 '22 01:12

meagar