Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery event fires twice

Tags:

jquery

I have a select element from which the users can select a value and copy it to a textarea element. Everything works as expected with the exception that the value from the select element is copied twice.

$('#cp_objs_for_goal_button').mouseup(function(){
    if ($("#cp_objs_for_goal_select").attr("selectedIndex") != 0)
    {
        console.log('selected index: '+$("#cp_objs_for_goal_select").attr("selectedIndex"));
        curr_txt = $('#pop_goal_text').val();
        console.log('curr_txt: '+curr_txt);
        added_txt = $('#cp_objs_for_goal_select option:selected').text();
        console.log('added_txt: '+added_txt);
        if (curr_txt)
        {
            new_pop_text = curr_txt + ' ' + added_txt;
        }
        else
        {
            new_pop_text = added_txt;
        }
        console.log('new_pop_text: '+new_pop_text);
        $('#pop_goal_text').val(new_pop_text);

        // TODO - This throws error:
        // $('#cp_objs_for_goal_select option').get(0).attr('selected', 'selected');
    }
})

When I click the cp_objs_for_goal_button button, I get this.... from the console log:

selected index: 1
curr_txt:
added_txt: Restore geomorphic integrity
new_pop_text: Restore geomorphic integrity

selected index: 1
curr_txt: Restore geomorphic integrity
added_txt: Restore geomorphic integrity
new_pop_text: Restore geomorphic integrity Restore geomorphic integrity

Here the html:

<select id="cp_objs_for_goal_select" style="width:100%"> 
    <option>Select the Objective you would like to copy to this project:</option> 
    <option>Restore geomorphic integrity</option> 
</select> 
<div id="cp_objs_for_goal_button" class="awesome" style="border:0;">Copy</div>

1 Answers

This is a common Bug in Jquery. you can find many articles around internet specially on SO for event being fired twice. You can try this

 $(document).on('click', '#task-list li', function(e)
 {
       alert('Hellow world');
       e.stopPropagation();
       return false;
 });

And it's definitely Javascript problem because if you hit google and search for event fire twice you will see that Angular, Jquery and backbone etc all are somewhere firing events twice or even thrice. So, it's seem that it's javascript behind this.

like image 195
Airy Avatar answered Sep 05 '25 15:09

Airy