Reputation: 2093
i have a form that consist of two textfield and one combobox. i want prevent the duplicate entry data from client side. i get combobox data from DB, like:
<select id="line" name="faline" >
<?php
$sql="SELECT `Line_Name` FROM `prod_sch` WHERE `Line_Name` LIKE 'FA %' GROUP BY `Line_Name` ORDER BY `Line_Name`";
if ($sql) {
$res=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
}
while ($dat = mysql_fetch_array($res, MYSQL_NUM)) {
echo "\t\t\t\t\t\t\t\t<option value='".$dat[0]."'>".$dat[0]."</option>\n";
}
?>
</select>
how to combine or modify this code:
<script language="javascript" type="text/javascript">
$(function() {
$("#Button1").click(function(e) {
var itemExists = false;
var txt = $("#Text1").val();
e.preventDefault();
$("#Select1 option").each(function() {
if ($(this).text() == $.trim(txt)) {
itemExists = true;
alert('Item already exists');
}
});
if (!itemExists) {
$("#Select1").append("<option value=\"1\">" + txt + "</option>");
$("#Text1").val('');
}
});
});
</script>
Upvotes: 0
Views: 822
Reputation: 38907
Can't you just use SQL to do this for you? i.e. by using the distinct keyword
$sql="SELECT distinct `Line_Name` FROM `prod_sch` WHERE `Line_Name` LIKE 'FA %' GROUP BY `Line_Name` ORDER BY `Line_Name`";
Sorry I had unique there before I meant distinct.
Upvotes: 0
Reputation: 90022
First, build an array with the Line_Name
s:
<select id="line" name="faline" >
<?php
$sql="SELECT `Line_Name` FROM `prod_sch` WHERE `Line_Name` LIKE 'FA %' GROUP BY `Line_Name` ORDER BY `Line_Name`";
if ($sql) {
$res=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
}
$lineNames = array();
while ($dat = mysql_fetch_array($res, MYSQL_NUM)) {
$lineNames[] = $dat[0];
}
Then call array_unique
:
$lineNames = array_unique($lineNames);
And finally iterate once again:
foreach ($lineNames as $lineName) {
echo "\t\t\t\t\t\t\t\t<option value='".$lineName."'>".$lineName."</option>\n";
}
?>
</select>
Upvotes: 1