How to have a drop-down menu that updates itself after submission? - javascript

Here is my drop-down form. I have searched and still do not understand how to have a selected drop-down value remain after the cart is updated. Maybe it is because of the PHP in the name value? I would greatly appreciate any help. I believe this has to be done with javascript, but again I am unsure.
<select id="quantity" name='.$cart[$x]['ASIN'].'>
<option value=1>1</option>;
<option value=2>2</option>;
<option value=3>3</option>;
</select></td>';
Thanks,
Eric

As I understand it, you want the selected item to remain selected after the form is submitted and the page is refreshed... in this case you will need to do something like this:
<select name='mySelect'>
<option value=1 <?=(isset($_POST['mySelect'])&&$_POST['mySelect']==1?'selected':'')?>>1</option>
Basically for each option you need to check if that select has a value, and if that value matches the current option ... if so, echo 'selected' which will set that option to the current displayed choice.
Unless, you have a situation where you're on like a profile page or something, and you want the user to be able to see his current setting, and still be able to change it... then you would need to do something similar but replace $_POST['mySelect'] with the data from the database. So if you have an array of user data, $data, and one of those values is 'quantity' that corresponds with the select, then you would need:
<option value=1 <?=($data['quantity']==1?'selected':'')?>>1</option>

Related

How to set a select option dropdown from localStorage

I have a select option dropdown with a default set that has no value, is disabled, and set as selected. The first time a person runs through the form they pick their selection. The selection is saved to local storage. They run through some questions then are reverted back to that initial form where all types input values set to hold the values saved in localStorage. However, I am having trouble setting the select option dropdown to the value that was saved in the local storage. I also have a button that allows the person to clear the session, thus reseting all the form fields. Below is a sample of the code.
HTML:
<select id="gender" name="gender" required="" aria-required="true">
<option value="" disabled selected>Choose your gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<label>Gender</label>
JavaScript to save selected value to local storage:
var gender = document.getElementById("gender");
localStorage.setItem('gender', gender.options[gender.selectedIndex].value);
JavaScript to set select option dropdown once the value is already saved, where the problem is:
document.getElementById("gender").value = localStorage.getItem('gender');
// Or this one, neither seem to work
$("#gender").val(localStorage.getItem("gender"));
Any ideas on how I can solve this?
**Update: After looking a little further, I just found that it is changing the value of the first option from "" to "Male" instead of selecting the option that has Male set as its value. But I still can't figure out how to fix it.

Manipulating select option selected value in DOM several times without page load

I am in an unfortunate position where I need to be able to copy entire blocks of HTML without the page reloading using javascript/jquery, including inputs and selects.
I have most of it working, but I'm stumped on the selects. In order for it to "copy" properly so the copy displays the selected value of where its copying from, I need to explicitly set the attribute "selected" on the copy from select. The problem is, if I change the value on a select that I will copy from, the previous selections "selected" attribute remains, and I don't know how to get rid of it.
Here is a link to the fiddle and below is the basic test to show you what I mean: fiddle. You'll need to inspect element on the select list and show all of the option tags.
Make a selection
Hit the Enter button
Observe the selected attribute go on the option you chose
Choose a different option
Hit the enter button
Observe that now two options have the selected attribute. At this point I need to get rid of the selected attribute from the step 3 observation
HTML:
<table>
<tr>
<td>
<select>
<option value="">Select One</option>
<option value="test1">Test1</option>
<option value="test2">Test2</option>
<option value="test3">Test3</option>
<option value="test4">Test4</option>
</select>
</td>
</tr>
</table>
<button onclick="enterTest()">Enter</button>
Javascript
function enterTest(){
var $selectedOption = $("select").children(":selected");
$selectedOption.attr("selected","selected");
}
No need to deal with options and selected attribute.
If the values are unique,
var $select = $("select");
function enterTest(){
$select.clone().val($select.val()).appendTo('body');
}
Demo
Otherwise, use selectedIndex:
$select.clone().prop('selectedIndex', $select.prop('selectedIndex'))
Demo

Drop Down Option Value resets are page reloading

Hy Stackoverflow members.
Here is my little problem, I have a page that I'm saving some values in sessions. For example I have a sorting drop down option for my users.
<form id="formName" action="Index.php" method="POST">
<select name="Sort_Ads" id="Sort_Ads" onchange="document.getElementById('formName').submit()">
<option>Most Recent Ads</option>
<option>Price: Low to High</option>
<option>Price: High to Low</option>
</select>
</form>
Once a option is selected the page reloads and the users can see the ads by the selected sorting option.Some php code is working behind it. But with javascript I want to create a function which will set the selected option by users after page reloads. please my javascript skills aren't good enough. Could someone do it I'll be really thank full!
You will need to cookie the user to maintain state or use php to parse the selected option as selected. HTTP is state-less.
ie, you can do something like:
var myselection;
$("#Sort_Ads").change(function(){
myselection = $("Sort_Ads option:selected").val();
});
call and have a set and read cookie function passing in the myselection var. w3 schools has a good example of this.
Or, what i would say is the better method, you can use php to print the form, but you'll need to give your options values, and then iterate through each value and if value == selected, change
<option value='x'>
to
<option value='x' selected>
when printing the form.

jQuery val() on dropdown returns value "Array"

I'm stumped. I have a dropdown menu where a user selects an item.
<select name="rep-name" type="text" id="rep-name" size="" value="" >
<option value></option>
<option value="alex">alex</option>
<option value="ben">ben</option>
...
</select>
The value is then retrieved...
$('#rep-name').val()
and sent to a database.
Usually it works fine but in some cases, it sends the value 'Array' to the database. Interestingly, in those cases, the serialize function on the form still gets the correct value of the item. So in other words:
$('#run-pma-form').serialize() // works fine
$('#rep-name').val() // fails
It works fine in ~95% of cases and unfortunately, I don't have info on what browsers are being used, etc when it incorrectly returns 'array.' I'm just wondering if anyone has run into this issue or has any clue why it might be happening.
$("#rep-name")[n].val() will get you the value of any given option, but it's not correct to think of a select menu as having a value—what you want is the value of the currently selected option.
http://api.jquery.com/selected-selector/
$("#rep-name option:selected").val() should work.

Selecting options from a drop down

I'm building a recipe-finder for a new food blog. The design I have basically involves the user selecting ingredients, one at a time, from a drop down <select>, the option disappearing from the list (so they can't select it again) and appearing on another HTML list with a link to remove it from the list. Once they're done, they click a button and that takes them through to a results page.
Here's the select markup as generated by the PHP:
<select>
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
It's not drastically complex but it does raise a few questions on how I'm going to do some of these things. I'm using jquery.
I need to store the selected items in memory so I know what to send to the search page when they've done selecting items. What's the best way of doing that in your opinion as each item has two values (its "real" value and its database-value)?
How do I make "Please select" the selected option after they've selected something (preferable without triggering the onchange event)?
Once I've stored it in memory and added it to the displayed list of things they're searching for, how do I delete that item from the available items? Can I just "hide" or disable it (safely)?
If in #3 I have to delete it from the DOM, when I add it again, can I sort the list (based on either value) and keep the please-select option at the top?
1.) You can append hidden form elements to the page whose value is the value of the selected option.
2.)
jQuery("#select-list")[0].options[0].selected = true // assuming it's the first item
3.) I would remove the element from the DOM using jQuery("#select-list option:selected").remove()
4.) You can use before(). jQuery(your_default_option).before("#select-list option:first");
You can store the 'two values' in a hidden form field as an object in JSON notation. This will make it easy to modify in jQuery as the user interacts with the page.
You will need to use a combination of the onchange, keyup and keydown event to capture possible changes to the form so that you can re-select the 'Please Select' option.
You will need to remove the option from the dom and re-add it later. You can easily do this through jquery through something like this:
$("select option:selected").remove();
You can write a sorting function for the options starting with index 1, and keep the 'Please Select' as the first option.
1)
Basic idea, you need to check to make sure the first is not picked
var selections = [];
var mySel = document.getElementById("mySelectId");
var ind = mySel.selectedIndex;
selections.push( mySel.options[ind].value ); //add to a list for you to remember
mySel.options[ind] = null; //remove
2)
mySel.selectedIndex = 0;
3)
See #1
4) Yes you can add it anywhere you want by using insertBefore
Example here: http://www.pascarello.com/lessons/forms/moveSelectOptions.html
Will leave this answer here but I think I failed to read your whole post, so it might not help much.
You need to give your select a id like this:
<select id="MySelect">
<option value="">Please select</option>
<option value="beef-mince">Beef mince</option>
<option value="carrots">Carrots</option>
...
</select>
And to get it is just something like this:
<?php
$value = $_REQUEST["MySelect"];
echo $value;
?>
Code is not tested and $_REQUEST can be replaced by $_GET or $_POST regarding what you have specified as action on your form. $_REQUEST will eat it all though.

Categories