LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-26-2022, 09:06 PM   #1
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Rep: Reputation: 12
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()
 
Old 09-28-2022, 12:06 PM   #2
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,269
Blog Entries: 24

Rep: Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196Reputation: 4196
Quote:
Originally Posted by pizzipie View Post
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).
 
Old 09-29-2022, 05:16 PM   #3
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
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>
 
Old 09-30-2022, 06:25 AM   #4
Guttorm
Senior Member
 
Registered: Dec 2003
Location: Trondheim, Norway
Distribution: Debian and Ubuntu
Posts: 1,453

Rep: Reputation: 448Reputation: 448Reputation: 448Reputation: 448Reputation: 448
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.
 
1 members found this post helpful.
Old 09-30-2022, 01:44 PM   #5
pizzipie
Member
 
Registered: Jun 2005
Location: Hayden, ID
Distribution: Ubuntu 20.04
Posts: 441

Original Poster
Rep: Reputation: 12
Thank you Guttorm,

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

R
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
LXer: Latest Firefox available to users where they browse the web laptop, Fire TV and the office. Plus, a chance to help with the next Fire LXer Syndicated Linux News 0 03-14-2018 01:01 AM
strange value assignments variable = value, value?? ostrow30 Programming 2 07-24-2011 07:59 AM
difference between value *value and value * value PoleStar Linux - Newbie 1 11-26-2010 03:37 PM
How to replace fire fox 1.5.0.9 with fire fox2 in mepis 6.0 inspiron_Droid LinuxAnswers Discussion 0 02-21-2007 01:19 PM
javascript alerts with radio modules graziano1968 Programming 3 11-10-2004 03:14 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:40 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration