I'm trying to create a select box that refreshes its options when selected by the user, but I'm encountering a problem that I can't figure ho to solve.
Being still a beginner with jquery I've already asked an advice for the same program: Keeping selected an option in select dropdown with jquery after refresh.
Following the suggestion now it works almost completely, but I'd like the dropdown to behave exactly as a non dynamic one, keeping the selected option when opened, except for having the options list also refreshed: now it “almost” keeps the value selected (it retains it in the dropdown) but resets to the first option when the element lose focus to others in the page and I don't know how to resolve the problem. I tried to pass a variable with ajax to the php page to have it selected on refresh, but it still resets when focus is change.
The JS code:
$(document).ready(function() {
$("#UsersDiv").focusin(function() {
var UsersSelect = $('#UsersList').val();
$.get(
"userlist.php",
{ UserSelect1: UsersSelect },
function(data) {
$('#UsersList').html(data);
}
);
})
$('#UsersList').val(UsersSelect);
});
The html page:
<div name="UsersDiv" id="UsersDiv">
<select name="UsersList" id="UsersList">
<option value="User1">User1</option>
<option value="User2">User2</option>
</select>
</div>
The php file (the “users” array is in place of the sql query, both work properly):
$UserSelect1 = $_GET['UserSelect1'];
$users=array( 'User1','User2','User3','User4','User5');
echo '<select name="UsersList" id="UsersList">';
foreach($users as $list):
echo '<option value="'.$list.'" ';
if ($UserSelect1 == $list) {
echo 'selected=selected';
}
echo '>'.$list.'</option>';
endforeach;
echo '</select>';
Thanks to everyone for the answers.
$("#UsersDiv")
than you assigning this
$select=$(this) // $select is $("#UsersDiv");
and than you are trying to get val from div
UsersSelect = $select.val() // $select.val() is undefined
Related
I have a question on how to populate a drop-down list depending on the value that is selected in another drop-down list.
I'm working with an MVC pattern and when the view loads, it already brings me two variables with the values I need. What are $tipohardware and $tiposoftware.
So I wouldn't need to call a .php file again to get the data, because it's already loaded.
My static drop-down list is:
<select id="producto" class="form-control" required>
<option value="">Seleccionar..</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
</select>
And the dynamic drop-down list I want to populate depending on what is selected in the drop-down list "producto" is:
<select id="tipoproducto" name="tipoproducto" class="form-control">
</select>
I already have two variables that have the data of the tables, "tipo_hardware" and "tipo_software". What are $tipohardware and $tiposoftware.
So, for example, if I select the "Hardware" option in the drop-down list, the second drop-down list should be filled with the data of the variable $tipohardware.
On the other hand, if I select "Software" the drop-down list should be populate with the values of the variable $tiposoftware.
Here's my controller if you needed to.
<?php
namespace app\controllers;
use \app\models\Hardware;
use app\models\Software;
use app\models\TipoHardware;
use app\models\TipoSoftware;
use \Controller;
use \Response;
class IngresarProductoController extends Controller
{
public function actionIndex()
{
$softwares = Software::all();
$hardwares = Hardware::all();
$tiposoftware = TipoSoftware::all();
$tipohardware = TipoHardware::all();
Response::render("ingresarProducto", ["hardwares" => $hardwares,
"softwares" => $softwares, "tipohardware" => $tipohardware,
"tiposoftware" => $tiposoftware]);
}
}
I think I should call a php code in a javascript onchange function like:
$("#producto").on("change",function){
<?php
foreach($tipohardware as $tipohard) {
?>
<option value="<?php echo $tipohard->idtipo_hardware ?>"><?php echo
$tipohard->nombre_tipo_hardwarecol ?></option>
<?php
}
?>
}
});
But I dont know how I can continue with that,
Thanks for the help!
You are mixing frontend script with backend script, which does not work. Backend will build the entire page before the frontend starts doing it's thing. PHP creates the DOM and JavaScript manipulates the DOM after PHP spits it out. That is why your jQuery does not work/update.
For example, if you do this:
$('.button').on('click',function(){
var whatever = <?php echo rand() ?>;
alert('This value is'+whatever);
});
It will run the php first so you will end up with the random number off the bat:
$('.button').on('click',function(){
var whatever = 3241231;
alert('This value is'+whatever);
});
No matter how many times you click the button element, it will always say 3241231 until you reload the page when PHP will run the rand() function at load.
To make it load in real time, you need to create an ajax listener to receive a value from the target, send to the backend PHP, then when that backend page responds, you place the response back into your currently loaded page, altering the DOM.
A simple example would be:
/index.php
<?php
# Create the back end to listen for your front end ajax
if(!empty($_POST['test'])) {
# Do your code here to send back.
$rand = rand();
die('Ajax done! Here is a random number: '.$rand);
}
?>
<!-- CLICK ELEMENT -->
<div id="button">CLICK</div>
<!-- PLACEMENT ELEMENT -->
<div id="response"></div>
<script>
$(function(){
// When you click the div
$('#button').on('click',function(){
// Fire the ajax to the same page (you may want to do a
// different page in production). Note, I am referencing a new instance of
// of index.php in the background and sending $_POST['test'] = true as noted
// in the data section of the ajax below.
$.ajax({
'url': '/index.php',
'type': 'post',
// Send the data from the click or whatever
'data': {
'test':true
},
// If there are no server errors,
'success': function(response){
// place the phrase 'Ajax done! Here is a random number: 123124'
// back into the placement div
$('#response').text(response);
}
});
});
});
</script>
In this example, the random number will change each click of the div. Anyway hope this example was helpful.
i have created the drop down menu using php and i want to use the selected value of menu on url of the current page. How can i do this without redirecting to the next page. the code for creating dropdown menu is:
echo '<select name="Company">';
if($data['count']>0){
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select>";
Hum? Dont know what you exactly want. You want to create a dropdown menu and use the selected value on the current php page?
That wont work. Ill show you how it works:
PHP renders page -> gives it to you.
When you see the page, the php-script is already done. So you have to call your page again and give it the value via $_POST ...
echo <form action="page.php" method="post">
echo '<select name="Company">';
if($data['count']>0) {
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select></form>";
... or $_GET (this only works in combination with JS!) ...
echo "<a href='page.php?company=companyname'>Im a link!</a>"
You need to get drop down value using javascript or JQuery
In Javascript:
<script type="text/javascript">
var myselect=document.getElementById("Company")
for (var i=0; i<myselect.options.length; i++){
if (myselect.options[i].selected==true){
alert("Selected Option's index: "+i)
break
}
}
</script>
In JQuery
$('select[name=Company]').val()
It's not entirely clear how you want to use this value, but you can refer to it on the same page using javascript. Consider the code below, which will update the line "Your company is:" whenever a new option is selected from the dropdown box.
<script type="application/javascript">
function update_box() {
selected_value = document.getElementById('company_dropdown').value;
document.getElementById('your_company').innerText = selected_value;
}
</script>
<form action="page.php" method="post" id="my_form" name="my_form" onchange="update_box()">
<select name="company_dropdown" id="company_dropdown">
<option value='A'>A</option>
<option value='B'>B</option>
<option value='C'>C</option>
</select>
</form>
Your company is: <span id="your_company" name="your_company"></span>
If I am getting it right, you want to use the selected value from dropdown on the same page url via querystring.
You can do that like following:-
echo '<select name="Company" onchange="location.href = location.href+'?var=' + this.value">';
if($data['count']>0){
foreach($data['results'] as $key=>$value){
echo "<option value='".$value['CID']."'>".$value['Name']."</option>";
}
}
echo "</select>";
When you will change the value in dropdown, current page will refresh with the selected option value in querystring. You can use the querystring value as following:-
<?php echo isset($_GET['var']) ? $_GET['var'] : ''; ?>
You can also do it via use of hash value without refreshing the page
When ever you change the dropdown on the onchange event you can write the code
onchange="window.location.hash(this.value);"
it will set a hash value in the url and then you can write a function which will detect the change in the hash value as the page is not refreshing you need to track the change in the hash value and then you can show the selected menu on the basis oh the hash value.
use this to detect the change in the hash value
$(document).ready(function() {
$(window).bind('hashchange', function(e) {
var hashStr = window.location.hash;
hashStr = hashStr.substring(1, hashStr.length);
hashArray = hashStr.split('&');
// here you will get the array of all the parameters you passed in the array
});
});
Question: I have two drop-down boxes. Using jQuery, I want to populate second drop-down box on selection of the first drop-down box (help with my existing code). I have marked the area I need help with in the jQuery code below, plus an explanation of what I want to achieve in "Code help".
I realise this is a VERY frequently requested item on SO and I have seen many comments that this can be done in simple JS, but since there are already other jQuery elements in use on the page (not coded by me) and for simplicity, I want to use JQ.
I am completely new to any jQuery code, I have researched many examples, however I am getting lost in the logic since I am not familiar with JS or JQ coding conventions, so keeping things simple is important so I can understand what is happening within the code (I am not just looking for help to get my code working, but also so I can learn and understand what is happening).
I found pretty much exactly the operation I want to achieve (except for one important point explained in "Code help" below) by following a tutorial here: http://jqueryfordesigners.com/populate-select-boxes/. A sample page showing the operation is here: http://jqueryfordesigners.com/demo/select-boxes.html
Code help: In the tutorial, the second dropdown is populated from the content of static html files in: $article.load('select-boxes-' + categoryName + '.html');
I need the second dropdown to be populated from the JS variable $st_list and the PHP variable $student_block based on the selected value in the first dropdown, as shown in my code below.
Could anyone please help with how to adapt the code to make that happen?
Thank you
My code:
For simplicity, the first dropdown is static with simple integer values, but will be populated from the DB in $test_seq in the working code with integer values same as the example code below (if that matters). Additionally, in a separate PHP process (later) the $test_seq, $student_id and other new variables will be used to send back data to the DB (included for reference only, though not relevant for this request).
select-boxes.php
$sql = "SELECT * FROM TBL_NAME";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$test_seq = $row['SEQ'];
$student_id = $row['st_num'];
$student_name = $row['st_name'];
$student_block .= '<OPTION value="'.$student_id.'">'.$student_id.' - '.$student_name.'</OPTION>';
}
Form:
<form action="select-boxes.php">
<label for="test_day">Test day:</label>
<select name="test_day" id="test_day">
<option selected value=""> </option>
<option value="1">Day 1</option>
<option value="2">Day 2</option>
<option value="3">Day 3</option>
</select>
<input type="submit" id="next" value="next »" />
</form>
jQuery:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function () {
var $test_day = $('#test_day'),
$st_list = null;
$test_day.change(function () {
var test_dayVal = $test_day.val();
if ($st_list == null) {
$st_list = $('<select name="st_name" id="st_name"><?php echo $student_block; ?></select>').appendTo('form');
$next.remove();
$('form').append('<input type="submit" value="process »" />');
}
$st_list.load('#test_dayVal'); //<--I think this is where I need help.. What do I do here?
});
var $next = $('#next');
$next[0].setAttribute('type', 'button');
});
</script>
see my client site first to get an idea.
In above site, i have a giftfinder box in right side. There are 3 select boxes. currently I'm using 3 forms for these 3 select boxes which means each drop down select box is embedded into form. When you select the first drop down select box, it picks one and second select box's value will be determined which value is selected from first select box. So if you choose Man, then all athe related occasions of Man will be dispalyed into seconds drop down select box. Its working fine.
But the problem is it refreshes everytime you select the first drop down box.
I don't want to refresh page. it must select the value and pass the value so seconds select box can determine its related values.
so I'm thinking to us ajax. but no success.
So i included some code for the first drop down select box.
this is mix of html and php and wordpress.
<div class="select-one">
<form id="searrec" method="post" action="">
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
<?php
$results_rec = get_option('current_recipient');
if(isset($_POST['selectionRecipient'])){
$results_rec = $_POST['selectionRecipient'];
update_option('current_recipient', $results_rec);
$results_rec = get_option('current_recipient');
}
?>
<?php
//asort($result_rec);
$t_name_arr = array();
foreach($result_rec as $rec):
$t_id = $rec->term_id;
$term = get_term($t_id , 'category' );
$t_name_arr[] = $term->name;
endforeach;
//print_r($t_name_arr);
rsort($t_name_arr);
foreach ($t_name_arr as $t_name):?><option class="rec_val"<?php if($results_rec==$t_name){ echo 'selected="selected"';}?>value="<?php echo $t_name;?>"><?php echo $t_name;?></option>
<?php endforeach;?>
</select>
<input type="hidden" id="submitrec" value="Search" />
</form> -->
</div>
So I'm am using form method post and using $_POST to retrieve the selected value and pass it to $results_rec variable.
Later in the code, I'm using if.. else to determine if $results_rec =='Man' then display certain items which are related to Man and so forth.
So what I want is not to refresh the page while I select item from first drop down select box.
Please help.
change this:
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
to this:
<select name="selectionRecipient" id="selectionRecipient">
and the jquery:
$("#searrec").submit(function(e) {
e.preventDefault();
// your code
return false;
});
EDITED:
use this to get the selected index (number)
var index = $("#selectionRecipient")[0].selectedIndex;
or value:
var value = $("#selectionRecipient")[0].value;
Then you can call an ajax perhaps: (assuming the other selection box has "id=other_select"
$.ajax({url:"index.php",type:"POST",data {type:"populate",index:2,value:"option1"},dataType:"json",
success: function(data) {
// data (json) returned from server so populate other selection boxes with that..
// in this example 'data' is an array, coming directly from server (see below the .php)
$("#other_select")[0].selectedIndex = 0;
for(var x in data) {
$("#other_select")[0].options[x] = new Option(data[x]);
}
}
})
in your .php i assume you get a list (etc. database) to populate the other selection list (in client). This code could looks like:
if (isset($_POST["type"]) && $_POST["type"]=="populate") {
echo json_encode(array("option1","option2","option3"));
exit(1);
}
$('#searrec').submit(function () {
//do some form submit work here
return false;
});
You'll have to use an AJAX call to populate the other select boxes based on whatever you've selected in the first one without reloading the page.
I suggest you take a look at jQuery's AJAX functionality. Read up on $.ajax and $.post - with them you could submit the value that you've selected in the first listbox to a PHP script and then based on that value return and populate the other select boxes.
Use AJAX to update the other selects without refreshing the page. Use jQuery to make AJAX easy.
This question will help:
Change the selected value of a drop-down list with jQuery
$('#searrec').submit(function(e){
e.preventDefault();
});
You should delete event onchange="this.form.submit(); from combobox
And use ajax with jquery:
$("#searrec").onchange(function() {
$.ajax({
url:"",
success:function(response){
alert("success");
}
});
});
Guys its fixed.
Plz have a look at http://giftideasitems.com/.
See gift finder box and see how it works.
I used iframe and embedded the forms, drop down coding there. thats it.
Even I used onchange="this.form.submit()" and page doesnot referesh, actually page refresh .... but not the main page, only the iframe is refreshing which is fine. this is exactly what i wanted.
<div id="gift-finder">
<div class="gift-finder-form">
<iframe name="inlineframe" src="code.php" frameborder="0"
scrolling="auto" width="200" height="180"
marginwidth="0" marginheight="0" id="gift-iframe">
</iframe>
</div>
This is my iframe code and see src, i used code.php; so all code is in separate place.
Though I had to modify some css, but anyways this is fine.
Thanks everyone who contributed yesterday.
I have a select item, that is filled with a list of files. This list of files is stored in a php variable.
I have another list of files, from another directory, stored in another variable.
I have a dropdown, with 2 options. When I change the dropdown, I want the items in the select to change to the file list associated with the item selected.
For example, my dropdown contains:
Misc Images
People
I have 2 variables, $misc and $people.
When Misc is selected, I want the select to contain all the images listed in $misc, and when the People option is selected I want the select to contain all the options listed in $people.
As far as looping through the php to generate all the items is fine, what I don't understand is how to do the javascript portion?
Thanks, and apologies for poor wording.
Try this code out.
PHP:
<?php
$miscArray = array("misc1", "misc2", "misc3");
$misc = implode(", ", $miscArray);
$peopleArray = array("people1", "people2", "people3");
$people = implode(", ", $peopleArray);
?>
HTML:
<form action="#">
<select id="fileCat">
<option id="misc">Misc</option>
<option id="miscData" style="display:none"><?php echo $misc ?></option>
<option id="people">People</option>
<option id="peopleData" style="display:none"><?php echo $people ?></option>
</select>
<select id="files"></select>
</form>
JS:
init();
function init()
{
addListeners();
}
function addListeners()
{
document.getElementById("fileCat").onchange = fillSelect;
}
function fillSelect()
{
var fileCat = document.getElementById("fileCat");
var imageFiles;
switch(fileCat.options[fileCat.selectedIndex].id)
{
case "misc":
imageFiles = document.getElementById("miscData").innerHTML.split(", ");
break;
case "people":
imageFiles = document.getElementById("peopleData").innerHTML.split(", ");
break;
}
var parent = document.getElementById("files");
parent.innerHTML = "";
if(imageFiles.length)
{
for(var i=0;i<imageFiles.length;i++)
{
var option = document.createElement("option");
//populate option with corresponding image text
option.innerHTML = imageFiles[i];
parent.appendChild(option);
}
}
}
I mocked up some data in PHP and then echoed it into a hidden <option> tag for each category. Then, the data is grabbed using a case/switch depending on the id of the selected option.
I think something like this would work. You would set the onchange attribute of your drop down box to call that function. You will need to have a URL that returns the options you want to use in JSON (selectMenus.php in that example). You'd need two different urls or one that takes a parameter to indicate which option set.
could You provide us some code? It is quite heavy to write it completely of nothing :)
UPDATE:
then how about You try the following (or similar) by using jQuery:
<select id="foo">
<option class="misc">MISC</option>
<option class="misc">MISC2</option>
<option class="people">People1</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$('option.misc').click(function(){
$('#foo').html('<option class="misc">MISC</option>
<option class="misc">MISC2</option>');
});
});
</script>
PHP is server side. JavaScript is client side. You have two options
(1) send an XmlHTTP request back to your server to pull the options and update the select list, or (2) send the values to a hidden field on the initial render of the page and get the values from there.