0

I manage do change the text in my button using Javascript.

Using this code

$("#unfriend").click(function(){
    $.post("/unfriend/<?= $friend_but->id ?>",
    function(data,status){
        //alert(data);
        if (data == 'ok') {
            alert(data);
            $('#unfriend').html('Add Friend');
        };
    });
});

But I have a problem, how can change the id #unfriend into #addfriend?

I added $('#unfriend').setAttribute('id','addfriend'); but it's not working. And When I also added that code, the text in my button is not changing.

3
  • hope you can use $("#unfriend" ).replaceWith( $( "#friend" ).html("your text") ); Commented Oct 24, 2014 at 12:55
  • it's not working. My button is vanishing when I click it. Commented Oct 24, 2014 at 13:05
  • I am doing this because I want to dynamically change the button text and Id. Say, if a user want to unfriend another user I want to make the button change its text into "Add friend" dynamically without reloading the page. Also with the id of the button since my js depends on which controller of my CodeIgniter needs to be use. Commented Oct 24, 2014 at 13:15

5 Answers 5

2

Use jQuerys .attr() instead.

$('#unfriend').attr('id','addfriend');

Demo which works:

http://jsfiddle.net/r8vr6u49/

Sign up to request clarification or add additional context in comments.

Comments

1
.attr('id','addfriend')

you cant use javascript setAttribute on jQuery object

Comments

0
$('#unfriend').attr('id','addfriend');

4 Comments

Adding a little supportive text will help understand your solution.
I didnt bother adding a comment because 4 other people had posted the same answer. I usually add an answer and then edit with a more descriptive response but in this case with some many other responses it was useless
Maybe that's why Doodlebunch gets the upvotes instead of your answer (although you postet first)...
Does it matter? The user got their desired answer and result. I am not concerned with me upvotes or rank. I simply like to help where I can. Don't take things so seriously pal. Thanks.
0

HTML

<div id="friend">Hello</div>

Script

$('#friend').on('click', function() {
   $(this).attr('id', 'unfriend').html("text to be updated"); 
});

Comments

0
$('#unfriend').attr("id","newId");

This will change the id of div

to applay click event or any jquery event on dynamically changed div you have to use

$(document).on('event',id,function(){});

give the code inside function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.