dqyitt2954 2017-11-02 20:08
浏览 65
已采纳

将特定的表格单元格值设置为文本框(jQuery / PHP)

I have 1 table with 2 columns. We'll call it col Number and col Letter. It appears as such:

1  |  A
2  |  B
3  |  C
4  |  D

I have 1 select2 drop down box that has a loop of all the Numbers - and a text box I would like to have the Letter appear that correlates with that number.

HTML/PHP querying current table

<label for="number">NUMBER</label>
<select onChange="setLetter(this)" style="text-transform: uppercase;" class="form-control select2" style="width: 100%;" name="number" id="number">
    <option selected="selected" disabled="disabled">-Select-</option>

    <?php
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            echo "<option name='".$row["Number"]."' value='".$row["Number"]."'>";
            echo $row["number"];
            echo "</option>";
        }
    } else {
        echo "0 results";
    }
    $conn->close();
    ?>
</select>
</div>

JavaScript attempt at querying the value of the select2 box

function setLetter(sel)
{
    var col = sel.value;
    <?php
    $number = "SELECT ['Letter'] FROM `msftrail` WHERE ['Number']= '".$col."'";
    ?>
    var php_var = "<?php echo $number; ?>";
    $("#letter").val(php_var);
}

How can I populate the Letter text box with the cell in the table that correlates with the correct number?

  • 写回答

3条回答 默认 最新

  • dongzhizhai4070 2017-11-02 22:14
    关注

    The easiest here would be to put all those rows in an array, and serializing it as JSON. Then you can load it up on the client.

    HTML+PHP:

    $msftrail = array();
    while($row = $result->fetch_assoc()) {
        echo "<option name='".$row["Number"]."' value='".$row["Number"]."'>";
        echo $row["number"];
        echo "</option>";
        $msftrail[$row['Number']] = $row['Letter']; // Store the mapping from Number to Letter in this array
    }
    

    JavaScript+PHP:

    var msftrail = <?php echo json_encode($msftrail); /* Send the array to the client as JSON */ ?>;
    function setLetter(sel)
    {
        var col = sel.value;
        var php_var = msftrail[col]; // Look up the letter for that number in the array
        $("#letter").val(php_var);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器