I have a page with two drop-down menus. The option selected in the first drop-down menu controls what is displayed in the second.
The code was nice and easy when the drop-down menus were only used once - but I'm looking to repeat each set of drop-down menus four times.
Drop-down menu one is assigned the ID experience[<?php echo $i; ?>][manufacturer]. Drop-down menu two is assigned the ID experience[<?php echo $i; ?>][type].
Essentially, what I've got is:
<select id="experience[1][manufacturer]">...</select>
<select id="experience[2][manufacturer]">...</select>
<select id="experience[3][manufacturer]">...</select>
<select id="experience[4][manufacturer]">...</select>
... followed by:
<select id="experience[1][type]">...</select>
<select id="experience[2][type]">...</select>
<select id="experience[3][type]">...</select>
<select id="experience[4][type]">...</select>
I'm wondering: what's the best way to get the equivalent of <?php echo $i; ?> into the chunk of JavaScript that's used to output the contents of the second drop-down menu? (I know I can't use PHP directly within JavaScript like this - I just left the <?php echo $i; ?> snippets to indicate where I need to output numbers 1, 2, 3, 4 etc.
Thanks for your help!
Code:
<form>
<?php
$i=1;
while($i<=4) {
?>
<select id="experience[<?php echo $i; ?>][manufacturer]">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
<script type='text/javascript'>
$(document).ready(function() {
$("#experience[<?php echo $i; ?>][manufacturer]").change(function() {
$("#experience[<?php echo $i; ?>][type]").load("get_type.php?choice=" + $("#experience[<?php echo $i; ?>][manufacturer]").val());
});
});
</script>
</select>
<?php
$i++;
}
?>
</form>
Revised code:
<form>
<script type='text/javascript'>
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience["+$(this).attr('data-id')+"][type]").load("get_type.php?choice=" + $(this).val());
});
});
</script>
<?php $i=1;
while($i<=4) { ?>
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]">
</select>
<?php
$i++;
}
?>
</form>
You should not need to include the script element in your PHP loop.
Instead, you should add a similar class to all common select elements. Something like class="experience"
Then, with a single script element you can attach events to all the selects:
<script type='text/javascript'>
$(document).ready(function() {
$("select.experience").each(function(i,element){
// here element is the actual item from the selected set, i is its index
$(element).on("change", function() {
$("#experience[" + i + "][type]").load("get_type.php?choice=" + $(element).val());
});
});
});
</script>
Instead of repeating the same javascript code 4 times, put it outside your loop and give classes to your select elements and use them as selectors for your jquery code. You could then add an attribute (named data-id for example) to your select elements containg their ids. It would look something like this
<select id="experience[<?php echo $i; ?>][manufacturer]" class="experienceManufacturer" data-id="<?php echo $i; ?>">
<option value="Ford">Ford</option>
<option value="Honda">Honda</option>
<option value="Mercedes">Mercedes</option>
</select>
<select id="experience[<?php echo $i; ?>][type]"></select>
And your javascript code (outside the loop) would look something like this
$(document).ready(function() {
$(".experienceManufacturer").change(function() {
$("#experience\\["+$(this).attr('data-id')+"\\]\\[type\\]").load("get_type.php?choice=" + $(this).val());
});
});
Note that I used the keyword "this" inside the change event which references to the select element.
Edit: Added backslashes to escape the brackets in the jQuery selector (or else jQuery interprets it as an attribute).
Related
Bit of a strange one, I have a webpage that iterates through a set number of times using while ($i <= 21):. During this iteration I have a dropdown in each which displays some values I pulled from a database, at this point that specific value doesn't matter but the id of each dropdown uses the value of $i. For example:
<select name="dropdown<?php echo $i; ?>" id="dropdown<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
What I am then wanting to do is take the value selected from that dropdown and place in another field that also has the id corresponding to the iteration number, for example:
<textarea name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>"></textarea>
I am using the following code for the jQuery to get the value from the dropdown and put it into the textarea:
<script>
$("#dropdown<?php echo $i ?>").on("change",function(){
//Getting Value
var selValue = $("#dropdown<?php echo $i ?>").val();
//Setting Value
$("#textfield<?php echo $i ?>").val(selValue);
});
</script>
However it doesnt seem to like the use of <?php echo $i ?> part as if i replace that with for example 2 or 3 then it works for that iteration.
I have tried setting the variable in PHP like: $textfield= 'textfield'.$i; and the using this as a whole in jQuery like this: $("#<?php echo $textfield ?>").val(selValue); but it doesnt like that either. Interstining if I change it to $textfield= 'textfield'.'2'; or $textfield= 'textfield2'; it works. Seems like it doesnt like my use of $i, is it the PHP concatenation that it doesnt like?
Anyone experienced this or know of a fix?
Huge fixes are required in your code but will explain the solution in minimal coding.
use array in name,dont use id,use class and data attribute to store the loop value as follows
<select name="dropdown[]" class="dropdown" data-id="<?php echo $i; ?>">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<textarea name="textfield[]" class="textfield<?php echo $i; ?>"></textarea>
now in script single piece of code is enough to perform your operation with the help of class dropdown and dynamic class textfield
<script>
$(".dropdown").on("change",function(){
//Getting Value
var selValue = $(this).val();
var dynamic_id = $(this).data('id');
//Setting Value
$(".textfield"+dynamic_id).val(selValue);
});
</script>
http://jsfiddle.net/hr5aH/
I am jQuery beginner, I have just small problem here..
when I select language from the drop down menu the page refresh, but the drop down menu dose not show me which language I picked up..it's remain Choose Language - however the URL shows me which language I picked up, which is what I want, but not the drop down menu
for example if I choose from the drop down menu English
<script type="text/javascript">
$(document).ready(function(){
$("form").change(function(){
$("select[name='lang']").attr('selected','selected');
$("form").submit();
})
})
</script>
</head>
<body>
<form action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
<select name="lang">
<option value="">Choose Language</option>
<option value="English">English</option>
<option value="Arabic">Arabic</option>
<option value="French">French</option>
</select>
I see the URL http://127.0.0.1/index.php?lang=english
(Which what I want)
but the drop down menu remain on choose language - I just want to the drop down menu shows me the language as well.
If you want to remeber the last language seleted then you need to use a cookie. Use the jquery cookie plugin.
//checks if the cookie has been set
if($.cookie('remember_select') != null) {
// set the option to selected that corresponds to what the cookie is set to
$('.select_class option[value="' + $.cookie('remember_select') + '"]').attr('selected', 'selected');
}
// when a new option is selected this is triggered
$('.select_class').change(function() {
// new cookie is set when the option is changed
$.cookie('remember_select', $('.select_class option:selected').val(), { expires: 90, path: '/'});
});
Here is what your select would look like:
<select class="select_class">
<option value="1">Row 1</option>
<option value="2">Row 2</option>
<option value="3">Row 3</option>
</select>
This needs a bit of php magic coupled with your HTML code:
PHP Code
</head>
<body>
<form action="<?php htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
<select name="lang">
<option value="">Choose Language</option>
<?php foreach(array('English','Arabic','French') as $lang) ?>
<option value="<?php echo $lang; ?>" <?php if ($_GET['lang']==$lang) echo "selected"; ?>><? echo $lang; ?></option>
?>
</select>
Explanation: The php code checks for your url and selects the appropriate option from the select list.
Tip: If you wish to have a cleaner code, place all your language values in an array and loop through it to generate your dropdown menu.
Your js script must be:
$(document).ready(function(){
$("form").change(function(){
$("select[name='lang']").attr('selected','selected');
$("form").submit();
})
var lang=getURLParameter('lang');
if(lang!='null')
$("select[name='lang']").prop('value',lang);
})
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
Link for details of getURLParameter() function: Get URL parameter with jQuery
Try with:
$("select[name='lang']").change(function(){
$("form").submit();
})
and to this you can add:
<option selected disable value="">Choose Language</option>
to prevent errors in you PHP
EDIT:
$_SESSION['language'] = $_GET['lang'] and in your jQuery
var selected_lang = '<?php echo $_SESSION["language"]; ?>';
$("select[name='lang']").val(selected_lang);
I have a dropdown list(in a php file and without form tag)
print "<select id="animal" onchange="getSelectedItem(this.value)">
<option value = "Dog"> Dog </option>
<option value = "Cat"> Cat </option>
</select>";
and a variable $selAnimal
and a javascript function
function getSelectedItem(opt){
//$selAnimal = opt <- how do i do this?
}
As much as possible I wouldn't like the page to reload so I avoid putting this inside a form and submitting as I select. I can't get to make $.post method work. I know for a fact that this cannot be directly done since php is server side and javascript is client side.
I also thought of putting the selected value inside a hidden component(span or something) and get the value from it. But I have no idea how to get it from the component. I've also seen use of AJAX or jquery but I'm not really knowledgeable enough.
I need to save this value to the php variable since I'll be using it as basis for the options in my second dropdown. For example, if I choose Dog, the dropdown list would have dog breeds as options.
I've spent days looking for possible solutions everywhere. Help would be very much appreciated. Thank you!
here is the solution
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#animal').change(function(){
$.post('loadbreeds.php', { animal:$('#animal').val() },
function(data){
$('#breedList').html(data);
});
});
});
</script>
<form method="post" >
<div id="animalList">
<select id="animal" name="animal">
<option value="">--Select--</option>
<?php if (!empty($animals)) { foreach ($animals as $value) { ?>
<option value="<?php echo $value['animalKey']; ?>"><?php echo $value['animalName']; ?></option>
<?php }} ?>
</select>
</div>
<div id="breedList">
<select id="breed" name="breed">
<option value="">--Select--</option>
</select>
</div>
<input type="submit" value="Submit" />
</form>
code for loadbreeds.php
$animalKey = $_POST['animal'];
$breeds = selectByKey($animalKey); // code for selecting breeds
<select id="breed" name="breed">
<option value="">--Select--</option>
<?php if (!empty($breeds)) { foreach ($breeds as $value) { ?>
<option value="<?php echo $value['breedKey']; ?>"><?php echo $value['breedName']; ?></option>
<?php }} ?>
</select>
You cannot have the variable available to the same file since PHP declares all its variables before the JS even starts. You can however simply redirect the user to a new file where the variable is available.
Use something like this:
function getSelectedItem(opt){
location.href = location.href + "?selAnimal=" + opt;
}
In PHP, now you can use the selAnimal variable to display something different, like this:
$selectedAnimal = $_GET["selAnimal"];
if($selectedAnimal == "dog"){
// Whatever you want to do now
}
A better way would be to use POST with forms, but this should work fine for you as well.
Try the following, to rebuild the second dropdown:
http://jsfiddle.net/kAY7M/59/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
print "<script type=\"text/javascript\">var AnimalTypeList = [\"Dog1,Dog2,Dog3,Dog4\",\"Cat1,Cat2,Cat3,Cat4\"];</script>";
<script type="text/javascript">
$("#animal").change(function () {
var sel = $("#animal").prop("selectedIndex") - 1;
var list = AnimalTypeList[sel].split(",");
var Counter = list.length;
$("#type").children().remove();
for (var i = 0; i < Counter; i++) {
$("#type").append("<option value = '" + list[i] + "'> " + list[i] + "</option>");
}
})
</script>
I could do a pure Javascript only version too, but that is a bit more code.
I've been rebuilding my site using CodeIgniter. I am currently making the sign up page and am looking for the most efficient/ strategic way to make a dynamic drop down. This is a social network for the Cystic Fibrosis community. That being said, when registering there is a drop down that ask your relation to CF.
There are two options: 1. I have CF and 2. Someone I know has CF. I am wanting to make it to where when you select 1. a NEW drop down appears with options, and the same for 2.
Here is controller code:
function relation_dropdown($relation="relation", $top_relations=array()) {
$relations = array(
"choose"=>"Choose One",
"I have CF"=>"I have CF",
"Someone I know has CF"
);
$html = "<select name='{$relation}'>";
if(!empty($top_relations)){
foreach($top_relations as $value){
if(array_key_exists($value, $relations)){
$html .="<option value='{$value}'>{$relations[$value]}</option>";
}
}
$html .="<option>----------</option>";
}
foreach($relations as $key => $relation){
$html .="<option value='{$key}'>{$relation}</option>";
}
$html .="</select>";
return $html;
}
and the form on the view:
<div id="signup_form">
<?php
echo validation_errors();
echo form_open('general/send?');
echo "<div class='form_text'>First Name</div>";
echo form_input('first_name');
echo "<div class='form_text'>Last Name</div>";
echo form_input('last_name');
echo "<div class='form_text'>Email</div>";
echo form_input('email');
echo "<div class='form_text'>Confirm Email</div>";
echo form_input('confirm_email');
echo "<div class='form_text'>Password</div>";
echo form_input('password');
echo "<div class='form_text'>Confirm Password</div>";
echo form_input('confirm_password');
echo "<div class='dropdown_structure'>";
echo "<div class='form_text'>";
echo "Location";
echo "</div>";
echo country_dropdown('country');
echo "</div>";
echo "<div class='dropdown_structure'>";
echo "<div class='form_text'>";
echo "Relation To CF";
echo "</div>";
echo relation_dropdown('relation');
echo "</div>";
echo form_close();
?>
</div>
So my question is what is the best way to do this?
thanks in advance
If you have multiple decisions the user must make, I would have a lookup table in a database to start, with a parent-child relationship among the select options. That way, you could use ajax with jquery, and select the children of the currently selected option.
So, basically, I would do this:
User selects "I Have CF"
Ajax goes and gets all the children of the "I Have CF" option from the database table
jQuery gets those options back, and displays the next drop down.
Rinse and repeat until all decisions are made
You can:
Use ajax to get the options when the first dropdown is changed
This requires a second controller that return the data for the second dropdown (in either HTML, JSON, or whatever you want) and JQuery/JS to tie it all together. This is good if there are lots of options and you don't want to have to load them all up front.
Output all of the options with the initial page load
This allows you to just use JQuery/JS to update the second dropdown. The data in the intial page load can either be a Javascript array or hidden HTML elements. This is easy, but increases the initial download, especially if you have lots of options.
Here is an example of having the options in the initial page load as hidden HTML elements:
<select id="dropdown1" name="dropdown1">
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>
<select id="dropdown2" name="dropdown2" disabled="disabled">
<option value="">select an option</option>
</select>
<select id="dropdown2a" name="dropdown2a" style="display: none">
<option value="a">option a</option>
<option value="b">option b</option>
<option value="c">option c</option>
</select>
<select id="dropdown2b" name="dropdown2b" style="display: none">
<option value="i">option i</option>
<option value="ii">option ii</option>
</select>
<select id="dropdown2c" name="dropdown2c" style="display: none">
<option value="x">option x</option>
<option value="y">option y</option>
</select>
<script type="text/javascript">
$(function()
{
$('#dropdown1').change(function(){
var val = ('#dropdown1').val();
if (val == 1)
{
$('#dropdown2').html($('#dropdown2a').html());
}
else if (val == 2)
{
$('#dropdown2').html($('#dropdown2b').html());
}
else if (val == 3)
{
$('#dropdown2').html($('#dropdown2c').html());
}
$('#dropdown2').removeAttr("disabled");
});
});
</script>
I Have a select list, each option contains a category ($k[3]) in its id.
<select name="page_from_link" class="my_select_list" >
<OPTION VALUE="" >With:</OPTION>
<?php foreach($pages_created as $k) {
$i=0; ?>
<OPTION id="<?php $i."-".$k[3]; ?>" class="pages_created" VALUE="<?php echo $k[0]; ?>" ><?php echo $k[1]; ?></OPTION>
<?php } ?>
</select>
I have another select list with all options hidden depending on the precedent select category :
AS:
$v) { ?>
" >
my jquery script doesn't work, how would you have done that ?
$(document).ready(function(){
$(".my_select_list").change(function(){
var array = $(this).find('option:selected').attr('id').split('-');
var cat = array[1];
alert("cat");
$("#cat_"+cat).show();
$(".pages_created_option:not(#cat_"+cat).hide();
return false;
});
});
$(this > option).attr(... => $(this).find('option:selected').attr (...
alert("cat"); => alert(cat);
$("#cat_"+cat+")").show(); => $("#cat_"+cat).show();
you should consider using firebug or chrome internal development tools (on F12).
on a side note, you might like to use optgroup instead of a dummy option:
<select name="page_from_link" class="my_select_list" >
<OPTGROUP label="With:">
<?php foreach($pages_created as $k) {
$i=0; ?>
<OPTION id="<?php $i."-".$k[3]; ?>" class="pages_created" VALUE="<?php echo $k[0]; ?>" ><?php echo $k[1]; ?></OPTION>
<?php } ?>
</OPTGROUP>
</select>
you could use either a php script, or a js script with the data encoded, holding the innerHTML and that changes the innerHTML of the parent object (such as a div) depending on what you selected in the previous select box.
add this in the head for javascript
function showsel()
{if(document.getElementById('parentid').value=="id of the option that will triger the shild ")
{document.getElementById('shild id').style.display="inline";}
else {document.getElementById('shild id').style.display="none";}
}
Then add for the shild
div id="shild id" style="display:none"
and to the parent
div id="parent id" onchange"showsel()"