JQuery - pass a variable to a click function

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 want to pass a variable to a function .clickinstead of "1", but it doesn't seem to return the syntax. Can someone point me in the right direction?

Thank.

+3
source share
2 answers

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 this value is from something like:

$.get("test.php", { sectid: $(this).attr("something") },
+2
source

You can set a variable before calling the function. Then read this value after.

Example (using jQuery .data):

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

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

Source: https://habr.com/ru/post/1782497/


All Articles