LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Javascript - can't get return value - alerts fire prematurley (https://www.linuxquestions.org/questions/programming-9/javascript-cant-get-return-value-alerts-fire-prematurley-4175717171/)

pizzipie 09-26-2022 09:06 PM

Javascript - can't get return value - alerts fire prematurley
 
Hi Using Ubuntu 20.04

Can't get a return value from functio getChoice().
Also how do you stop the alert functions from going off prior to data being fed to them?? I know this is related to the 'return' problem but I can't discover how to fix this.

Thanks for help in fixing.

R

Code:


Excerpt from dbConnect.html

<script type="text/javascript">

$(document).ready(function(){

var db="";

 $('#exit').click(function ()  {
                location.href='xperFrontEnd.html'
 });       
$("#getdb").click(function ()  {
        var request = $.ajax({
            url: "getDbs-Tbls.php",
            dataType: "json"       
        });
       
        request.done(function(data) {
        var dbases=new Array();
        for (var i=0; i<data.length; i++) {
                dbases[i]=data[i]['db'];
        }
       
        var y =getChoice(dbases); // function in dropdownDB.js
        alert(y);              // NOTHING HERE

}); // end done

request.fail(function (jqHR, textStatus) {
        alert("failed at line 97");
});
 
}); //end #getdb

}); // end doc ready

</script>

Code:

Excerpt from dropdownDB.js

// ========= CREATE SELECT BOX & MAKE CHOICE  ==============

function getChoice(data) {

var myselection="";

        $('#dbsbox').show();
        $('#dbsbox').append($("<h4>Make Your Choice</h4>"))  // Header
                              .append("<select id='selbox' name='selbox' size='5'></select>");  // Select Box
    for (const val of data) {
            $('#selbox').append($("<option>").prop({ value: val, text: val })); // Options
    } // for
    $('#dbsbox').append("<br><br>");
   
        $("#selbox").on('change', function () {  // pick choice
                        myselection=$("#selbox option:selected").text(); 
                        $("input[name=dbase]").val(myselection);
                        $('#dbsbox').hide();
                        alert("my sel "+myselection); // SHOWS CORRECT VALUE
                        return myselection;              // DOESN"T WORK
        }); // change
    //  Alternate position for return myselection;        DOESN"T WORK

} // end getchoice()


astrogeek 09-28-2022 12:06 PM

Quote:

Originally Posted by pizzipie (Post 6382787)
Hi Using Ubuntu 20.04

Can't get a return value from functio getChoice().
Also how do you stop the alert functions from going off prior to data being fed to them?? I know this is related to the 'return' problem but I can't discover how to fix this.

Code:


function getChoice(data) {

var myselection="";

        $('#dbsbox').show();
        $('#dbsbox').append($("<h4>Make Your Choice</h4>"))  // Header
                              .append("<select id='selbox' name='selbox' size='5'></select>");  // Select Box
    for (const val of data) {
            $('#selbox').append($("<option>").prop({ value: val, text: val })); // Options
    } // for
    $('#dbsbox').append("<br><br>");
   
        $("#selbox").on('change', function () {  // pick choice
                        myselection=$("#selbox option:selected").text(); 
                        $("input[name=dbase]").val(myselection);
                        $('#dbsbox').hide();
                        alert("my sel "+myselection); // SHOWS CORRECT VALUE
                        return myselection;              // DOESN"T WORK
        }
); // change
    //  Alternate position for return myselection;        DOESN"T WORK

} // end getchoice()


There is no return value from getChoice(), the value returned from the anonymous function in blue is simply discarded (if I remember my JQuery correctly).

pizzipie 09-29-2022 05:16 PM

I'll try again. Hopefully this explains my problem a litttle better.

I am trying to use a dropdown box but can't get selected value outside of $("#selbox").on('click', function (). I have tried using return but that doesn't work. Any help greatly appreciated.

R

Code:

 

Place in program: <head>

 <script type="text/javascript">
              $("#returneddatabox").hide();
  window.myselection=""; // declare global
    </script>

Place in program: Just above </body>


//  =========  dbases ==================
 

 $("#getdb").click(function ()  {

    var request = $.ajax({
        url: "getDbs-Tbls.php",
        dataType: "json"       
    });
   
    request.done(function(data) {
        for (var i=0; i<data.length; i++) {
            dbases[i]=data[i]['db'];
        }
        getChoice(dbases); // this function is in dropdownDB.js see below
 
        console.log("myselection:103"+myselection);  //  output:  "myselection:103        "
        alert("myselection:104"+myselection);        //  output:  localhost - myselection:104


    }) // end request done
   
    request.fail(function (jqHR, textStatus) {
            alert("error at line 106");
        });
           


}); // end #getdb

// ========= dropdownDb.js - CREATE SELECT BOX & MAKE CHOICE  =============
=

function getChoice(data) {

    $('#dbsbox').show();
    $('#dbsbox').append($("<h4>Make Your Choice</h4>"))  // Header
                  .append("<select id='selbox' name='selbox' size='5'></select>");  // Select Box
    for (const val of data) {
        $('#selbox').append($("<option>").prop({ value: val, text: val })); // Options
    } // for
    $('#dbsbox').append("<br><br>");
   
    $("#selbox").on('click', function () {                      // pick choice
          myselection=$("#selbox option:selected").text();
            $('#dbsbox').hide();
            // return myselection;  // doesn't work
            alert( "line 23 getChoice "+myselection);  // output: "line 23 getChoice contacts"  ie: SHOWS VALUE
    }); // change
            alert( "line 25 getChoice "+myselection); // output: localhost - "line 25 getChoice"              
} // end getchoice()

//  =========================================================

Quote:

Sequence of visuals:

Start program click button "getdbases" (not shown above) Then:

alert() - localhost - "line 25 getChoice <nothing> "
alert() - localhost - "myselection:104 < nothing> "

Make a Choice and:

alert() - "line 23 getChoice <contacts> / / which was my choice
console:log() - "myselection:103 <nothing>


Guttorm 09-30-2022 06:25 AM

Hi

You are mixing up async functions vs callbacks and regular functions.

If you think about it, the getChoice function cannot work. What it does is basically:

- show some html (a header and a select box).
- set up a callback function so when you click on #selbox, that function will be called.
- return - all done

When getChoice returns, you have not selected anything.

If you want to do something when something in the select box is selected, do it in the callback function.

Or another strategy is to make another button that does something. Then you can simply check $("#selbox option:selected").text() and give an error message if nothing is selected.

pizzipie 09-30-2022 01:44 PM

Thank you Guttorm,

I followed your suggestion and it all worked out fine!!!!

R


All times are GMT -5. The time now is 01:28 PM.