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.
Related
I'm trying to find the best way to make my teachers' lives a little easier.
I've got a select field and list of options generated by a tlist sql query. The select field itself already has a javascript attached to it, which fleshes out other field values (credit values and credit types) elsewhere based on the id of the select option chosen. This is the javascript that works for that purpose:
<script type="text/javascript">
function changeValue(){
var option=document.getElementById('courseno').value;
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
}
</script>
I also need to populate a hidden field that is (and must remain) outside the tlist sql tag that generates the select list.
Here is my sql code:
<select id="courseno" name="course_number" onchange="changeValue();">
<option value="">Select a Course</option>
~[tlist_sql;
SELECT cc.course_number, cc.section_number, c.COURSE_NAME
FROM cc cc
RIGHT JOIN COURSES c ON c.COURSE_NUMBER = cc.course_number
RIGHT JOIN STUDENTS s ON cc.studentid = s.id
WHERE cc.studentid = ~(curstudid)
AND TERMID = ~(curtermid)
AND c.CreditType LIKE 'English%'
AND NOT EXISTS (
SELECT * FROM storedgrades sg
WHERE sg.studentid = ~(curstudid)
AND sg.course_number = c.course_number
)
ORDER BY c.course_name;]
<option name="~(course_no)" value="~(course_no)" id="~(secno)">~(course_no).~(secno) (~(cname))</option>
[/tlist_sql]
</select></td>
</tr>
And just below that is the hidden field I would like to populate:
<td width="25%" class="bold"> </td>
<td><input type="text" id="secnum" name="section_number" value=""> </td>
I gave each of the options the section number as its ID, thinking I could use the ID element of each of those options and some clever jquery to populate the hidden field, but I'm having no luck. I just read on another question that was ably answered by the community that you shouldn't use an option ID tag that begins with a number... so now what can I do?
Could somebody please help me?
Thanks forever,
Schelly
I don't think your problem comes from the ID being a number. We haven't seen what jQuery you've tried, but you most likely don't need jQuery at all. Assuming what you have is working correctly, and the PowerSchool code is putting out elements the way you expect them to be (View Source in your browser to be sure, if this doesn't work), you should be able to grab the ID from the selected option inside your changeValue function, store it in a variable, and push that value into the "secnum" field as follows:
function changeValue(){
var courseDropdown = document.getElementById('courseno');
var selectedElement=courseDropdown.options[courseDropdown.selectedIndex];
var option=selectedElement.value;
var courseNo = selectedElement.getAttribute("id");
if(option=="E100"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngFresh";
}
else if(option=="E200"){
document.getElementById('credval').value="10";
document.getElementById('credtype').value="EngSoph";
}
document.getElementById('secnum').value=courseNo;
}
I changed the way that your "option" variable is being set, but it will work the same way. You might end up wanting to move the last line, where the "secnum" field is being set, or wrap it in an "if", etc.; I don't know your full requirements.
All that said, there would be nothing wrong with using jQuery in this situation, but it's not necessary in this case unless you need extreme backwards-browser compatibility.
Working Example Here
You can use multiple on change events to do whatever you want. On change add a new event and populate the hidden input. You can define custom attributes to any html element with any data that is required to populate the hidden input
<select id="myselect">
<option>Select</option>
<option data-number="1">One</option>
<option data-number="2">Two</option>
<option data-number="3">Three</option>
<option data-number="4">Four</option>
<option data-number="5">Five</option>
</select>
<input type="hidden" id="hiddenInput"/>
$(document).ready(function(){
$('#myselect').on('change', mySelectChange);
function mySelectChange(){
console.log('your standard change value here');
}
$('#myselect').on('change', mySelectChange2);
function mySelectChange2(){
var option = $("#myselect option:selected");
console.log(option.text());
console.log(option.attr('data-number'));
}});
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>
Is it possible to auto submit a select menu when the selection changes without using a button to submit the form. I have four of these on my page and using a button for each uses up too much space. By Select Menu, I mean:
<select name="something" class="something" title="something something">
<option selected="selected">Option One</option>
<option >Option Two</option>
</select>
I would also like to add a confirm popup for the on change event. The following is what I use for buttons but it does not work for the select menu.
onclick="return confirm('do you haz teh codz?');"
Any link to articles tutorials or examples would be greatly appreciated!
Thanks
This is more appropriately tagged 'javascript' since it's javascript that you'll use to do it.
Add an 'onchange' event to the select. In the example below, 'form' should be substituted for your favourite method of targeting the form node.
<select name="something" class="something" title="something something" onchange="form.submit()">
<option selected="selected">Option One</option>
<option >Option Two</option>
</select>
You need a JavaScript solution, not a PHP solution. PHP can only handle form data after it's been sent to the server; i.e., when the form has been submitted.
You can use JavaScript to:
Add an event listener to the <select> to trigger when it changes (onchange).
When the <select> changes, get its current value.
Based on the value, redirect the user (change window.location) to the page you want them to go to.
Edit: I re-read your question and if you are just looking to submit the form when the user changes the <select>, then mwotton's answer is probably the way to go. (Of course, move the JavaScript away from the HTML; it doesn't belong there.)
For your confirmation, you can do something like this:
document.getElementById('my-select').onchange = function(){
return confirm('do you haz teh codz?');
});
(It's always a good idea to keep your JavaScript away from your HTML. So just give your <select> an ID like id="my-select" and you can access it from the JavaScript. You can also use a JavaScript library like jQuery to greatly ease your JavaScript programming.)
Well, you need to know the form name/id or something. Assuming <form id="selectform"> and <select id="selectelement">,
window.onload=function() {
document.getElementById('selectelement').change = function() {
if(confirm('do you haz teh codz?'))
document.getElementById('selectform').submit();
else
return false;
return true;
}
}
The return false/true will determine whether or not to revert the select back to the original option.
Here's a test: http://jsfiddle.net/yrqcj/2/
You can implement the onchange event for select object and inside the function make a reference to the form.submit();
There's a class 'Car' with brand and model as properties. I have a list of items of this class List<Car> myCars. I need to represent 2 dropdowns in a JSP page, one for brand and another for model, that when you select the brand, in the model list only appear the ones from that brand. I don't know how to do this in a dynamic way.
Any suggestion on where to start?
Update
Ok, what I do now is send in the request a list with all the brand names, and a list of the items. The JSP code is like:
<select name="manufacturer" id="id_manufacturer" onchange="return getManufacturer();">
<option value=""></option>
<c:forEach items="${manufacturers}" var="man">
<option value="${man}" >${man}</option>
</c:forEach>
</select>
<select name="model" id="id_model">
<c:forEach items="${mycars}" var="car">
<c:if test="${car.manufacturer eq man_selected}">
<option value="${car.id}">${car.model}</option>
</c:if>
</c:forEach>
</select>
<script>
function getManufacturer()
{
man_selected = document.getElementById('id_manufacturer').value;
}
</script>
How do I do to refresh the 'model' select options according to the selected 'man_selected' ?
There are basically 3 ways to achieve this:
Use JavaScript to submit the form to the server side on change of the dropdown and let the JSP/Servlet load and display the child dropdown accordingly based on the request parameter. Technically the simplest way, but also the least user friendly way. You probably also want to revive all other input values of the form.
Let JSP populate the values in a JavaScript array and use a JavaScript function to load and display the child dropdown. A little bit trickier, certainly if you don't know JavaScript yet, but this is more user friendly. Only caveat is that this is bandwidth and memory inefficient when you have relatively a lot of dropdown items.
Let JavaScript fire an asynchronous HTTP request to the server side and display the child dropdown accordingly. Combines the best of options 1 and 2. Efficient and user friendly.
I've posted an extended answer with code samples here: Populating child dropdownlists in JSP/Servlet.
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.