简体   繁体   中英

jQuery: How to get input value within an ajax call?

I have a jQuery script, in which I need to load data from a CSV from an external URL.

At the same time, I need to combine the data from the CSV with data provided by a frontend user through an input field. My expected result would be that I'd be able to call the jQuery code for fetching the value from the user's entry into the input field. However, while this works when the code is placed outside the ajax call, it does not work inside.

At the same time, I can't place the code for fetching the user's input outside the ajax call, as I need to be able to utilize information from the loaded CSV together with the user input to perform a dynamic calculation.

My code is as below:

HTML:

<input type="text" id="my_input" value="12" maxlength="2">

Javascript:

$.ajax({
    url: csv_url,
    async: false,
    success: function (csvd) {
      var csv = $.csv.toObjects(csvd);
      // XYZ done with the CSV data to populate various fields

      $("#my_input").keyup(function () {
          console.log(this.value);
          // this does not result in anything being logged
      });
    },
    dataType: "text",
    complete: function () {}
  });

Of course it will not work. You are telling the compiler to add the keyup event listener to input after the ajax call is successful. Which means it will not work until ajax call is completed successfully.

You need to put the keyup event listener outside and inside the ajax call just get the value like below:

let myInputValue = "";

    $("#my_input").keyup(function () {
        console.log(this.value);
        myInputValue  = this.value;

     });
    
    $.ajax({
        url: csv_url,
        async: false,
        success: function (csvd) {
          var csv = $.csv.toObjects(csvd);
          // XYZ done with the CSV data to populate various fields
    
          //And later use the myInputValue here
        },
        dataType: "text",
        complete: function () {}
      });

You have not give us enough info. if you only need the current value in the ajax call you can do like below:

$.ajax({
            url: csv_url,
            async: false,
            success: function (csvd) {
              var csv = $.csv.toObjects(csvd);
              // XYZ done with the CSV data to populate various fields
        
              let myInputValue = $("#my_input").val();//And later use the myInputValue here
            },
            dataType: "text",
            complete: function () {}
          });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM