Ive created a dropdown box dynamically getting datea from a database but when I try to get (or set) the first value, it always says undefined.

Ive tried something like:

$j("#mydiv").val(1);
var somevariable = $j("#mydiv").val();
console.log ("print it out " + somevariable);

And it says

print it out undefined

If I add a alert it works. Seems to be because of a delay so I how can I get it to work? Thank you.

Recommended Answers

All 14 Replies

$j("#mydiv").val(1);

Maybe it should be $j("#mydiv").val('1');?

Member Avatar for diafol

Are you using $j for $/jQuery?

Maybe it should be $j("#mydiv").val('1');?

Putting:

$j("#combobox").val('1');
var myvariable="";
var myvariable = $j("#combobox").val('1'); 
console.log("print out " + myvariable);

Prints out

print out [object Object]

I know the combobox is indeed populated.

Try this

var optionalValues=[];
$('#combobox option').each(function(){
    optionalValues.push( $(this).attr('value'));
});
var FirstOption = optionalValues[0];
alert(FirstOption);

Try this

var optionalValues=[];
$('#combobox option').each(function(){
optionalValues.push( $(this).attr('value'));
});
var FirstOption = optionalValues[0];
alert(FirstOption);

Nothing. Still same thing. Says it is undefined.

When I try it in my PC it works fine.. One question . Why do you use $j ?
Check the following code. It's my code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>

<body>
<select id="My">
<option value="Test">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</body>
<script type="text/javascript">
$(function() {
var optionalValues=[];
$('#My option').each(function(){
    optionalValues.push( $(this).attr('value'));
});
    var FirstValue = optionalValues[0];
    alert(FirstValue);
});
</script>
</htm>

When I try it in my PC it works fine.. One question . Why do you use $j ?
Check the following code. It's my code

Because my jquery is defined this way.

Also, are you sure your code is this way? You have a </htm> tag at the end which is at least not standard and should not work.

This is my code:

formapredeterminada: function(point)
    {


        var varpas=$j('#iddetienda',window.parent.document).text();
        varpas.replace(/\s/g, "");


        $j.ajax({                                      
            url: 'mysqlcall.php',                  //script para obtener datos      
            data: "idpastelero="+varpas,                        //you can insert url argumnets here to pass to api.php
                                            //for example "id=5&parent=6"
            dataType: 'json',                //data format      
            success: function(data)          //on recieve of reply
                {

               var selecthtml='Formas predeterminadas: <select name="dibujoshechos" id="dibujoshechos">'

                    for (var i=0;i<data.length;i++)
                        {     

                            var row = data[i];          
                            var nombre = row[0]; //nombre


                            var coordenadas = row[1]; //coordenadas

                            selecthtml=selecthtml+'<option value="'+coordenadas+'">'+nombre+'</option>';



                        } 
                        selecthtml=selecthtml+'</select>';
                           $j('#formas').append(selecthtml);



                  } 

                });


    var draws = this.canvasListener.getDrawManager().getAll();


    $j("#dibujohechos").val('1');



    var lospuntos="";


    var lospuntos = $j("#dibujoshechos").val('1'); 
    console.log("the value is " + lospuntos);




        this.canvasListener.redraw();
    },

No errors, just says undefined.

You have a </htm> tag at the end which is at least not standard

Sorry ..Thats was my typing mistake..

Did you try like this ?

var optionalValues=[];
$j('#dibujoshechos option').each(function(){
    optionalValues.push( $j(this).attr('value'));
});
    var lospuntos="";
    var lospuntos = optionalValues[0]; 
    console.log("the value is " + lospuntos);

And check it in your console.

Same thing.

"the value is undefined"

No error.

Same thing.

"the value is undefined"

No error.

Oh I see. You use Ajax to create the specified select tag, and right after you attempt to call the select element. Yes, that would not work unless your Ajax call is synchronous (but that would go agaist the purpose of Ajax). I do not know how to make it synchronous in JQuery, so I will suggest you a work around.

One approach is that you could take the part where you attempt to access the populated elements out to another function. Then access that function and see if the selected element exists. If it does, do whatever you want; otherwise, call it again using delay() of JQuery or setTimeout() (whichever is appropriate to your script).

var draws = this.canvasListener.getDrawManager().getAll();
selectDefault("dibujohechos", 1);

... // end the function

function selectDefault(id, val) {
  var lospuntos = $j("#"+id).val(val);
  if (lospuntos=="undefined") {
    // call the selectDefault() again with a sleep/delay time
  }
  else {
    // do whatever you want to do
  }
}

The other approach is to cut all the script part you access the element and place it inside success: portion at the end after you populate the data.

New code:

formapredeterminada: function(point)
    {


        var varpas=$j('#iddetienda',window.parent.document).text();
        varpas.replace(/\s/g, "");


        $j.ajax({  // Start AJAX function                                     
            url: 'mysqlcall.php',                  //script para obtener datos      
            data: "idpastelero="+varpas,                        //you can insert url argumnets here to pass to api.php
                                            //for example "id=5&parent=6"
            dataType: 'json',                //data format      
            success: function(data)          //on recieve of reply
                { //start success function

               var selecthtml='Formas predeterminadas: <select name="dibujoshechos" id="dibujoshechos">'

                    for (var i=0;i<data.length;i++)
                        {    //start for  

                            var row = data[i];          
                            var nombre = row[0]; //nombre


                            var coordenadas = row[1]; //coordenadas

                            selecthtml=selecthtml+'<option value="'+coordenadas+'">'+nombre+'</option>';



                        }  //end for
                        selecthtml=selecthtml+'</select>';
                           $j('#formas').append(selecthtml);

                           var draws = this.canvasListener.getDrawManager().getAll();









                        $j.each(draws, function(index, draw) {
                                    if (draw.hasPoints() && draw.isPointSelected()) {





                                        var points = draw.getPointManager().getAll();
                                            $j.each(points, function(index, point) 
                                            {


                                            }.bind(this));

                                    }
                                }.bind(this));


                        var dot="";
                        dot=$j("#dibujoshechos").val();


                        console.log("value is " + dot);

                        } //end sucess



                                    }); //end ajax function




        this.canvasListener.redraw();
    },

The console line doesnt get printed out at all.

Your

I do not know how to make it synchronous in JQuery

comment made me think and I did this:

formapredeterminada: function(point)
    {


        var varpas=$j('#iddetienda',window.parent.document).text();
        varpas.replace(/\s/g, "");


        $j.ajax({  // Start AJAX function                                     
            url: 'mysqlcall.php',                  //script para obtener datos      
            async: false,
            data: "idpastelero="+varpas,                        //you can insert url argumnets here to pass to api.php
                                            //for example "id=5&parent=6"
            dataType: 'json',                //data format      

            success: function(data)          //on recieve of reply
                { //start success function

               var selecthtml='Formas predeterminadas: <select name="dibujoshechos" id="dibujoshechos">'

                    for (var i=0;i<data.length;i++)
                        {    //start for  

                            var row = data[i];          
                            var nombre = row[0]; //nombre


                            var coordenadas = row[1]; //coordenadas

                            selecthtml=selecthtml+'<option value="'+coordenadas+'">'+nombre+'</option>';



                        } 
                        selecthtml=selecthtml+'</select>';
                           $j('#formas').append(selecthtml);



                        } //end sucess



                                    }); //end ajax function


          var draws = this.canvasListener.getDrawManager().getAll();








                        $j.each(draws, function(index, draw) {
                                    if (draw.hasPoints() && draw.isPointSelected()) {




                                        //Modificaion
                                        var points = draw.getPointManager().getAll();
                                            $j.each(points, function(index, point) 
                                            {


                                            }.bind(this));

                                    }
                                }.bind(this));


                        var lospuntos="";
                        lospuntos=$j("#dibujoshechos").val();


                        console.log("value is " + lospuntos);



        this.canvasListener.redraw();
    },

And I got a console output and the correct console output at that.

Thank you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.