-1

Hello I want to achieve is to make "Select Form HTML" dynamic using JavaScript, What I mean by that is I expect every time I select a dropdown must be selected the value that I set to that tag.

The data from tag is from database I loop the data using php

ex. 1 src: Get selected value/text from Select on change
This example is 100% working correct but what I need is not to get the value but to assign like sample below next example 2

function handleSelectChange(event) {

    var selectElement = event.target;
    var value = selectElement.value;
    alert(value);
}

<select onchange="handleSelectChange(event)">
    <option value="1">one</option>
    <option value="2">two</option>
</select>

ex 2 Those function will alert or run everytime I select/Click each of them F1 or F2

<table>
    <tr>
      <td onclick="myFunction1()">F1</td>
      <td onclick="myFunction2()">F2</td>
    </tr>
</table>

<script>
 
 // Function 1 will run when I click the F1 
 function myFunction1() { alert('myFunction1'); }
 // Function 2 will run when I click the F2
 function myFunction2() { alert('myFunction2'); }

In example 1 As you can see the first example select form html will grab the the value of option tag, right?.
Now In example number 2 it will run the function when I click each of the F1 or F2

So what I need to the program is pass a value from my database to my javaScript function and run it like in alert or example 1 but in "Select tag" HTML version

ex. 3 Here's my query

 <form action=""> 
  <select name="customers" id="myId" class="form-control">
    <option value="">Select a customer:</option>

 <?php 
    
 $user_id =  1;
 
 $sql     = "SELECT * FROM `myTable` WHERE user_id = '$user_id' Order by create_at DESC";
 $result  = $mysqli->query($sql);
 
 if ($result->num_rows > 0) {
   
  // output data of each row
  while($row = $result->fetch_assoc()) 
  { ?>
    
   <!-- appsFunction('<?php echo $row['colName2']; ?>') << will be the value that should run in console.log -->
   <option value="<?php echo $row['id']; ?>" onclick="appsFunction('<?php echo $row['colName2']; ?>')"><?php echo $row['colName1']; ?></option>

  <?php }
  
 } else {  return false;  }
 
 ?>
 </select>
</form>

ex. 3 part 2 javascript

<script>

function appsFunction(passVar) {
  
  colose.log(passVar);

}

</script>

As you can see in my first example a "Select Tag" HTML when I select dropdown it returns to me a value right?, in second example when I click F1 or F2 it will run the function then return alert, What I need here is When I select the dropdown it will accept the value I pass in function "appsFunction(passVar)" appsFunction('<?php echo $row['colName2']; ?>') from select tag which the value is from my database.. so I need help idea how to do that properly..

NOTE: The function must be run when I select the dropdown, the function must be accept the value I set which from my database it's like totally example number 2 but in Select tag HTML version not just text or html table.

Thanks in advance for solving my problem.

  • I'm a bit confused, do you mean that you want to display the selected dropdown value in the alert? – Sal Jan 04 '21 at 08:28
  • Please read how to create a [minimal, reproducible example](/help/mcve). – Wais Kamal Jan 04 '21 at 08:36
  • nope, look example number 3 I have function ``` appsFunction() ``` I have different value for that function, so when I select different dropdown it will return different value.. make sense? – Renniel Fernandez Jan 04 '21 at 08:37
  • I don't get your problem. "every time I select a dropdown must be selected the value that I set to that tag" - that's how HTML forms work from the very beginning. There is no way you would ever need JS, PHP, or MySQL for this – Nico Haase Jan 04 '21 at 08:47
  • @NicoHaase He means that he doesn't want the value from the `value` attribute to display in the console, but a second value that is bound to the ` – Emiel Zuurbier Jan 04 '21 at 08:54
  • @Sal When I click

    it will return to console.log; how to achive this in drop down properly reference: https://www.screencast.com/t/AEB5Qm8jqnyY

    – Renniel Fernandez Jan 04 '21 at 09:19

1 Answers1

0

If you register an event handler on the select element itself that listens for change events you will be able to process the selected OPTION and access any value/property associated with it. You cannot assign an event handler directly to an OPTION element as you are trying to do here. You can add as many dataset attributes as you need to the OPTION elements however which you can easily access in the Javascript event handler.

If the value you pass into the SQL statement is to be dynamic ( from a GET or POST request most usually ) you really need to use a Prepared Statement to help mitigate SQL Injection attacks.

As your select menu is making use of only 3 columns from the mytable table you should limit the returned fields to those columns which in turns helps when using a Prepared Statement as you can easily assign the results as variables.

<form name='geronimo'> 

    <select name="customers" class="form-control">
        <option selected hidden disabled>Select a customer:
        <?php 

            $user_id =  1;

            $sql="select `id`, `colName1`, `colName2` from `mytable` where user_id = ? order by create_at desc";
            $stmt=$mysqli->prepare($sql);
            $stmt->bind_param('s',$user_id);
            $res=$stmt->execute();
            
            if( $res ){
                $stmt->bind_result($id,$col1,$col2);
                while( $stmt->fetch() ){
                    printf('<option value="%s" data-col="%s">%s', $id, $col2, $col1 );
                }
                $stmt->free_result();
                $stmt->close();
            }
        ?>
    </select>
</form>


<script>
    document.forms.geronimo.customers.addEventListener('change',function(e){
        let id=this.value;
        let col2=this.dataset.col;
        let col1=this.options[this.options.selectedIndex].text;
        
        alert( id + ' ' + col2 + ' ' + col1 )
    });
</script>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Also, that `if( $res ){` doesn't make much sense. You check only for the return value of `execute` and then you have both `free_result()` and `close()` inside the `if`. That makes no sense why would you want to close the statement only when it was successfully executed. Instead of doing this kind of thing, you should always have error reporting enabled. – Dharman Jan 04 '21 at 11:54
  • fair play I take the point but this was more a javascript issue than the OPs php (despite potential for sql injection. ) – Professor Abronsius Jan 04 '21 at 11:58