Selecting options from a drop down - javascript

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.

Related

Display number of options selected as soon as they are selected using a multiple choice select2

So, I have this multiple choice select2 that gets its options via database query and I wanted to show in an input the number of options that are selected. However, I wanted to do it as soon as they are selected and I don't know how to do it. For example, if I choose 2 options and then, later, I decide to add one more, I want the input to change to 3 options selected. Any help is appreciated and if you have other ideas like how I can do similar stuff but not like how I described it your help is appreciated too. Thanks
<select name="select_areas_educ_form" id="select_areas_educ_form" class="form-control js-example-tokenizer" multiple="multiple">
<?php foreach ($areas_educacao as $area)
{
echo '<option value="'.$area['id_areaeducacao'].'">'.$area['cod'].' - '.$area['designacao'].'</option>';
}
?>
</select>
So, its much more simple than what I expected, so if anyone need the answer I'll leave it here. You just basically need to add an "onChange" in your select that calls a function. The function will count the number of options selected via jquery and after, change the placeholder of the input. Its very simple and now I can't explain how I didn't think of this before
function opcoes_select_areas_educ_form()
{
var n_opcoes = $("#select_areas_educ_form :selected").length;
document.getElementById("total_areas").placeholder = n_opcoes;
}

Combining javascript and jquery to fill multiple hidden fields - bad idea?

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'));
}});

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

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>

jQuery move specific option top the top of select (drop down)

I am basicly trying to take a specific option from select and move it at the top of the list. What I am trying to do now is this.
$("select[name=list]").find('option[value="car"]').insertBefore($("select[name=list]").find('option:eq(1)'));
and for some reason it executes twice leaving two options at the top
<option value="car">Car</option>
<option value="car">Car</option>
Not sure what am I doing wrong, maybe someone knows?
thank you.
From the jQuery Documentation:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved before the target (not cloned) and a new set consisting of the inserted element is returned.
[..]
If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first, and that new set (the original element plus clones) is returned.
So, there is a clue! My guess is that your selector, is too much embracing, and you are selecting more than one element... Even in another select list in the document.
You may provide a little more HTML code for your example, but let me show how I would do it...
Html
<select id='MyNiceList'>
<option value='my_option_1'>First Option</option>
<option value='my_option_2'>Second Option</option>
<option value='my_option_3'>Third Option</option>
</select>
Js
$('#MyNiceList option[value="my_option_2"]').insertBefore('#MyNiceList option[value="my_option_1"]');
If you pay attention on the selector that I used, I eliminate any possibility of select more than one element, so, the rule on the second part I quoted is obeyed.
Example:
http://jsfiddle.net/sASCg/1/
I hope I helped you on my first Answer! : )
There may be 2 problems
If you insert a new option, then you simply may have 2 options with the same values, as you did not remove it.
The first item is numbered "0" not "1"
http://jsfiddle.net/4kHuA/
var $el = $("select[name=list]").find('option[value="car"]');
$("select[name=list]").find('option[value="car"]').remove();
$("select[name=list]").find('option:eq(0)').before($el);
:eq(1) will select the second element rather than the first element. Other than that, the code you've posted should work fine:
var $select = $("#mySelect");
$mySelect.find('option[value="car"]')
.insertBefore($mySelect.find('option:eq(1)'));
http://jsfiddle.net/B5W4B/
try this
$("select[name=list]").find('option[value="car"]').prependTo($("select[name=list]"));
$("select[name=list]").val('car')

Add and select a "fake" <option> value to a <select>

I need to add a "fake" <option> to a <select>, that will be shown as the selected one, but that can't be selected in the dropdownmenu if the user want to change item.
For example: I have a page that displays 10 fruits. Each fruit has his weight. Using the select, I can filter the fruits by weight:
<select id="fruits">
<option>1 kg</option>
<option>2 kg</option>
<option>3 kg</option>
</select>
if I select the 2nd option (2kg), the page will remove every fruit that has weight != 2kg, and obviously show only those with weight == 2kg.
Now I need to add a "weight range", for example "show fruits whose weight is between 1 and 2 kg". I don't want to add a new option to the , I just want to filter the table showing fruits with weight between the selected range (1 and 2kg), and show this range as the selected value in the select. So my CLOSED dropdown menu will have value = "1-2kg", but if I click on the select, I will not find "1-2kg" option (that's why I wrote "fake" option in the title).
In a nutshell I just want to edit the selected-shown select text, not his options... Something like, using JS
var select = document.getElementById("fruit-select");
select.value = "1-2kg";
obviously this is not working because the option "1-2kg" does not exists..
Is this possible? I hope I was clear enough.. Thanks in advance for any helps, best regards
Solution (not working on Safari...)
Thanks to Ricardo I came to this solution: http://jsfiddle.net/4suwY/5/
HTML:
<select id="asd">
<option>hello</option>
<option>I'M THE CHOSEN ONE</option>
<option>asd</option>
<option>wer</option>
<option>qwe</option>
</select>
JS:
var sel = document.getElementById("asd");
var optnz = sel.getElementsByTagName("option")[1];
sel.value = optnz.value;
optnz.style.display = "none";
the "I'M THE CHOSEN ONE" option is displayed as selected, but is not clickable (not even visible in the options list)
Thanks guys!
I think what you need to do here, is actually have a visible select with all those values, 1kg, 2kg, etc and then you have a hidden select, that will contains those ranges, like 1-2kg, etc (if the ranges are fixed). Everytime you select something from the visible dropdown you change the selected item of the hidden dropdown to the desired range.
It sounds like you want to include a range of weights. You may want to consider a different type of input, such as a range slider. Here's an example from the jQuery UI project. I'm not suggesting you use jQuery UI per se, just showing you one way it can be implemented.
You could use <select multiple> and whenever someone selects more than one option you get the maximum and minimum and show that interval.
try this:
http://jsfiddle.net/4suwY/4/
the only problem I see is losing the value on select click on this function:
$("#asd").mousedown(function () {
$("#asd option[value='1-2kg']").remove().change();
});

Categories