Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

return 2 values javascript

I’m trying to return two values in GAS like this:

Html

<script>
  function phoneSearch() {
    var phone = document.getElementById("phone").value;
    google.script.run.withSuccessHandler(onSuccess).phoneSearch(phone);
  }
  function onSuccess(name, email) {
    document.getElementById('nameDiv').innerHTML = "<div>" + name + "</div>";
    document.getElementById('emailDiv').innerHTML = "<div>" + email+ "</div>";
  } 
</script>

JS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function phoneSearch(phone){
  try {
    var ss = SpreadsheetApp.getActive();
    var sheet = ss.getSheetByName("sheetNameHere");
    var data = sheet.getDataRange().getValues();
    for (var i = 1; i < data.length; i++) {
      if (data[i][4] == phone) {
        var name = inputData[i][3];
        var email = inputData[i][5];
        return name;
        return email;
      }
    }
  } catch(e) {
    alert(e)
  }
}

Only the first value (name) returns. Thanks in advance!

>Solution :

You can only return 1 value from your function at a time, but you can easily wrap that in an object:

<script>
  function phoneSearch() {
    var phone = document.getElementById("phone").value;
    google.script.run.withSuccessHandler(onSuccess).phoneSearch(phone);
  }
  function onSuccess(result) {
  //                  ^ phoneSearch now returns -one- object, containing `name` and `email`.
    document.getElementById('nameDiv').innerHTML = "<div>" + result.name + "</div>";
    document.getElementById('emailDiv').innerHTML = "<div>" + result.email+ "</div>";
  } 
</script>

JS

function phoneSearch(phone){
  try {
    var ss = SpreadsheetApp.getActive();
    var sheet = ss.getSheetByName("sheetNameHere");
    var data = sheet.getDataRange().getValues();
    for (var i = 1; i < data.length; i++) {
      if (data[i][4] == phone) {
        var name = inputData[i][3];
        var email = inputData[i][5];
        // Return both values at once. 
        return { name, email };
        // (This is shorthand for: `return { name: name, email: email };`)
      }
    }
  } catch(e) {
    alert(e)
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading