TheMook
TheMook

Reputation: 1541

Manually trigger click event on other DOM element in knockout viewmodel page

In my html:

<input type="image" src="http://placehold.it/145x145" data-bind="click: imgClick"/>
<input type="file" id="artImage" style="display: none;" />

In my viewmodel:

var imgClick = function () {
    $("artImage").click();
};

If I put a debug breakpoint on the '$("artImage").click()' line, it is hit. I get no error in the console, nothing happens on screen though.

Seems to work ok in a fiddle? http://jsfiddle.net/nVrSP/ so I'm not sure why it's not working on my page.

(in case anyone asks, I'm trying to do a clickable image to trigger a file upload browse)

Upvotes: 3

Views: 3584

Answers (2)

Adrian Salazar
Adrian Salazar

Reputation: 5319

Dude, it is a security measure from the vast majority of browsers to do nothing on "click" event if the html file input control is hidden.

A workaround for this is to hide the file input control using opacity, do not hide it using visibility or display=none.

See this thread for more info:

In JavaScript can I make a "click" event fire programmatically for a file input element?

Upvotes: 0

JF it
JF it

Reputation: 2403

your selector is probally returning nothing as you have not given it a # to say "this is ID."

try

$("#artImage").trigger('click');

see this link for list of valid selectors: https://cdn.tutsplus.com/net/uploads/legacy/154_cheatsheet/jquery12_colorcharge.png

Upvotes: 2

Related Questions