HTML获取由PHP数组popledlated的select值

时间:2018-03-15 11:18:09

标签: javascript php html events dom

我认为我用HTML和PHP编写的内容如下:

<select name="category" id="_category" class="_cateogry"  onchange="submitTheForm() >
    option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
    <option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>

现在,我希望在调用onChange函数时获得<?php echo $contents->name;?>

我尝试在JS中解决它失败,这是我尝试的JS代码:

function submitTheForm () {
    var selectElement = document.getElementById('_category');
    var selected = selectedElem.options[selectedElem.selectedIndex];
    console.log(selected.text);
}

我希望在调用onchange函数时console.log所选的<?php echo $contents->name;?>

4 个答案:

答案 0 :(得分:1)

&#13;
&#13;
<select name="category" id="_category" class="_cateogry" onChange="submitTheForm(this);" >
    <option value="">Please select</option>
    <option value="1">First</option>
    <option value="2">Second</option>
</select>

<script>
    function submitTheForm(sel)
    {
        console.log(sel.options[sel.selectedIndex].text);
    }
</script>
&#13;
&#13;
&#13;

您可以按照以下方式执行

    // select box code whch one you have alredy
    <select name="category" id="_category" class="_cateogry" onChange="submitTheForm(this);" >
    <option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
    <option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>

//获取所选选项文本值的Javascript代码

<script>
    function submitTheForm(sel)
    {
        console.log(sel.options[sel.selectedIndex].text);
    }
</script>

答案 1 :(得分:1)

使用函数addEventListener绑定事件change

这是另一种选择。

您可以使用上下文value获取textthis

document.getElementById('_category').addEventListener('change', function() {
  console.log(this.value);
  console.log(this.options[this.selectedIndex].text);
});
<select name="category" id="_category" class="_cateogry">
    <option value="">Please select</option>
    <option value="1595">Ele</option>
</select>

答案 2 :(得分:1)

javascript函数后缺少",您的代码可能会被修改一下 - 使用event而不是依赖名称或ID

<select name="category" id="_category" class="_cateogry" onchange="submitTheForm(event)" >
    <option value="">Please select</option>
    <?php foreach ($categories as $contents ) {?>
        <option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
    <?php }?>
</select>

function submitTheForm( event ) {
    var value=event.target.value;
    var text=event.target.options[event.target.options.selectedIndex].text;
    console.log('%s -> %s',value,text);
}

答案 3 :(得分:0)

您可以轻松使用jquery而不是javascript:

function submitTheForm () {

   var optionName =  jQuery('#_category option:selected').text();

    alert(optionName);
}