简体   繁体   中英

Selecting a specific column in a option box using Javascript

I'm using the following php code to create a select option box:

$TypeLU = mysqli_query($mysqli, "SELECT * FROM LookupList");
while($Row = mysqli_fetch_array($TypeLU)) { 
    $TypeOptions = $TypeOptions."<option>$Row[1] $Row[2]</option>";
}

In HTML it gets displayed as a list with 2 columns. If I select and item from the list the value would be the concat of both $Row[1] and $Row[2] which is fine for display purposes, but I want to be able to 'extract' for example only $Row[1] as being the 'bound' value which I can then use as refrence.

So in pure Javascript I want to be able to get the value of just $Row[1] for example:

var x = document.getElementById("selectbox").value;
// So x must be only $Row[1] and not the concat of $Row[1] $Row[2]

Thanks

Use:

 $TypeOptions = $TypeOptions."<option value='$Row[1]'>$Row[2]</option>";

You may also want to consider escaping the variables in case they contain any < or " or other special HTML characters. See htmlspecialchars .

Full example with escaping:

 $TypeLU = mysqli_query($mysqli, "SELECT * FROM LookupList");
 while($Row = mysqli_fetch_array($TypeLU))
 {
     $Row[1] = htmlspecialchars($Row[1]);
     $Row[2] = htmlspecialchars($Row[2]);
     $TypeOptions = $TypeOptions."<option value='$Row[1]'>$Row[2]</option>";
 }

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