简体   繁体   中英

How to access via jquery to select controls created dynamically

I have created dynamically some select controls(aka groupbox) but every time that I try to access to one of them if get the followig error:

Uncaught TypeError:  undefined is not a function

Here is the code:

var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();

Where parseInt(buttonElementId + 1 is always a number so the error is not there

<html>
<head lang="en">
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
    <style>
        body        { padding-top:80px; }
        html, body, #wrapper
        {
            width: 100%;
            height: 100%;
        }
    </style>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div class="container">
        <div id="information"></div>
        <div id="tableInformation"></div>

        <div id="goBack"></div>
        <br/>
        <div id="inputDiv"></div>
        <br/>
        <br/>
        <div id="UserGuide"></div>
    </div>

    <script src="js/jquery-1.11.js"> </script>
<script>
    var apiUrl = 'http://localhost/devices';
    $( document ).ready(function() {
        // Handler for .ready() called.
        jsonGETRequest(apiUrl, jsonExampleData);

    });
    $(document).on('click', ':button' , function() {
        // reference clicked button via: $(this)

        $("#UserGuide").empty();
        var buttonElementId = $(this).attr('id');
        if(buttonElementId.indexOf("btnShowFunc") > -1) {
            buttonElementId = buttonElementId.replace("btnShowFunc","");
            deviceUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) + 1)].cells[1].innerHTML;
            goBack = "firstAPIRequest";
            $("#tableInformation tbody").remove();
            jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
        } else if(buttonElementId.indexOf("btnGoBack") > -1 ) {
            switch (goBack) {
                case "firstAPIRequest":
                    goBack = "";
                    $("#tableInformation tbody").remove();
                    jsonGETRequest(apiUrl, jsonExampleData);
                    removeGoBackInputDiv();
                    break;
                case "secondAPIRequest":
                    goBack = "firstAPIRequest";

                    $("#tableInformation tbody").remove();
                    jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
                    removeGoBackInputDiv();
                    break;
            }
        }else if(buttonElementId.indexOf("btnRunFunc") > -1) {
            goBack = "secondAPIRequest";
            buttonElementId = buttonElementId.replace("btnRunFunc","");
            var functionUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) +1)].cells[2].innerHTML;

            var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
            $("#tableInformation tbody").remove();
            $("#inputDiv").empty();
            // /jsonPOST(apiUrl  '/functions/' + functionUID )
        }

    });

    function loadDataIntoDeviceGrid(jsonData) {
        //$("#tableInformation").addClass("table table-responsive table-bordered");
        var tbl=$("<table/>").attr("id","mytable");
        $("#tableInformation").append(tbl);
        $("#mytable").append("<tr>" + "<th>dal.device.status</th>" + "<th>dal.device.UID</th>"
                + "<th>dal.device.driver</th>"  + "<th>service.id</th>" +"<th></th>" + "</tr>");
        for(var i=0;i<jsonData.length;i++)
        {
            var tr  = "<tr>";
            var td1 = "<td>"+jsonData[i]["dal.device.status"]+"</td>";
            var td2 = "<td>"+jsonData[i]["dal.device.UID"]+"</td>";
            var td3 = "<td>"+jsonData[i]["dal.device.driver"]+"</td>";
            var td4 = "<td>"+jsonData[i]["service.id"]+"</td>";

            //@Deprecated var dataList = fillSelectControl(jsonData[i]["objectClass"]); @Deprecated
            var btn = "<td>" +  "<button id='btnShowFunc"+ i + "' class='btn btn-success btn-lg'>See function</button>" + "</td></tr>";

            $("#mytable").append(tr + td1 + td2 + td3 + td4 + btn );

        }
        $("#mytable").addClass("table table-responsive table-bordered");
    }
    function loadInformationDeviceGrid() {
        $("#UserGuide").addClass("alert alert-info");
        $("#UserGuide").html("<h3>Getting devices list:</h3><br/> "+
                "Using this request, you can retrieve a list of all the available devices."+
                "For every device, among other info, there is the indication of the device unique ID, which" +
                "can be used to directly access to the device and the indication of the device driver (ZigBee, Bluetooth, etc.).<br/>If you want see some request response example please visit this <a href='#'>site</a>");
    }

    function removeGoBackInputDiv() {
        $("#inputDiv").empty();
        $("#btnGoBack").remove();
    }

    function loadDataIntoFunctionsGrid(jsonData) {
        $("#mytable").append("<tr>" + "<th>function.device.UID</th>"
                + "<th>service.id</th>"  + "<th>function.UID</th>"  + "<th>operation.names</th>" + "<th></th>" + "</tr>");
        var tr, td2, td3, td4, dt2, btn;
        for(var i = 0; i < jsonData.length; i++) {
             tr = "<tr>";
             //@Deprecated td1 = "<td>" + jsonData[i]["CLASS"] + "</td>";
             td2 = "<td>" + jsonData[i]["al.function.device.UID"] + "</td>";
             td3 = "<td>" + jsonData[i]["service.id"] + "</td>";
             td4 = "<td>" + jsonData[i]["dal.function.UID"] + "</td>";
             //@Deprecated dt1 = fillSelectControl(jsonData[i]["objectClass"]);
             dt2 = fillSelectControl(jsonData[i]["dal.function.operation.names"], i);
             btn = "<td>" +  "<button id='btnRunFunc"+ i + "' class='btn btn-success btn-lg'>Run</button>" + "</td></tr>";
            $("#mytable").append(tr + td2 + td3 + td4  + dt2 + btn );
        }
        createGoBackButton();
        createInputTextParameters();
    }

    function loadInformationFunctionsGrid() {
        $("#UserGuide").addClass("alert alert-info");
        $("#UserGuide").html("<h3>Getting device functions:</h3><br/>"
                              + "This API is used to retrieve the list of the available functions supported by the device. For"
                              + "example a Smart Plug has two functions: one to retrieve the energy consumption and another"
                              + "'boolean' function useful to change the status of the smart plug (ON/OFF). Every function"
                              + "indicates the id, which can be used to access directly the function and the list of the operation"
                              + "that can be invoked on the function.<br/>"
                              + "P.S. If he want use a function that want some parameters he must write these into the dedicated textbox. If the API needs more parameters separate these using comma. <br/>"
                              + "Example of parametes: <br/> <code>'type':'java.math.BigDecimal'</code><br/> <code>'value':1</code> <br/> etc...");
    }
    function createGoBackButton() {
        var btn = '<button id="btnGoBack"  class="btn btn-warning btn-lg">Go Back</button>';
        $("#goBack").append(btn);
    }

    function createInputTextParameters() {
        var lbl ="<label>Paramters</label>";
        var txt ='<input type="text" class="form-control" name="email">';
        $("#inputDiv").addClass("form-group");
        $("#inputDiv").append(lbl);
        $("#inputDiv").append(txt);

    }

    function fillSelectControl(obj, id) {
        var dataList = "<td><select id='slt"+ id +"'>";
        for(var j = 0; j < obj.length; j++)
            dataList = dataList + "<option value='" + obj[j] + "'>" + obj[j] + "</option>";
        return dataList = dataList + "</select></td>";
    }
    var json = "";
    var goBack = "";
    var deviceUID;
    function jsonGETRequest(url, dataExample){
        $.getJSON(apiUrl, function(data) {
            alert(JSON.stringify(data));
            this.json = data;
        })
                .done(function() {
                    $("#information").addClass("alert alert-success");
                    $("#information").text("getJSON request succeeded!");
                    if(goBack == "") {
                        loadDataIntoDeviceGrid(jsonExampleData);
                        loadInformationDeviceGrid();
                    } else if (goBack=="firstAPIRequest") {
                        loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
                        loadInformationDeviceGrid();
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    //alert('getJSON request failed! ' + textStatus);
                    $("#information").addClass("alert alert-danger");
                    $("#information").text("Impossible get data from API, it will be use example data" + errorThrown);
                    if(goBack == "") {
                        loadDataIntoDeviceGrid(jsonExampleData);
                        loadInformationDeviceGrid();
                    } else if (goBack=="firstAPIRequest") {
                        loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
                        loadInformationFunctionsGrid();
                    } else if(goBack=="secondAPIRequest") {

                    }
                })
                .always(function() {  });
    }
    function jsonPOST(url, method, paramters, dataExample) {

    }
    var jsonExampleData = [
        {
            "dal.device.status": 2,
            "dal.device.UID": "ZigBee:test123",
            "dal.device.driver": "ZigBee",
            "service.id": 28,
            "objectClass": [
                "org.osgi.service.dal.Device"
            ]
        },
        {
            "dal.device.status": 2,
            "dal.device.UID": "ZigBee:test456",
            "dal.device.driver": "ZigBee",
            "service.id": 29,
            "objectClass": [
                "org.osgi.service.dal.Device"
            ]
        },
        {
            "dal.device.status": 2,
            "dal.device.UID": "ZigBee:test789",
            "dal.device.driver": "ZigBee",
            "service.id": 30,
            "objectClass": [
                "org.osgi.service.dal.Device"
            ]
        }

    ];
    var jsonExampleDataFunctions = [
        {
            "CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
            "dal.function.device.UID": "ZigBee:test123",
            "service.id": 27,
            "dal.function.UID": "ZigBee:test123:testButton",
            "objectClass": [
                "org.osgi.service.dal.Function"
            ],
            "dal.function.operation.names": [
                "getData",
                "reverse",
                "setFalse",
                "setTrue"
            ]
        },
        {
            "CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
            "dal.function.device.UID": "ZigBee:test456",
            "service.id": 26,
            "dal.function.UID": "ZigBee:test456:testButton",
            "objectClass": [
                "org.osgi.service.dal.Function"
            ],
            "dal.function.operation.names": [
                "getData",
                "reverse",
                "setFalse",
                "setTrue"
            ]
        },
        {
            "CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
            "dal.function.device.UID": "ZigBee:test789",
            "service.id": 25,
            "dal.function.UID": "ZigBee:test789:testButton",
            "objectClass": [
                "org.osgi.service.dal.Function"
            ],
            "dal.function.operation.names": [
                "getData",
                "reverse",
                "setFalse",
                "setTrue"
            ]
        }
    ];
</script>
</body>
</html>

.is() returns a true/false value, it does not continue the jQuery chain, therefor there is no .text() function to call

As DevishOne points out in the comments to get the selected option's text do:

=$("#slt" + (parseInt(buttonElementId + 1))).children("option:selected").text();

Split that in to multiple steps and check for the particular result:

 button = $("#slt" + (parseInt(buttonElementId + 1)));
 if ( button )
 {
     childs = button.children("option");
     if ( childs .....

Whenever there's no option selected, you are unable to catch that since you refer directly to a method .text() of null.

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