Developer
Developer

Reputation: 6350

Change the onclick of a hyper link

I want to update the click event of the hyperlink onClick and want to update the html inside the hyperlink in jquery

HTML

<a class=" save" href="javascript:void(0);" onclick="save_unsave('unsave','UID','ID',this);">
    <div class="jopt_iconwrap" title="Unsave" alt="Unsave" >
        <span class="saved"></span>
    </div>
    Unsave
</a> 

Now onlick of save_unsave function i want to update the html design as below:

 <a class=" save" href="javascript:void(0);" onclick="save_unsave('save','UID','ID',this);">
        <div class="jopt_iconwrap" title="Save" alt="Save" >
            <span class=""></span>
        </div>
        Save
    </a> 

I am trying to do this in the function:

jQuery

if(type == 'save')
    {
            var new_type = "'unsave'";
            jQuery(elem_obj).html("");
            jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class="saved" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="saved"></span></div>Unsave</a>');
    }
    else if(type == 'unsave')
    {

        var new_type = "'save'";
        jQuery(elem_obj).html("");
        jQuery(elem_obj).html('<a onclick="save_unsave('+new_type+','+uid+','+id+',this);" class=" save" href="javascript:void(0);"><div class="jopt_iconwrap" title="Unsave" alt="Unsave"><span class="mico"></span></div>Save</a>');

    }

How can we do this in jquery.Please help me in the i have the elmenet object in the function.

Upvotes: 3

Views: 103

Answers (3)

Pooja Dubey
Pooja Dubey

Reputation: 683

simply i will suggest you to use replaceWith() in place of .html() it will work properly for you.

Upvotes: 2

guradio
guradio

Reputation: 15555

$('a').click(function() {

  if ($(this).hasClass('save')) {
    $(this).removeClass('save').addClass('unsave');
    $(this).text('Unsave')
    $(this).attr('id','save')

  } else {
    $(this).removeClass('unsave').addClass('save');
    $(this).text('Save')
    $(this).attr('id','unsave')

  }



})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class=" save">
  <div class="jopt_iconwrap" title="Save" alt="Save">
    <span class=""></span>
  </div>
  Save
</a>

Try this way

Upvotes: 1

Buzinas
Buzinas

Reputation: 11725

You can replace the onclick event, like this:

$('.save')[0].onclick = function() {
  save_unsave('save', 'UID', 'ID', this);
}

Upvotes: 0

Related Questions