I have a dropdown menu that is generated in a different file. It is generated with a while loop, and I would like to add one static value ( Select contract ).
Right now a dropdown menu looks like this:
1234
4321
2323
3232
And I would like to make it like this:
Select contracr
1234
4321
2323
3232
Here is my code in index.php:
<select id="text2" name="text2">
</select>
And here is my code in process.php (where items are generated):
<?php
$selectedKey = $_GET['selected_key'];
$query = "SELECT * FROM `1 received` WHERE Key = '".$selectedKey."'";
$run = mysql_query($query);
while($row = mysql_fetch_assoc($run)) {
echo "<option value='".$row['Number']."'>".$row['Number']."</option>";
}
?>
Ajax code:
<script>
$("select#select2").change(function(){
$.ajax({
type: "GET",
url: "process.php",
data: "selected_key=" + $(this).val(),
success: function(result) {
$("select#text2").html(result);
}
});
});
</script>
I think you’re overthinking this.
Just add an extra option to the
<select>– i.e. a literal value, not something PHP generates – before you add all the other values from the database. Give it a value like “0” or “NotSelected”, then check for that in your validation routines.Oh, and as an unrelated issue, don’t do this:
You’re opening yourself to SQL injections. If you don’t know what that is, look it up. You should be using prepared/parameterized queries for this. Both the PDO and mysqli extensions have this capability, so you should be using one of those instead of the mysql extension, which has been deprecated (i.e. “this will be removed from the language soon, so stop using it”) in the latest version of PHP.
Update:
Based on the fact that you’re updating the HTML directly using an AJAX request to get new content for the
<select>element, you need to move the<option>item I mentioned to be part of the script you call in your AJAX request.Specifically, you should do it directly before your
foreachloop: