PHP Page: Dropdown always selects the first value - javascript

I have multiple dropdown lists on my PHP page and all are created like this:
<?php
//Select values from MySQL Database
$query = "SELECT name FROM Player";
$result = mysql_query($query);
//Show DropDownList
echo '<select name="players" onclick="sortlist(this)">';
while($row = mysql_fetch_assoc( $result ))
{
echo '<option value="'.$row['name'].'">' . $row['name'] . '</option>';
}
echo '</select>';
?>
Now in case you haven't noticed I call a javascript function "sortlist(this)" on every dropdownlist i have. This function just order values alphabetically. You can check the script:
<script>
function sortlist(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
</script>
All my dropdownlists are inside a form tag like this:
<form accept-charset="utf-8" action="" method="post">
The script is running ok, i have the dropdownlist ordered alphabetically, but whenever i select one value, it always shows the first one.

try something like this
<body>
<select id="select_id" >
<option value="B">B</option>
<option value="Z">Z</option>
<option value="C">C</option>
<option value="E">E</option>
<option value="A">A</option>
</select>
</body>
<script type="text/javascript">
function sortlist(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
sortlist(document.getElementById('select_id'));
</script>
REASON: your script always sorting your select on onclick no matter whether you are selecting value it is sorting and reseting your selected value.
so call your script only once for sorting after you have render your select element

Why not just
$query = "SELECT name FROM Player ORDER BY name ASC";
How about this
function sortlist(elem) {
arrTexts = new Array();
for(i=0; i<elem.length; i++) {
arrTexts[i] = elem.options[i].text;
}
arrTexts.sort();
for(i=0; i<elem.length; i++) {
elem.options[i].text = arrTexts[i];
elem.options[i].value = arrTexts[i];
}
}

Related

"options is not defined" When Using Selectize

I'm trying to have some options start as selected when using a selectize multiselect. I'm pulling some info from a database using PHP then converting the info to a JS array. When I try to "initialize the Selectize control" I get an error saying ReferenceError: options is not defined. What can I do to add items to my multiselect?
<?
//Query
$courseQuery = $page->dbf->query("SELECT * FROM courses");
$curCourses = $page->dbf->query("SELECT * FROM recipesToCourse WHERE recipeId = '$recID'");
$course = [];
while($crs = $courseQuery->fetch_object()) {
$course[$crs->id] = $crs->title;
}
$jsCourse = json_encode($course);
$crsList = [];
while($cr = $curCourses->fetch_object()) {
$crsList[] = $cr->courseId;
}
$jsCrsList = json_encode($crsList);
?>
<script>
//Enable multiselect
$('#course').selectize({
maxItems: 10
});
</script>
<select id="course" name="course[]" multiple>
<option value="">-- Select Courses --</option>
<?
foreach($course as $key=>$value) {
?>
<option value="<?=$key?>"><?=$value?></option>
<?
}
?>
</select>
<script>
var courses = '<?echo $jsCourse?>';
courses = JSON.parse(courses);
var crsList = '<?echo $jsCrsList?>';
crsList = JSON.parse(crsList);
// initialize the Selectize control !!My ERROR!!
var $select = $('#course').selectize(options);
// fetch the instance
var selectize = $select[0].selectize;
index = 0;
var select = document.getElementById('course');
for(var i = 1; i < Object.keys(courses).length + 1; i++) {
console.log('checking...');
if(crsList[index] == i) {
console.log('adding');
selectize.addItem(courses[i]);
index++;
}
}
</script>

check duplicate rand function value in database and generate it again

i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.

How can I refresh second select option when first select option is changed?

How can I refresh second select option when first select option is changed?
I am generating the array here for patient_code2:
//GENERATE NUMBERS FOR CYCLE
function patsient(selector) {
var i;
for (i = 1; i <= 99; i++) {
var text = '0' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 2, 2));
}
}
patsient(document.getElementById("patient_code2"));
I am generating the array for patient_code here:
function myFunction(selector) {
var i;
for (i = 1; i <= 999; i++) {
var text = '00' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 3, 3));
}
}
//usage:
myFunction(document.getElementById("patient_code"));
Here I am inserting the last value from database to the field:
//INSERT THE VALUE FROM DATABASE
var tsykkel_id = '<?php foreach ($tsykkel_id as $row){echo $row['patsiendi_tsykkel'];}?>';
$('#patient_code2')[0].options[parseInt(tsykkel_id)].selected = true;
$(document).ready().on('change', '#patient_code2', function () {
var index = $('option:selected', $(this)).index();
$('option', $(this)).each(function (i, x) {
if (i < index) { $(this).remove(); }
});
});
HTML
<select name="patient_code" data-placeholder="" id="patient_code" class="chosen-select form-control" tabindex="2">
</select>
<label class="control-label">Tsükkel:</label>
<select name="patient_code2" data-placeholder="" id="patient_code2" class="chosen-select form-control" tabindex="2">
</select>
So lets say that person chooses 002 from the first then the second should start from 01 again.
try this then. Code is tested.
$(document).ready().on('change','#patient_code2',function(){
var index = $('option:selected',$(this)).index();
$('option',$(this)).each(function(i,x){
if(i<index){$(this).remove();}
});
$('select#patient_code').prop('selectedIndex', 0);
});
fiddle : http://jsfiddle.net/roullie666/69j94ro6/2/
You can just start printing after the match has been found. I am writing both ways since you asked?
For javascript version use roullie's no point duplicating.
<?php
$flag = false;
foreach ($tsykkel_id as $row) {
if ($selected) {
$flag = true;
}
if ($flag) {
$row['patsiendi_tsykkel'];
}
}?>

dynamic select tag in html using javascript, php and json

I want to create dynamic select options in html.
My html looks like
<form id="example-1" name="redirect">
<select id="stateID" name="stateID">
<option value=""> By Collateral Type </option>
<option value="SC">Stories </option>
<option value="TL">Thought </option>
<option value="MI">Insights </option>
/select>
<select id="countyID" name="countyID" onchange="aq()">
<option value="">By Area of Interest </option>
/select>
<select id="townID" name="townID">
<option value="">By Sub-Categoris </option>
...
I want the 2nd and 3rd select box to change as per the first and second selection box.
Sorry if it appears to be a repeated question but I have looked at
Loading values into an HTML select using jQuery/Json
How to create option inside select tag dynamically with ajax response text in php?
and still cannot understand how to do it.
My aq() is:
function aq()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var selectList = document.getElementById('townID');
alert("inside onreadystaechange");
var jsonData = JSON.parse(val);
alert(jsonData);
for (var i in jsonData)
{
var option = document.createElement('option');
option.value = jsonData[i];
option.text = jsonData[i];
selectList.appendChild(option);
alert(option);
}
}
}
xmlhttp.open("GET","datasupplier.php",true);
xmlhttp.send();
}
and my datasupplier.php is:
$stateID = $_GET['stateID'];
$countyID = $_GET['countyID'];
$townID = $_GET['townID'];
$html = $_GET['html'];
$states = array();
$states['SC'] = "Stories";
$states['TL'] = "Leadership";
$states['MI'] = "Insights";
$counties = array();
$counties['SC']['PRACT'] = 'By Practical purposes';
$counties['SC']['SERV'] = 'By Service Area';
$counties['TL']['PRACT'] = 'By Practical purposes';
$counties['TL']['SERV'] = 'By Service Area';
$counties['MI']['PRACT'] = 'By Practical purposes';
$counties['MI']['SERV'] = 'By Service Area';
$towns = array();
$towns['SC']['PRACT']['/index.php?q=sc%3Fpract%3Faut'] = "Automotive";
$towns['SC']['PRACT']['/index.php?q=sc%3Fpract%3Fedu'] = "Education";
$towns['TL']['PRACT']['/index.php?q=tl%3Fpract%3Faut'] = "Automotive";
$towns['TL']['PRACT']['/index.php?q=tl%3Fpract%3Fedu'] = "Education";
$towns['MI']['PRACT']['/index.php?q=mi%3Fpract%3Faut'] = "Automotive";
$towns['MI']['PRACT']['/index.php?q=mi%3Fpract%3Ffam'] = "Business";
$villages = array();
$villages['SC']['PRACT']['HEA']['/index.php?q=node/124'] = 'Apollo Hospitals';
$villages['SC']['PRACT']['PRI']['/index.php?q=node/130'] = 'Fund Raising in Rwanda';
$villages['TL']['PRACT']['AUT']['/index.php?q=node/78'] = 'India-Mecca of Small Car Design';
$villages['TL']['PRACT']['AUT']['/index.php?q=node/141'] = 'Bullish on Automotive Sector';
$villages['MI']['PRACT']['EDU']['/index.php?q=node/116'] = 'Education - TL';
$villages['MI']['PRACT']['HEA']['/index.php?q=node/59'] = 'Indian AWC Market';
if($stateID && !$countyID && !$townID)
{
echo json_encode( $counties[$stateID] );
}
elseif( $stateID && $countyID && !$townID )
{
echo json_encode( $towns[$stateID][$countyID] );
}
elseif( isset($villages[$stateID][$countyID][$townID]) )
{
echo json_encode( $villages[$stateID][$countyID][$townID] );
}
else
{
echo '{}';
}
I don't know how to insert the JSON echoed by my datasupplier.php into my aq() function. What should be the value of the variable "val" used in JSON.parse(val) ?
Thanks sanketh
I added the following in aq() function
var val = xmlhttp.responseText;
var county = document.getElementById("countyID").value;
var town = document.getElementById("townID").value;
var state = document.getElementById("stateID").value;
and edited the following in my aq() function
option.value = i;
var url = "http://localhost/consulting/sites/all/themes/danland/datasupplier.php?stateID=" + state + "&countyID=" + county + "&townID=" + town;
xmlhttp.open("GET",url,true);
and it works perfectly well !

Moved data not sending in php submit

I'm using the following function to move data between two select fields:
<script language="javascript">
function move(tbFrom, tbTo)
{
var arrFrom = new Array(); var arrTo = new Array();
var arrLU = new Array();
var i;
for (i = 0; i < tbTo.options.length; i++)
{
arrLU[tbTo.options[i].text] = tbTo.options[i].value;
arrTo[i] = tbTo.options[i].text;
}
var fLength = 0;
var tLength = arrTo.length;
for(i = 0; i < tbFrom.options.length; i++)
{
arrLU[tbFrom.options[i].text] = tbFrom.options[i].value;
if (tbFrom.options[i].selected && tbFrom.options[i].value != "")
{
arrTo[tLength] = tbFrom.options[i].text;
tLength++;
}
else
{
arrFrom[fLength] = tbFrom.options[i].text;
fLength++;
}
}
tbFrom.length = 0;
tbTo.length = 0;
var ii;
for(ii = 0; ii < arrFrom.length; ii++)
{
var no = new Option();
no.value = arrLU[arrFrom[ii]];
no.text = arrFrom[ii];
tbFrom[ii] = no;
}
for(ii = 0; ii < arrTo.length; ii++)
{
var no = new Option();
no.value = arrLU[arrTo[ii]];
no.text = arrTo[ii];
tbTo[ii] = no;
}
}
</script>
main php page
<?php
mysql_select_db($database_UARData, $UARData);
$query_DistributionGroups = "SELECT distgrp.distgrpnme FROM distgrp";
$DistributionGroups = mysql_query($query_DistributionGroups, $UARData) or die(mysql_error());
$row_DistributionGroups = mysql_fetch_assoc($DistributionGroups);
$totalRows_DistributionGroups = mysql_num_rows($DistributionGroups);
?>
<select name="newusrdgavail" size="10" id="newusrdgavail" style="width:300px">
<?php
do {
?>
<option value="<?php echo $row_DistributionGroups['distgrpnme']?>"><?php echo $row_DistributionGroups['distgrpnme']?></option>
<?php
} while ($row_DistributionGroups = mysql_fetch_assoc($DistributionGroups));
$rows = mysql_num_rows($DistributionGroups);
if($rows > 0) {
mysql_data_seek($DistributionGroups, 0);
$row_DistributionGroups = mysql_fetch_assoc($DistributionGroups);
}
?>
</select>
</label></td>
<td align="center" bgcolor="#CCCCCC"><p>
<input type="button" name="newusrdgadd" id="newusrdgadd" value="Add" onclick="move(newusrdgavail,newusrdgreq)"/>
</p>
<p>
<input type="button" name="newusrdgremove" id="newusrdgremove" value="Remove" onclick="move(newusrdgreq,newusrdgavail)"/>
</p></td>
<td bgcolor="#CCCCCC"><label>
<select name="newusrdgreq" size="10" multiple="multiple" id="newusrdgreq" style="width:300px">
</select>
</label></td>
The move function works well and the moved values show in the correct field on the form. The problem is when I go to php submit:
$newusrdgreq = $_POST['newusrdgreq'];
$email_message .= "Required Email Distribution Groups: ".$newusrdgreq."\n";
I get the Notice: Undefined Index. On this field only. Everything else submits just fine. I know I can use the isset function to avoid empty or null values. However I think the great issue is that the "newusrdgreq" field is not getting the added and removed values properly attached to the field, but I cannot see why. Any help would be appreciated.
problem here that SELECT has only one value, even if you set it multiple - user must select all values manually, so basically all you items in select box - are not sending back to server
to fix this you can have 2 options:
create hidden field were you will duplicate data from select box
before submit - select all values in SELECT

Categories

Resources