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>
Related
I am creating a listbox box with 2 optional values Ja(Yes) or Nein(No). Additional iam using a default Value which is taken from the database for the record.
Here the code:
<td>
<select name="s_BKAG">
<option selected="selected" ><?php $bkagbruggwert = ''.$abc['BKAG (Brugg)']. ''; if ($bkagbruggwert==1){echo 'Ja';} else {echo 'Nein';};?></option>
<option value="1">Ja</option>
<option value="0">Nein</option>
</select>
</td>
Problem: Now i want that when Yes or No is selected, then id should take their value and if nothing is selected it should take the Value of the preselected default value. But the problem is the variable which i have created has the value "Ja", it does not matter what I'am changing on the formular. I do not know if I overseeing something.
The code of variable defining is here:
$BKAG_Brugg = $_POST['s_BKAG'];
I could take $BKAG_Brugg and define a new variable which i am asking, if the $BKAG_Brugg is "Ja" then set 1 to the new variable. But it's my first project on php and i do not really now how to do the query for the new variable.
Can someone help me with that? i would be thankful for every little help.
regards:
okanog
I think you can do like this:
<select name="s_BKAG">
<option></option>
<?php $bkagbruggwert = $abc['BKAG (Brugg)']; ?>
<option value="1" <?php if($bkagbruggwert == 1) { echo 'selected'; } ?>>Ja</option>
<option value="0" <?php if($bkagbruggwert == 0) { echo 'selected'; } ?>>Nein</option>
</select>
This way, if there is no preselected value, the empty option will be displayed; if there is a preselected value and this value is same as value of any option, it will be selected.
I hope this works for you.
You can do it this way,
Assign the default value to the hidden element
In case, if the user doesn't select one option, then assign the default value from the hidden element
function fetchValue()
{
var selectedValue = document.getElementById("s_BKAG").value;
if(selectedValue == "")
{
selectedValue = document.getElementById("default-value").value;
}
console.log("The selected value is: " + selectedValue);
}
<select id="s_BKAG" name="s_BKAG">
<option value="">None</option>
<option value="1">Ja</option>
<option value="0">Nein</option>
</select>
<input id="default-value" type="hidden" value="<?php echo $abc['BKAG (Brugg)'] ?>" />
<input type="button" value = "Fetch Value" onclick="fetchValue()" />
<label>Country <font color="8AC007">*</font> </label></td>
<td><select name="country" onchange="print_state('state',this.selectedIndex);" id="country"<?php
$sel_country = $myform->value('country');
if (isset($sel_country)) echo 'selected="selected"'; ?> />
<option value="<?php $myform->value("country"); ?>"/>Select country</option>
</select><br><?php $sel_country.'sample' ?>
<span class="error"><?php echo $myform->error("country"); ?></span>
I want to get hold with the country selected value when I submit form, instead filling the form from starting again. Here is the code Iam trying to get countries from a js file.
Apperciate your help
HTTP is stateless, so you have to put a little effort on keeping data around when moving from page to page. Seeing this as being a form with inputs (select in this case), you can use $_POST to get hold of your submitted value in the next page.
In this case you'd use $_POST['country']. If you want to keep the current form filled next time the page refreshes, make the form submit to the current page, then you'll have access to that value in $_POST.
Other ways to keep data around:
Sessions
Cookies
Database storage
But this require a little bit of additional coding in PHP.
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country"/>
<option <?php if($youroldval==$myform->value('country')){ echo 'selected="selected"'; } ?> value="<?php echo $myform->value("country"); ?>"/><?php echo $myform->value("country"); ?></option>
</select>
You must store your old value of form
Ok, if I am right you should do it as follows.
If you are posting your page to the server. You have the selected value. You store this and return this page. In that case I added bollow code and added $isSelected to the code. Normally it emtpy, but if the value is equal to the selected then you set selected='selected'.
<select name="country">
<?php
$countryList = array("USA", "UK", "France", "Germany", "India", "Netherlands");
$isSelected = "";
foreach($countryList as $country)
{
if($_POST["country"] == $country)
{
$isSelected = "selected='selected'";
}
echo "<option value='" + $country + "' " + $isSelected + ">" + $country + "</option>";
?>
</select>
If you are using jquery / Ajax, you have the selected value which stays selected because the page wont refresh :-) However, you can get the value by using javascript and get value from selectbox.
------ Edit
Mmm ok, I was in the illusion you had your array in php. However you get your collection from javascript. In that case you will get this as solution:
<script type="text/javascript">
var selectedCountry = "<?php echo $myform->value("country"); ?>";
</script>
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country">
/* This is generated by javascript */
</select>
Your javascript function will be like this:
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selectedCountry == country_arr[i])
{
option_str.options[option_str.length].setAttribute("selected", "selected");
}
}
}
----- Edit 2:
http://jsfiddle.net/eLProva/5mU76/ with filling and selecting the country
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).
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.
With below code I select a quantity, then I check the Item whose quantity I have selected then I click the add button to submit the form.
<form name="addtocart" method="post" action="checkbox.php">
//foreach loop below loops through array of items fetched from the db
<?php foreach($result2 as $row) { ?>
<select name="qty">
<?php for ($i=0; $i < $row['prd_quantity'] + 1 ; $i++) { ?>
<option value = "<?php echo $i; ?>" ><?php echo $i; ?></option>;
<?php }?>
</select>
<input type="checkbox" name="checkitem[]" id="addtocart" value="<?php echo $row['prd_id'] ?>" optional /></p>
<?php } ?>
enter code here
<input type="submit" value="Make Order"/>
</form>
After selecting, say 8 on the select element, $ordqty below still outputs 0. I am thinking its something to do with the loop and $_POST superglobal but
checkitems[ ]
works. Help would be appreciated. Thanks.
$ordqty = $_POST['qty'];
//$ordqty returns 0.
Below is the HTML Generated for the first item whose $row['prd_quantity'] = 8 :
<select name = "qty">
<option value="0">0</option>
;
<option value="1">1</option>
;
<option value="2">2</option>
;
<option value="3">3</option>
;
<option value="4">4</option>
;
<option value="5">5</option>
;
<option value="6">6</option>
;
<option value="7">7</option>
;
<option value="8">8</option>
;
</select>
Seems to me like if there's more than a single row returned by your DB then there will be multiple select elements within your response, all named qty. This could explain why the form isn't posting the correct value. Have you checked that?
Try something along the lines of:
<select name="qty[<?php echo $row['prd_id']; ?>]">
<?php for ($i=0; $i < $row['prd_quantity'] + 1 ; $i++) { ?>
<option value = "<?php echo $i; ?>" ><?php echo $i; ?></option>;
<?php }?>
</select>
This will post an array of selections keyed by product IDs.
Update
Thank you for the idea of indexing the array of selected items' quantities using product IDs worked.
And to access the elements of the qty[ ] array , I know this could be better, but I did:
//Array below holds the values of the quantities entered
$new_ord_qty = $_POST['qty'];
//Array below holds product ids -- in the HTML code -- prodid is the name of a hidden inputfield inside the foreach loop whose value i have set to $row['prd_id']
$prod_id_array = $_POST['prodid'];
for($i=0; $i<count($checked_items_array);$i++) {
for ($i=0; $i < count($new_ord_qty); $i++) {
//Array below holds the values of the quantities entered with the prod_id_array elements as //the indices
$ord_qty = $new_ord_qty[$prod_id_array[$i]];
// Here echo will output an array of the quantities entered for the checked items
echo $ord_qty;
}
}
Thanks folks.
I think the issue might be that you are passing the checkbox as an array checkitems[] but you are passing the quantity as a single qty might be worth changing the name of the quantity select to qty[]
Obviously you may also need to update your code to handle the qty being an array and match it to the checkitem value.
The problem should be that you have multiple selects with the same name, I assume that the POST variable will show the last one, which is still set to 0. You might use an id postfix, like, qty_0, qty_1 for each dropdown list.
Could you post the HTML code the segment generates? That might helpful.