I'm makin a select with the multiple property enabled.
<select id="lst_prueba1" size="8" multiple>
<option>Alderaan</option>
<option>Corellia</option>
<option>Endor</option>
<option>Kashyyyk</option>
<option>Mustafar</option>
<option>Naboo</option>
<option>Nar Shaddaa</option>
<option>Tatooine</option>
<option>Yavin</option>
</select>
But i want to select the options without the need of pressing the ctrl key.
Is there a way to fake the press using javascript or what could in the onchange event?
The answer provided here didn't work for me:
How to avoid the need for ctrl-click in a multi-select box using Javascript?
Although I'd suggest using checkboxes as mentioned in the comments, this should do the trick. Works in Chrome, Firefox and Edge. Might want to test more depending on your requirements.
<script>
var selected = {};
$("#lst_prueba1").click(function(e) {
var options = this.options;
var option;
var value;
value = $(this).val();
for (var i = 0; i < options.length; i++) {
option = options[i];
if (option.value == value) {
selected[value] = !selected[value];
}
option.selected = !!selected[option.value];
}
});
</script>
Related
I have a lot of select drop downs on a jsp page with a long list of elements. All of these drop downs have the same list of elements. Say I have to get the choice in descending order of preference from the user. I made (many) selects in the following way:
<select id="sel1" class="myClass">
<script>
populate(document.getElementById('sel1'));
</script>
</select>
...
<script>
function populate(op1)
{
var myArray = ["Chinese", "Italian", "Indian", ...//a long list of elements
var sel = op1;
for(var i = 0; i < myArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = myArray[i];
opt.value = myArray[i];
sel.appendChild(opt);
}
}
</script>
I have to create javascript/JQuery code in such a way that if a user selects an option the first select, that option gets disabled/removed in the others, leaving room for changes later. Say, the user's preference order is: Chinese, Indian, Italian... then on selecting Chinese in the first drop down, it gets disabled/removed from the other drop downs. Then, on selecting Indian from the second, it gets disabled/removed from all the others (including the previous one).
Now, if the user decides his order of preference is actually Chinese, Italian, Indian, .. he should be able to change his choice in such a way that the code doesn't break down. Say, we can have a button for reset and it resets all the choices by calling this function:
function resetFunc()
{
var options = document.getElementsByClassName("myClass");
for (var i = 0, l = options.length; i < l; i++)
{
options[i].selectedIndex = "0";
}
}
Any idea how to accomplish this? I need the code to be browser independent (while googling, I read somewhere that IE doesn't support removal of elements from drop down).
EDIT: Here's what I basically want:
http://jsfiddle.net/RaBuQ/1/
However, there's a problem in this. If a user keeps changing his choices, this thing breaks down. I'm able to select multiple choices.
$('select').change(function(){
var v = $(this).val();
$('select option[value="'+$(this).data('old-val')+'"]').prop('disabled', false);
$(this).data('old-val',v);
if(v != "0"){
$('select option[value="'+v+'"]').not(this).prop('disabled',true);
}
});
Here's a fiddle.
If I selected 'Football', 'Golf', 'Tennis', I'd need to select 'No preference' in the third box before I could then select it in one of the other boxes. I think this is acceptable from a UX perspective.
Since you've tagged this jQuery my example below will utilize that:
function populate() {
var myArray = ["Chinese", "Italian", "Indian"];
$('.myClass').each(function() {
var dis = $(this);
dis.append($("<option>").attr("value", "").text("select"));
$.each(myArray, function(i, o) {
dis.append($("<option>").attr("value", o).text(o));
});
});
}
function init() {
$('.myClass').html('').prop('disabled', false);
populate();
}
$(document).on('change', '.myClass', function() {
$('.myClass option[value="' + $(this).val() + '"]:not(:checked)').remove();
$(this).prop('disabled', true);
});
$('#reset').click(init);
init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel1" class="myClass"></select>
<select id="sel2" class="myClass"></select>
<select id="sel3" class="myClass"></select>
<input type="button" id="reset" value="Reset options" />
The following might not be the most efficient solution, but you should try it if there is nothing better: when you change a select, empty all other selects and then fill them with all the other options.
lets say you have 3 selects: sel1, sel2, sel3
in the onchange event, you could call a function "fill_other_sel(number)" where number is the number of the current selector.
This function should delete current options and then populate checking with the previous selectors so that you dont populate with a previously selected value.
function fill_other_sel(number){
var num_selectors = 3;
while (number <= num_selectors){
number++;
$('#sel'+number).options.length=1;
populate('sel'+number, already_selected_values_array);
}
}
also you might add a parameter to your populate function showing which values have already been selected to prevent them from appearing again
I am a beginner to javascript. I am trying to remove few items from the dropdown list based on an option button. In firefox, I see that it is reaching the line to remove the item, but not deleting the item. Can you please help on this?
disable_dropdown_items()
{
var yes = document.getElementById('RadioYes').checked;
var all_opts = document.getElementById('ALL_ITEMS').options;
for (var i = 0; i < document.getElementById('ALL_ITEMS').options.length; i++)
{
if((document.getElementById('ALL_ITEMS').options[i].value == '891') && (yes == true))
{
document.getElementById('ALL_ITEMS').options[i].remove(i);
}
}
}
The line,
document.getElementById('ALL_ITEMS').options[i].remove(i);
works well in IE and chrome and removes the value "891", but firefox doesn't remove. Am I missing anything here?
I have tried:
document.getElementById('ALL_ITEMS').options.remove(i);
without the index for options, still no luck.
A much smaller version would be to do it like this. Use remove() on select.
function disable_dropdown_items() {
var yes = document.getElementById('RadioYes').checked;
var sel = document.getElementById('ALL_ITEMS');
for (var i = 0; i < sel.options.length; i++) {
if ((sel.options[i].value == '891') && (yes == true)) {
sel.remove(i); //Remove from select using index
}
}
}
An example fiddle.
This removes the third option i.e. Rejected
<select id="FilterByTypeTop" class="form-control">
<option value="1">Approved</option>
<option value="2">Not Approved</option>
<option value="3">Rejected</option>
</select>
<script>
$('#FilterByTypeTop').find('option[value="3"]').remove();
</script>
This is the idea: When I click on "word1" (or "word2") the select tag shows me the options. Once I click on one of the options, my script change "word1" (or "word2") whit the option. I can update the options, but once I click on one of them the script always write the last option.
The script write the same onClick attribute for all the options...
I've been searching a lot but I cannot understand why it happen, and how to solve it.
Here is the code:
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
option.onclick = function() {
currentElement.innerHTML = newWord;
};
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
Thanks in advance
You can not bind 'click events' on 'options' property of a 'select box'. You will need to bind a onchange event listner on the 'select element'. Inside the callback function of the change event listner put your code logic for updating word text. As the 'change' event listner is not in the scope of 'updatemyselect' function, you can store the last clicked element in a variable and use the same in the callback function for updating the desired word text. Please refer to the below code which I have edited.
var clickedElement;
function updatemyselect(currentElement, optionsList) {
clickedElement = currentElement;
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
/*option.onclick = function() {
currentElement.innerHTML = newWord;
};*/
mySelect.add(option);
}
}
document.getElementById("mySelect").addEventListener("change", updatePTag);
function updatePTag(){
clickedElement.innerHTML = this.value;
};
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
The reason why you are always getting the last option value is because you are using the newWord variable in your onclick function instead of an actual value, or reference to the currently selected option.
As a result, after you have finished going through the loop, the value of newWord is always equal to the last option text, so, regardless of which option is selected, when you are returning newWord, you will get the same value (i.e., either, "Fish" or "Whale").
Instead, try using currentElement.innerHTML = mySelect.value; in the onclick function.
First you need to set the value attribute on each option.
After you can use the onChange event on Select to display your value.
You can use Jquery to do this, its more easy
jquery select change event get selected option
Thanks to everybody.
I didn't realize that currentElement.innerHTML = newWord; was actually giving the value of the same variable to every onClick attribute.
I finally solved in this way, even if I think the solution of Arun Singh is better.
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
mySelect.onchange= function() {currentElement.innerHTML=mySelect.value;};
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i];
option.text = newWord;
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" value="a">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" value="b">Word2</p>
I have a select form that looks kind of like this:
<select multiple="multiple" id="id_color_id" name="color_id"">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Brown</option>
</select>
What I want to do is select the item above via javascript. This is actually part of a hidden form, so all I'm trying to do is leverage the serialize part of the form. I'm thinking it will just be easier to hack that after the serialize then to add this as well, but I also want to deselect any options that have already been selected.
So two questions:
How to select an option via javascript. All I will know is "Red", "Blue" or "Brown". I also have a look up dictionary that can get me the values as well.
How to deselect all options previous to selecting one of the above.
This is related to: Selecting options in a select via JQuery
Native Javascript:
var textToFind = 'Red';
var dd = document.getElementById('id_color_id');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
break;
}
}
or with jQuery:
$('#id_color_id option:contains('Blue')').prop('selected',true);
with variable:
var blue = "Blue";
$('#id_color_id option:contains(' + blue + ')').prop('selected',true);
And to deselect all selected options:
Native Javascript:
var elements = document.getElementById("id_color_id").options;
for(var i = 0; i < elements.length; i++){
if(elements[i].selected)
elements[i].selected = false;
}
jQuery:
$("#id_color_id option:selected").removeAttr("selected");
To select an option by it's content (considering what you posted is what you have)
$("#id_color_id option:contains('Red')").prop('selected',true);
jsFiddle Demo
You can set the value on the select box using the .val() method. Running this will reset any previously selected values, so you don't need to do anything specific to accomplish that part. You can also use an array to select multiple values, which may be of interest, since you are using a multi select.
$("#id_color_id").val(['1','2']);
Prior to adding this code to my page, if, when executed, I notice that all of my select boxes take 2 clicks of the user to open the drop down menu, the first click seems like it sets focus on it, then the 2nd click finally opens it. If I remove the code, the behaviour changes, and the user is able to open the drop down with all of its menu options in only 1 single click.
I am not sure what to fix or modify, so that it doesn't take 2 clicks, im also using ie. 7 so this would be a work around of css focus. I do not wish to have any jquery please.
Thanks for all your help.
function v9_form() {
//===========================================================================================>>
var x = document.getElementsByTagName('INPUT');
for (var i = 0; i < x.length; i++) {
if (x[i].type == "text" && x[i].readOnly == false) {
if (x[i].id != "date2" && x[i].id != "date3") {
x[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4';};
x[i].onblur = function() { this.style.backgroundColor = '#FFFFFF';};
}
}//end of if
}//end of for
var y = document.getElementsByTagName('SELECT');
for (var i = 0; i < y.length; i++) {
y[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; };
y[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
var z = document.getElementsByTagName('TEXTAREA');
for (var i = 0; i < z.length; i++) {
z[i].onfocus = function() { this.style.backgroundColor = '#FFFFC4'; };
z[i].onblur = function() { this.style.backgroundColor = '#FFFFFF'; };
}
}
This is a known issue with IE. If you change any of the style in the onfocus IE doesn't display the dropdown choices.
A solution is to use the onfocusin event for IE:
y[i].onfocusin = function() { this.style.backgroundColor = '#FFFFC4'; }
From MSDN:
Fires for an element just prior to setting focus on that element.
Another option is to use the :focus CSS selector but you're obviously limited to CSS with that, no complex Javascript logic.
You're a victim of this bug.
It looks like this is some special behavior from IE. There's some code in that answer that provides a possible workaround you can try, but it's pretty heavy for what it does (accommodate people with old versions of IE). I think your best option would be to use a CSS pseudo class (as recommended by the answer above), or to just remove the functionality for those using IE<8.