Dvir Naim Dvir Naim - 12 days ago 6
HTML Question

How to put multiple arguments inside OPTION for Javascript?

I created a table in SQL via PHP that has 3 columns. I'm trying to put the values inside a SELECT dropdown in this way:


  • The first column will be in the value of the OPTION (for passing in the POST).

  • The second column will be in the display of the OPTION.

  • The third column will be hidden and sticks to each row in the dropdown, so when the user chooses one option from the dropdown, the hidden column will present in other div.



For example, if the table is:

col1 col2 col3
-----------------
1 Joe Key st.
2 Matt Link st.


When the user chooses Joe,
Key st.
will display in a separate div, and after the user presses enter, the value
1
will be sent via POST.

This is what I got so far:



$('.foo3').on('change', function() {
var add = $(this).parent().find('.foo3').value();
$('.foo2').html(add);
});

<select class="foo3">
<?php while ($curRow=mysqli_fetch_array($TableOutput)) {
echo "<input class='foo' type='hidden' value='{$curRow['col3']}'><option value='{$curRow['col1']}'>{$curRow['col2']}</option>";
} ?>
</select>
<div class="foo2"></div>





Thanks!

Answer

You can store your own metadata in an element by using data attribute. You can then read that back out when the option is chosen. Try this:

$('.foo3').change(function() {
  $('.foo2').text($(this).find('option:selected').data('location'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="foo3">
  <option>Please select...</option>
  <option value="1" data-location="Key St.">Joe</option>
  <option value="2" data-location="Link St.">Matt</option>
</select>
<div class="foo2"></div>

To create that HTML output, your PHP would look like this:

echo "<option value=\"{$curRow['col1']}\" data-location=\"{$curRow['col3']}\">{$curRow['col2']}</option>";
Comments