Azuu
Azuu

Reputation: 856

Dynamic parameters in JQuery

I have function in which append method is taking a static parameter.

 function toggle() {
         $("#MS").append($('#hide'));        
    }

What i want is to pass the parameter dynamically from my Hyperlinks click event. In above code that #MS is static which i want to pass dynamically

Code: HTML

<div id="MS">
        <a href="javascript:void(0);" onclick="toggle();">JP MORGAN</a><br>
    </div>

I want to pass the argument from onclick to toggle method and that parameter will be used in the append method.

I have tried several combinations buut it didnt worked. Please help..

My new code after changes

<script>
$(function() { // when the DOM is ready
    var $hide = $('#hide').click(function(){
       $(this).closest('div').hide();
    }); 

    $('a.toggle').click(function(e){
       e.preventDefault();
       $(this).parent().append($hide);
    });
}); 


</script>

<div id="JP">
        <a href="#">JP MORGAN</a><br>       
    </div>

still not working

Upvotes: 0

Views: 163

Answers (2)

What have you tried
What have you tried

Reputation: 11138

Retrieve the ID dynamically on the anchor's click event and pass that ID to the function:

$("a").on("click", function(e){
    e.preventDefault();

    $(this).append($('#hide')); 

};

Upvotes: 0

Ram
Ram

Reputation: 144669

Since you are using jQuery, you can add classes to your a elements and use parent method:

$(function() { // when the DOM is ready
    var $hide = $('#hide').click(function(){
       $(this).closest('div').hide();
    }); 

    $('a.toggle').click(function(e){
       e.preventDefault();
       $(this).parent().append($hide);
    });
}); 

Upvotes: 1

Related Questions