0

I'm calling this php file from Ajax and writing the required javascript code in this php file.

<div class="add_people_invite">
    <button class="btn btn-default add_connection" id="right_connection_request" onclick="SentRequestMouseUpRight(event,{{ $peopleMayKnow->id }})">
        <span>My Text</span>
    </button>
</div>

Javascript code :

<script>
    function SentRequestMouseUpRight(event, user_id) {
        if (event.which == 1) {
            alert();
            $("#right_connection_request span", this).text("My NEW Text");
        }
    }
</script>

alert in javascript is working but it is not changing the text to My NEW Text and if I remove this and then I run this code $("#right_connection_request span").text("My NEW Text"); It changes the text.

3
  • 3
    Why do you need this here anyway? You're using an ID and IDs as such must be unique. Commented Mar 30, 2016 at 18:48
  • This doesn't seem to have aynthing to do with ajax. Commented Mar 30, 2016 at 18:51
  • If you want this to refer to the clicked element, you'd need to use .call(this, … Commented Mar 30, 2016 at 18:51

3 Answers 3

1

You can use event.target instead of this keyword. Here is a fiddle to demonstrate the same.

function SentRequestMouseUpRight(event, user_id) {
  if (event.which == 1) {
    $(event.target).text("My NEW Text");
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

if I want to change onlick function then $(event.target).setAttribute('onclick','writeLED(1,1)') ,this will also work.
0

You may want to look at this first, $(this +"selector") ? $("img",this) possible?

The answer as to why it works one way but not the other I cant really tell by lookign at your example we will need to look at what version of Jquery you are using and a few other factors.

1 Comment

I had tried this too : $("span", this).text("My NEW Text"); but not working.
0

u can change html also if you dont want to change ur javascript, else accepted answer is correct.

<div class="add_people_invite"> <button class="btn btn-default add_connection" id="right_connection_request" onclick="return SentRequestMouseUpRight(this,{{ $peopleMayKnow->id }});"> <span>My Text</span> </button> </div>

'this' is window object in both cases.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.