4

I have a simple jQuery question with the following code:

 <script>
    $(document).ready(function() {
    $("#changeText").click(function() {
        $.get("test.php", { sectid: "1"},
            function(data){
            $("#textBox").html(data);
        });
    });
    });
 </script>

My HTML is as follows:

<a id="changeText" href="#">Change</a>
<div id="textBox">This text will be changed to something else</div>

I'd like to pass a variable into the .click function in place of "1" but can't seem to get the syntax correct. Can someone point me the right direction?

Thanks.

2 Answers 2

2

You just use the variable name, for example:

$(document).ready(function() {
  $("#changeText").click(function() {
    var myVariable = "1";
    $.get("test.php", { sectid: myVariable },
        function(data){
        $("#textBox").html(data);
    });
  });
});

Or if it's a value from something for example:

$.get("test.php", { sectid: $(this).attr("something") },
Sign up to request clarification or add additional context in comments.

6 Comments

I think he wants to pass a variable to the click function when it's called.
@Rocket - in that case it'd look the same, just with the var MyVariable = "1"; moved outside/before.
@Nick: Yeah, I know. I was just sayin'.
Sorry, bear with me... I want to pass it through the html code so if I had multiple links I could change the link at the href and pass it through to the php code on the back end. If I bury this function in another function it doesn't seem to work for me.
@Seth - can you give an example of the markup, and what from it you want to pass? If for example you wanted the current clicked link's href, it'd be $(this).attr("href"), or this.href if you didn't care about normalization in IE.
|
0

You can set the variable before the function is called. Then read it's value after.

Example (using jQuery's .data):

$("#changeText").data('sectid', '1');

 $("#changeText").click(function() {
    $.get("test.php", {sectid: $(this).data('sectid')},
        function(data){
          $("#textBox").html(data);
    });
});

2 Comments

You can use $.data(this, 'sectid') which is much cheaper...but even that seems like overkill, why would you store a known thing via .data() on an ID element (which should be unique)?
@Nick: Yeah, I guess it is overkill, but it's the first thing that I could think of. Also, he wants the sectid to be a variable, and I wanted my answer to be different from yours :-P

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.