user7461846
user7461846

Reputation:

function with name as a data value of a div

I want to execute a function which name is a data attribute value of a div:

$('#dgok').click(function() {
    var fn = $(this).attr('data-fn');
    window[fn]();
});

function delimg(){
    console.log('james'); // this works     
    let src = $('.imgact');
    let afn = 'store';
    $.post('images-pro.php', {afn, src}, function(data){  // line 75
        console.dir(data);
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dgok' data-fn='delimg'>OK</div>

TypeError: Illegal invocation...at delimg (images.js:75)

Any help?

Upvotes: 0

Views: 57

Answers (1)

OliverRadini
OliverRadini

Reputation: 6467

Without knowing exactly what $('.imgact') is, it's hard to know what it should be. I'm going to guess it's an input, though, so correct me if I'm wrong.

The issue is that you're trying to send data that jquery really doesn't want to let you send. $('.imgact') is an element, and if it's an input, we probably want its value rather than the element itself.

That would look like this:

$('#dgok').click(function() {
    var fn = $(this).attr('data-fn');
    window[fn]();
});

function delimg(){
    console.log('james'); // this works     
    let src = $('.imgact').val();
    let afn = 'store';
    $.post('images-pro.php', {afn, src}, function(data){  // line 75
        console.dir(data);
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class".imgact" />
<div id='dgok' data-fn='delimg'>OK</div>

Upvotes: 2

Related Questions