Passing data from an echo dropdown list using javascript - php

I have this dropdown list that is written using echo
But the select is not as expected
This is my select tag
$output.=" <select name='selectnewauthor' id='selectnewauthor' class='form-control input-lg selectnewauthor'>
<option disabled selected value>Select Author</option> ";
// Getting data from database
$getresourcetype = "Book";
$selectqry = "SELECT author_fullname FROM tbl_author_add WHERE resource_type = ? ORDER BY author_fullname";
$stmt_author = $mysqlconnection->prepare($selectqry);
$stmt_author->bind_param("s",$getresourcetype);
$stmt_author->execute();
$stmt_author->store_result();
$stmt_author->bind_result($author_fullname);
// Writing options
while($stmt_author->fetch()) {
$author_fullname = $author_fullname;
$output .= "<option value='{$author_fullname}'>{$author_fullname}</option>";
}
$output.="</select>

It sounds as though your #selectnewauthor element is dynamically-generated. As such, you need to attach the listener to an element available on page load, and make use of event delegation.
Essentially, instead of $("#selectnewauthor").on('change', function() ...
You're looking for $("document").on("change", "#selectnewauthor", function() ....

Related

How to handle large data in drop down with search box bootstrap

I have one bootstrap drop down with search text box in my web page. I am adding dynamic data into that drop down, but they are large and come from a database. That why it takes long to load. Does anyone know the solution for this problem?
<select data-live-search="true" name="paymentfacility" id="paymentfacility" data-live-search-style="startsWith" class="selectpicker">
<?php
foreach($facilitiesall as $val)
{?>
<option value="<?php echo $val['Facility']['id']; ?>">
<?php echo $val['Facility']['name']; ?>
</option>
<?php } ?>
</select>
If you don't mind to change select field into an input text field, I use this script: it's an autocomplete library that create a list just below the input field. It calls a php file searching what I'm looking for, so you don't load all DB..
https://github.com/jhonis/bootcomplete
JS
$('#inputText').bootcomplete({
url: 'search.php',
method: 'post',
minLength: 2
});
PHP
$txt = $_POST['query'];
$helper = new PDO(CONNECTION_DNS, CONNECTION_USER, CONNECTION_PWD);
$helper->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// YOU MUST HAVE id AND label AS RETURN DATA
$stmt = $helper->prepare('SELECT P.Id as id, P.Code as label FROM TABLE_NAME WHERE Code LIKE :Query');
$stmt->bindValue(':Query', '%'.$txt.'%', PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
print json_encode($results);

html multiple select chosen js submit form

I have this easy select in PHP as echo (using Chosen JS):
echo" <tr>
<th>By country:<br />
<select id=\"firstselect\" name=\"country[]\"
data-placeholder=\"Country...\" multiple class=\"chosen-select\">
<option value=\"dontcare\">dontcare</option>";
foreach ($states as $state) {
echo "<option value=\"" . $state->stat .
"\" >" . $state->stat . "</option>";
}
echo "</select> </th></tr>";
after submitting from and refreshing page values are not as selected.
If i have select with only one choice this is working for me:
var my_val = '<?=$_POST['price']?>';
$("#cenan").val(my_val).trigger("chosen:updated");
but i dont know how to set it as selected in case of array. Can you help me and show me some code? I spent hours and hours without any result.
You are POSTing the form data to the same page and then refreshing it, right?
If so then you can just change your PHP slightly to mark the chosen options as selected when the page refreshes by checking if its value exists in the $_POST['country'] array.
Also, as you are enclosing your echo output in double quotes there is no need to escape variables as PHP will parse them anyway, just use single quotes within the string where you want quotes in your HTML. Much easier on the eye.
foreach ($states as $state) {
if ((!empty($_POST['country'])) && (in_array($state->stat, $_POST['country']))) {
echo "<option value='$state->stat' selected>$state->stat</option>";
} else {
echo "<option value='$state->stat'>$state->stat</option>";
}
}
Lets suppose you have HTML select like following :
<select id='firstselect' multiple class="chosen-select" >
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>
Here is the solution :
<?php
$arr = ['a','b']; // PHP Sample Array
?>
var js_json = '<?php echo json_encode($arr); ?>';
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string); // ['a','b']
// initialize
$("#firstselect").chosen();
// Loop for making HTML <select> options selected.
$.each(js_json_array,function(i,v){
$('#firstselect option[value=' + v + ']').attr('selected', true);
});
//Updating Chosen Dynamically
$("#firstselect").trigger("chosen:updated");

PHP - get data from select box without the value

I'm having a bit of a confusing question but hopefully you'll get what I mean:
In my website I'm trying to implement a select box which is updated based on the value from a previous select box. For that I'm using a javascript that takes the values. For example an option from the select box looks like this:
<option value="22"> Apple </option>
I need the value in order to filter the select boxes but in my PHP script I need to get that 'Apple' text. Is there a way to do that?
Sorry for the noob question but web development is new for me.
Edit:
This is the java script I'm using for filtering the second select box:
$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
If I try to change this 'value' in the filter function to some other attribute it doesn't work for some reason. I don't know JavaScript at all.
Try this
var pName = document.getElementById('selectname');
var name = pName.options[pName.selectedIndex].text;
Send the name value to your php script by hidden form field or ajax request,
It will contain the text of the option
try this
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');
or
this.options[this.selectedIndex].innerHTML
fruits_array.php
<?php
$fruits= array(
22 => 'apple' ,
23 => 'orange'
);
form_handler.php
if( isset($_POST['chosen_fruit']) && (int)$_POST['chosen_fruit'] > 0 ){
include 'fruits_array.php';
echo you chose ' . $fruits[$_POST['chosen_fruit'];
}
pick_your_fruit.php
<form action='form_handler.php' method= POST>
<select name='chosen_fruit'>
<?php
include 'fruits_array.php';
foreach($fruits as $key=$fruit)
echo '<option value=' . $key . '>' . $fruit .'</option>' . PHP_EOL ;
?>
<input type=submit />
</form>
Give this a try. Maintain an array of fruit in one place. Include it where you need it. If necessary that array could be from a database.
Use the array to
generate the form elements
generate the message
But, essentially, transferring the number of the key between the form and the form handler eases the thorny question of validating the incoming data.
DRY. Dont Repeat Yourself. Now if you have 99 fruit, and you add another, you only add it in one place.
(the main thing missing is the handling of a fruit number which does not exist, which probably means someone is tampering with you input form, leave that for another question, eh?)
Try like this
<form method="post" action="getvalue.php">
<select name="fruit">
<option value="">select the option</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Mango</option>
</select>
</form>
<?php
$option = array('1'=>'Apple','2'=>'Banana','3'=>'Mango');
echo $option[$_POST['fruit']];
?>
The Apple is not passed to the server, only your value, in this case 23. You can see that when you change your formular method to GET, it will look like script.php?some_select=23.
Two solutions to solve it:
The first one (the easy one) would be:
<option value="Apple" data-filterid="22"> Apple </option>
And in your js:
var options = $(this).data('options').filter('[data-filterid=' + id + ']');
So you get Apple in your php script instead of 22. You could then filter it in javascript by accessing data-filterid instead of value.
The second solution would be to store an associative dictionary which maps the value to the number, e.g.:
<?php
$mapped = array(22 => "Apple", 23=>"Orange");
$value = $mapped[$_GET['option_name']];

Retrieving value (not display item) of DropDown

I am filling DropDown dynamically using AJAX. The DropDown code looks like this:
<select class="element select medium" id="inDistrict" name="inDistrict" onclick="MakeRequest('divDistrict', 'inDistrict', 'SELECT * FROM districtmaster');" onchange="alert(document.getElementByID('inDistrict').value);">
<option value="Select" selected="Select">Select</option>
</select>
Another file that executes on AJAX request contains following code:
<?php
require("dbconnection.php");
require("dbaccess.php");
$dropdownControlName = $_GET['DropDownControlName'];
$query = $_GET['SqlQuery'];
dbconnection::OpenConnection();
$result = dbaccess::GetRows($query);
?>
<select name="<?php echo $dropdownControlName; ?>">
<option>Select from the list</option>
<?php while($row=mysql_fetch_array($result))
{ ?>
<option value="<?= $row[0] ?>"><?= $row[1] ?></option>
<?php } ?>
</select>
Everything works fine and the DropDowns also get filled, except that I am not following how to pick the value of the Option. In the above code you can see that I am using row[0] as value and row[1] as the display item. I want to pick the row[0] value whenever a user selects any row[1] display item.
In the first code above, you can see that I added an onchange event and there is just an alert box. But it is not executing. How to pick the row[0] value and why onchange event is not firing?
onchange doesn't fire in response to DOM manipulation of the selected value. You can fire it manually with some simple javascript:
var inDistrict = document.getElementById('inDistrict');
if (inDistrict.onchange)
inDistrict.onchange();
If you're using jQuery, it's even easier:
$('#inDistrict').change();
Since it looks like you're replacing the entire dropdownlist with your ajax request, just throw some of that javascript in there to fire the change event when it's done populating, and you should be good to go.
Wrong case usage in your onchage event line:
document.getElementByID
Correct:
document.getElementById
Note that rather than using above; you can alert dropdown value like this too:
onchange="alert(this.value);"
Then for dropdown:
If you add [ ] to the names of elements, they become array eg:
<select name="myselect[]">
Now from php you can access each of its element like this:
(assuming that you post method in the form)
echo $_POST['myselect'][0]; // this prints first item value
echo $_POST['myselect'][1]; // this prints second item value
echo $_POST['myselect'][2]; // this prints third item value
//and so on...

Problem With PHP/HTML Dropdown Box Code (selected value)

I wrote some PHP code that will allow me to create an html dropdown box, and then choose what should be the selected value. The code is:
$role_drop = "<select name='role'>";
$role_drop .= "\r\n<option value='Resident Assistant'>Resident Assistant</option>";
$role_drop .= "\r\n<option value='Community Assistant'>Community Assistant</option>";
$role_drop .= "\r\n<option value='Head RA'>Head RA</option>";
$role_drop .= "\r\n</select>";
$result = mysql_query("SELECT role FROM users");
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$role_drop = str_replace(">$role</option>", "selected=\"\" >$role</option>",$role_drop);
echo $role_drop;
}
}
In reality, this code has a bunch of HTML mixed in, but here is all of the PHP. When I run it, it seems to work. However, let's say the query returned 4 dropdown boxes with roles (from 4 users), and I were to Edit, or select, a new role for the 2nd dropdown box returned (with an UPDATE query), then when the page refreshes, all of the roles including and AFTER the dropdown box I updated will display their selected values as the new one I selected in the 2nd dropdown box.
And it's not that the values in the actual database are wrong, they are just displaying the wrong selected value. Here is the source code for the 3rd dropdown box after I select a new value for the second one:
<select name="role">
<option selected="" value="Resident Assistant">Resident Assistant</option>
<option value="Community Assistant">Community Assistant</option>
<option selected="" value="Head RA">Head RA</option>
</select>
So, it seems its selecting the correct value (Resident Assistant), however its ALSO selecting "Head RA", which is what I changed the prior dropdown box to.
It's very strange, and I have NO idea why this is happening. Any ideas?
Thanks!
It's because you're updating $role_drop each time, so all the previous changes are going to show up in subsequent dropdowns. I'd change the loop to something like this:
if (#mysql_num_rows($result)) {
while ($r=#mysql_fetch_assoc($result)) {
$role = $r["role"];
$temp_role_drop = str_replace(">$role</option>", "selected=\"\">$role</option>", $role_drop);
echo $temp_role_drop;
}
}
That way you're not overwriting your original dropdown markup.
Nuts - forgot to escape my code. I meant, "It's just <OPTION VALUE="foo" SELECTED>".
Dunno if this helps, but according to the HTML spec you shouldn't be passing a value along with the SELECTED attribute of each OPTION. It's just .

Categories