跟踪已单击哪个列表元素并将此数据传输到PHP中



我正在尝试创建一系列列表项目,当单击时将提交带有隐藏输入值的表单。问题在于,我似乎无法弄清楚如何从HTML中提取列表索引号并将其传输到PHP逻辑检查中,以显示单击列表右侧的输入字段的名称。

<?php
    $students = ['bob','paul'];     
?>
<section id="tablet_container">
    <div class="upload-tableview-wrapper">
        <ul>
            <form id="select_student" name="select_student" method='POST' action="<?php echo ($_SERVER['PHP_SELF']); ?>">
                <li><input type="hidden" name="student_firstname[]" value="<?php echo $students[0]; ?>">
                    <?php echo $students[0];?>
                </li>
                <li><input type="hidden" name="student_firstname[]" value="<?php echo $students[1]; ?>">
                    <?php echo $students[1];?>
                    <li>
            </form>
        </ul>
        </div>
<?php
    if (isset($_POST['student_firstname'])) {      
?>
    <div id="manual_student_container">
        <label id="label_student_first_name"> First Name:</label>
        <input type="text" readonly name="student_first_name" id="student_first_name" value="<?php echo $_POST['student_firstname'][1]; ?>">
    </div>
    </section>
<?php
    }     
?>  

javascript -jquery

 $(document).ready(function () {
    //colour selection rd and submit the form
    $('li').click(function () {
        $('li').css({ "background-color": "#F7F7F7" });
        $(this).css({ "background-color": "red" });
        var selectedStudent = $(this).text();
        // Remove saved data from sessionStorage
        sessionStorage.removeItem('selectedStudent');
        //store the new value
        sessionStorage.setItem('selectedStudent', selectedStudent);
        $('#select_student').submit();
    });
});

CSS

.upload-tableview-wrapper {
    position:absolute;
    height: 270px;
    width: 200px;
    top:60px;
    left:80px;
    box-shadow:inset 0px 1px 0px rgba(0, 0, 0, 0.075), 0px 1px 0px  rgba(255, 255, 255, 0.75);
    overflow: scroll;
    background-color: black;
}
ul {
    list-style-type:none;
    font-family:"Helvetica";
    font-size:16px;
    padding:0;
}
ul li {
    background-color:#F7F7F7;
    padding:14px 10px;
    border-left:1px solid #B2B4B8;
    border-right:1px solid #B2B4B8;
    border-bottom:1px solid #CBCBCB;
    border-top:1px solid #FDFDFD;
    color:#385487;
}
ul li:hover {
    color:white;
    background-color: red;
}

您可以填充带有选定值的隐藏输入并提交表单

<input type="hidden" name="selected_student" id="selected_student" value="" />
<script>
$('li').click(function() 
{
    $('li').css({"background-color": "#F7F7F7"});
    $(this).css({"background-color": "red" });
    var  selectedStudent=$(this).text();
    $('#selected_student').val(selectedStudent);
    $('#select_student').submit();
}  
</script>

您可以使用$_POST['selected_student']

访问PHP中的值

Submit()用于表单,并将自动提交给html中的任何表单操作。

喜欢<form action="/action_page.php" method="post">

您是否将输入值发送到任何PHP脚本/页面?


编辑:好吧,首先确保text()实际上获得了您想要的价值。我建议在输入上使用val()只是为了安全。

var selectedStudent=$(this).children('input').val();

最新更新