Get Text From

前端 未结 5 1841
野趣味
野趣味 2020-11-29 08:32

I want to get text inside the tags as well as its value.

Example


                        
    
提交评论

  • 2020-11-29 09:11

    set the value of text to the value of the option tag, be it through static HTML markup or even if it's being generated by a server side script. You will only get the value attribute through POST

    Another option however, on the server side, is to map the value ("5"), to an associative array, i.e.

    <?php
    $valueTextMap = array("5" => "Text");
    
    $value = $_POST['make'];  //equals 5
    $text = $valueTextMap[$value];  //equals "Text"
    ?>
    
    0 讨论(0)
  • 2020-11-29 09:17

    What about this? I think it's the best solution because you have separated fields to each data. Only one hidden field which is updated at each change and avoids hardcoding mappings.

    This inside HTML:

    <select name='make' onchange="setTextField(this)">
    <option value = '' selected> None </option>
    <option value = '5'> Text 5 </option>
    <option value = '7'> Text 7 </option>
    <option value = '9'> Text 9 </option>
    </select>
    <input id="make_text" type = "hidden" name = "make_text" value = "" />
    <script type="text/javascript">
        function setTextField(ddl) {
            document.getElementById('make_text').value = ddl.options[ddl.selectedIndex].text;
        }
    </script>
    

    This inside PHP:

    <?php
    $value = $_POST["make"];
    $text = $_POST["make_text"];
    ?>
    
    0 讨论(0)
  • 2020-11-29 09:20

    I have always used a very elegant solution, similar to the ones already presented, which does not require a lot of additional code.

    HTML

    <select name="make">
      <option value="1:First Option">First Option Text</option>
      <option value="2:Second Option">Second Option Text</option>
      <option value="3:Third Option Text">Third Option Text</option>
    </select>
    

    PHP

    $value = split(':', $make)[0];
    $text = split(':', $make)[1];
    

    Benefits of this method
    Yes, there are definitely similarities to serialworm's answer, yet we minimize the code in our PHP block by inconspicuously converting to an array and picking the element required right away.

    In my case, I use this exact short-hand code in a contact form where this one-liner (to get the selected department name) is critical to keeping the code looking clean.

    0 讨论(0)
  • 2020-11-29 09:25

    You'll need to include that Text in the value to begin with (e.g.: <option value="5_Text"> Text </option> and then parse, or...

    You could use javascript on the page to submit the text as another parm in the POST action.

    0 讨论(0)
  • 提交回复
    热议问题