简体   繁体   中英

How to get the text of dropdown and echo in php

I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.

Help?

<?php
    $resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
    $code = '';
     while($row = $resultcode->fetch_assoc())
        {
        $ok = $row['category'];
        $code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
        }
?>
<br/>

Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>

<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);

echo $result.'-'.$result1;      
?>

To get the selected text, you can use Javascript

var element = document.getElementById("mySelectTag");
var selected_text = element.options[element.selectedIndex].text;

To get a substring of a text, use Javascript, for example:

selected_text.substring(0,3)

You may try something like this:

Category
<select name="supplier" style="text-transform:uppercase;" onchange = "GetChangedValue(this);">
<option value="">Select</option>
<?php echo $code; ?>
</select>



<script>
function GetChangedValue(e) {
var value = e.options[e.selectedIndex].text;
alert(value);
}
</script>
function change(){
    var selectedtext = document.getElementById("idselect").value;
    document.getElementById("myTextField").value = selectedtext.substring(0,3);
}


<h1 id="title">Javascript example</h1>
<input type="text" id="myTextField"/>
<select id="idselect" onchange="change()">
    <option>Choose one</option>
    <option value="BLUE">Blue</option>
    <option value="YELLOW">Yellow</option>
    <option value="RED">Red</option>
</select>

http://jsfiddle.net/Fx5T8/

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