Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery programmatically click on new dom element

I am trying to do something tricky (at least to me) in jquery. I have a checkbox that is bound to a function called add_course which looks like this:

    function add_course(){
        var id = $(this).attr('id');
        if ($(this).is(':checked')){

            if($('#courseInput').val().search(id) < 0){
                $('#CourseSummary').append('<span id="cn'+id+'"><a href="#" class="courseDel" id="'+id+'">X</a> '+$('#course'+id+' a').html()+'<br/></span>');
                $('#courseInput').val(function(index,value){
                    return value+ id +',1;';
                });
                addTotal($('#price'+id).text());
            }
            imageSync();
        }else{
            //This is where my question refers to. 
            $('a#'+id+'.courseDel').click();
        }
    }

When someone checks the checkbox, a span with some data and a link are added to the page. The new link is connected to a different function with

$('.courseDel').live('click', del_course); 

del_course does a whole bunch of stuff, just like add_course.

As you can see in the add_course function. I check whether the checkbox has been checked and only do stuff if it has been.

here is del_course:

     function del_course(){
        var id = $(this).attr('id');
        $('#cn'+id).remove();
        $('#courseInput').val(function(index,value){
            return value.replace(id+',1;',"");
        });
        subtractTotal($('#price'+id).text());
        imageSync();
    }

I would like to have the else part of my add_course function trigger the del_course for the corresponding link that got added when the checkbox was checked. This isn't working. I've probably over complicated something.

here is the html for the checkbox (an example of one of them):

<input type="checkbox" class="courseAdd" name="courseAdd" id="204"/>

here is the html for the link that gets added when someone clicks a checkbox:

<span id="cn204"><a href="#" class="courseDel" id="204">X</a> Course Title<br/></span>

It works great when someone clicks the link, but how do i trigger it programatically?

like image 730
lovefaithswing Avatar asked Oct 21 '11 17:10

lovefaithswing


2 Answers

Since you have the ID of the element that you created, simply refernce the ID and use the trigger() method:

$('#'+id).trigger('click');

Also, an ID that is just a number is incorrect:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

like image 58
James Hill Avatar answered Oct 19 '22 23:10

James Hill


Use jquery's trigger() function.

$('.courseDel').trigger('click');
like image 34
jbabey Avatar answered Oct 19 '22 22:10

jbabey