How to prevent select of new option added to select element? - javascript

I'm adding new options to select tag and I don't want any of them to be selected. I've tried a couple of ways to do it but every time first option is selected. Here's code:
const $selectField = $('.clsname');
const array = ['option1', 'option2', 'option3'];
$selectField.empty();
array.forEach(function(iter, elem) {
$selectField.append(new Option(iter, elem, false, false));
});
$selectField.show();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select hidden class="clsname"></select>
As far as I understand using new Option() with defaultSelected and selected set to false should resolve the problem.
Additionally, I've tried adding something like this after forEach, but it doesn't work either.
$selectField.children("option:selected").prop("selected", false);

You can set the value of the select field to null after you added your options.
$('#mySelect').val(null)
for(var i = 1; i < 5; i++) {
$option = $('<option></option>').text('Option ' + i).val(i);
$('select').append($option);
}
$('select').val(null)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select>

Related

Empty a select if the option was already selected

I have a button that append a row with a select with its options. I gave those select a class (".nuevaDescripcionProducto"). The select has its first option (with the value: "Select an option" or whatever) and the rest of the options are added when I click the button to add the new row. Ok, what I want is: To go back to the first option if I select an option that is already selected in another row. Maybe you could get it more clear by looking a the picture:
This is my code so far:
$(".formularioVenta").on("change", "select.nuevaDescripcionProducto", function() {
var nombreProducto = $(this).val();
var productos = $(".nuevaDescripcionProducto");
for (var i = 0; i < productos.length; i++) {
var x = $(productos[i]).val();
if(nombreProducto == x) {
$(nombreProducto).val();
}
}
})
I think most of what is needed its done. But I would hugely appreciate any help for you. Thanks.

Changing one select option changes many others (JavaScript, JQuery)

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

Create options onClick attribute

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>

How to select an option via jquery

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

how to get the index of value in drop down in javascript?

I have dropdown list on my aspx page. I want to mannually set the selected value which in exist in the dropdown list. this value i am getting in var. i want to set this value as selected value when page get initialize. I want this in javascript. is there any property for dropdown as ddp.SelectedValue='40'..? here I don't know the index of 40 in the list.
selectedIndex is a property of HTMLSelectElement so you can do the following:
<select id="foo"><option>Zero<option>One<option>Two</select>
<script>
document.getElementById('foo').selectedIndex = 1; // Selects option "One"
</script>
And given an OPTION element, you can get its index using the index property:
<select><option>Zero<option id="bar">One<option>Two</select>
<script>
alert(document.getElementById('bar').index); // alerts "1"
</script>
I want to manually set the selected value
Iterate the select's options list to get the option you were interested in and set selected on it:
var options= document.getElementById('ddp').options;
for (var i= 0; n= options.length; i<n; i++) {
if (options[i].value==='40') {
options[i].selected= true;
break;
}
}
this will select the first option with a matching value. If you have more than one option with the same value, or a multiple-select, you may need different logic.
This:
document.getElementById('ddp').value= '40';
is specified by HTML5 to do the same, and has worked in most modern browsers for ages, but still fails in IE, unfortunately (even IE9).
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery 1.6.2.min.js" />
<script language="JavaScript">
$(function() {
quickSelect();
// Handler for .ready() called.
});
function quickSelect() {
var bnd = "40";
if (bnd != "") {
$("#ddp option[value='" + bnd + "']").attr("selected", "selected");
}
}
</script>

Categories

Resources