Disable option when clicked in select - javascript

How do I make disable an option when a select is clicked? Here is my code, which does not work. There are no errors in the console.
Here it is:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var numSelect = document.getElementsByClassName("numSelector");
for (var i = 0; i < numSelect.length; i++) {
numSelect[i].innerHTML="<span class='firstSelector'><option>Select Number</option></span><option>1/2</option>";
numSelect[i].onclick = disableSelect;
}
}
function disableSelect() {
for (var a = 0; a < document.getElementsByClassName("firstSelector").length; a++) {
document.getElementsByClassName("firstSelector")[i].innerHTML="<optgroup>Select Number</optgroup>";
}
}
</script>
</head>
<body>
<select class="numSelector"></select>
<select class="numSelector"></select>
</body>
</html>

I'm not sure what you want but here is the ways to disabled dropdown value.
<select id="select1" onclick="disableSelectedItem(this);">
<option>Select Number</option>
<option>1</option>
<option>2</option>
</select>
<select id="select2" onclick="disableFirstItemOnly(this);">
<option>Select Number</option>
<option>1</option>
<option>2</option>
</select>
<script type="text/javascript">
function disableSelectedItem(ddl) {
var value = ddl.options[ddl.selectedIndex].value;
var count = ddl.length;
for (var i = 0; i < count; i++) {
if (ddl.options[i].value == value)
ddl.options[i].disabled = true;
else
ddl.options[i].disabled = false;
}
}
function disableFirstItemOnly(ddl) {
ddl.options[0].disabled = true;
}
</script>

Just use pure HTML
<select required>
<option value="" selected disabled>Select Number</option>
<option>1</option>
<option>etc..</option>
</select>
You could also add the hidden attribute if you don't want it to show up in the dropdown too (at the moment it is visible but disabled)
The required attribute on the <select> means that not choosing a number will prevent submission (though you should still validate serverside)

Related

How to enable button upon dropdown item selection in js?

This snippet displays two select elements, and a submit button. Initially, button is disabled.
Desired behavior: enable submit button when both elements have second option (complete) selected. If either one of the elements has first option (received) selected, disable the button.
Current behavior: button is enabled/disabled regardless of the first select element. Meaning: If I select option received in the first dropdown, and option complete in the second, button will be enabled, instead of disabled.
function enableButton() {
var all_statuses = document.body.querySelectorAll(".selected > .form-control");
var option_two = "complete";
for (var i = 0; i < all_statuses.length; i++) {
console.log(i + " This will work")
if (all_statuses[i].value == option_two) {
document.getElementById("btn_completed").disabled = false;
} else document.getElementById("btn_completed").disabled = true;
}
}
$(document).ready(enableButton);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="selected">
<select class="form-control" id="select_one" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
<select class="form-control" id="select_two" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
</div>
</form>
<button id="btn_completed">Completed</button>
So, the question is: How to enable the button if all select elements have option complete selected, or how to disable the button if at least one select element has option different than complete selected?
working code:
<!DOCTYPE html>
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="selected">
<select class="form-control" id="select_one" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
<select class="form-control" id="select_two" onchange="enableButton()">
<option value="received">received</option>
<option value="complete">complete</option>
</select>
</div>
</form>
<button id="btn_completed" disabled>Completed</button>
</body>
<script>
function enableButton() {
debugger;
var all_statuses = document.body.querySelectorAll(".selected > .form-control");
var option_two = "complete";
var isdisabled = false;
for (var i = 0; i < all_statuses.length; i++) {
console.log(i + " This will work")
if (all_statuses[i].value != option_two) {
isdisabled = true;
break;
}
}
if(isdisabled) {
document.getElementById("btn_completed").disabled = true;
}
else {
document.getElementById("btn_completed").disabled = false;
}
}
$(document).ready(enableButton);
</script>
</html>

Javascript select option application

I am trying to create the select application using Javascipt only. I got to know about this code on internet
<!DOCTYPE html>
<html>
<head>
<title>Select Options</title>
</head>
<body>
<h2>Choose your car</h2>
<hr>
Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Hyundai">Hyundai</option>
<option value="Honda">Honda</option>
<option value="Maruti">Maruti</option>
</select>
<hr>
Choose Car Model
<select id="slct2" ></select>
</body>
<script type="text/javascript">
function populate(s1,s2){
var s1,s2;
s1 = document.getElementById(s1);
s2 = document.getElementById(s2);
if(s1.value=='Hyundai'){
optionArray=['Please Select Car','i10','i20','Verna']
} else
if(s1.value=='Honda'){
optionArray=['Please Select Car','Amaze','Jazz','City']
} else
if(s1.value=='Maruti'){
optionArray=['Please Select Car','Swift','Dezire','Ciaze']
}
for (var i = 0; i < optionArray.length; i++) {
var store = optionArray[i];
var createNewEl = document.createElement('option');
createNewEl.innerHTML = store;
s2.appendChild(createNewEl);
}
}
</script>
</html>
This is the full code I use now to write this apllication but I everytime I select option from car make ** and when I select another option fromcar make**, it does not delete the previous options from car model and the list gets increased so on everytime I select option from car make
First, you need to import jQuery. Paste this between <head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your script is appending new values to end of the select list, so it have to remove all old values.
$("#slct2 option").remove();
I tested it and works fine for me. Here is full, working code.
<!DOCTYPE html>
<html>
<head>
<title>Select Options</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h2>Choose your car</h2>
<hr>
Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Hyundai">Hyundai</option>
<option value="Honda">Honda</option>
<option value="Maruti">Maruti</option>
</select>
<hr>
Choose Car Model
<select id="slct2"></select>
</body>
<script type="text/javascript">
function populate(s1,s2){
var s1,s2;
s1 = document.getElementById(s1);
s2 = document.getElementById(s2);
$("#slct2 option").remove();
if(s1.value=='Hyundai'){
optionArray=['Please Select Car','i10','i20','Verna']
} else
if(s1.value=='Honda'){
optionArray=['Please Select Car','Amaze','Jazz','City']
} else
if(s1.value=='Maruti'){
optionArray=['Please Select Car','Swift','Dezire','Ciaze']
}
for (var i = 0; i < optionArray.length; i++) {
var store = optionArray[i];
var createNewEl = document.createElement('option');
createNewEl.innerHTML = store;
s2.appendChild(createNewEl);
}
}
</script>
</html>
EDIT:
If you don't want to use jQuery just replace this $("#slct2 option").remove(); with this:
while (s2.firstChild) {
s2.removeChild(s2.firstChild);
}
s2.appendChild(createNewEl); adds to a list of whatever
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_node_appendchild

JavaScript - how to remove `options` by its `value`

I have a dropdown menu with products similiar like this
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananes</option>
<option value="3" >Apples</option>
</select>
I need to remove options by its value. How to do that ?
Pure JavaScript please.
EDIT : I know that I need to use element.removeChild(child) method. But how to reference child by its value. Thats my point.
EDIT 2 : I use the script of zdrohn below and it works. Because I have several fruits dropdowns with the same collection I need to iterate trough all dropdowns and delete it from all dropdowns. This is my code now :
<script type='text/javascript'>
var id = 3;
var el= document.getElementsByClassName("fruits");
for (i=0;i<el.length;i++) {
for(var n = 0; n < el[i].length; n++) {
if(el[i][n].value == id) {
el[i][n].remove();
}
}
</script>
Though it works I wonder about that I do not need to use the parent.removeChild() method. How comes ?
P.S. I wonder that peole vote this question down. As the response shows their are several solutions. Though not all are sufficiantly explained.
Here is a snippet to play with.
The code removes the option with value = 3
window.onload = function() {
var optionToDelete = document.querySelector("select.fruits > option[value='3']");
optionToDelete.parentNode.removeChild(optionToDelete);
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
EDIT: Based on the updated question - I have several fruits drop-downs.
We could make use of querySelectorAll to select all matching elements and forEach to apply the desired logic on each element in the selected list.
window.onload = function() {
var optionsToDelete = document.querySelectorAll("select.fruits > option[value='3']");
optionsToDelete.forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
<select class="fruits">
<option value="1">Seville oranges</option>
<option value="2">Burro Bananes</option>
<option value="3">Baldwin Apples</option>
</select>
<select class="fruits">
<option value="1">Bergamot oranges</option>
<option value="2">Red Bananes</option>
<option value="3">Gravenstein Apples</option>
</select>
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananas</option>
<option value="3" >Apples</option>
</select>
<script type='text/javascript'>
var valueToRemove = 1;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
</script>
Edit:
<select class="fruits" >
<option value="1">Oranges</option>
<option value="2">Bananas</option>
<option value="3">Apples</option>
</select>
<br>
<label>Input value to delete</label><input type='text' id='delete_value'>
<button onclick='remove(document.getElementById("delete_value").value)'>Delete</button>
<script type='text/javascript'>
function remove(item) {
var valueToRemove = item;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
}
</script>
You can select the desired option by using document.querySelector() and a selector of this form
A more complete list of selectors can be found here
Example
var element = document.evaluate( '//option[#value="1"]' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
element.parentNode.removeChild(element)

Javascript - added Orange once in fruitslist drop down list

<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected)
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
From above code, first I select Orange from drop down list and click >> button, the Orange value will added in fruitslist drop down list. After that. I select Orange again from drop down list and click >> button, the Orange value will added again in fruitslist drop down list. However, I just want the Orange value added in fruitslist drop down list once. How should I modify it? Can someone help me?
Here is the fix.
<html>
<head>
<script>
function addfruits()
{
for(i = 0; i < document.getElementById("fruits").options.length; i++)
{
if(document.getElementById("fruits").options[i].selected && !isAddedAlready(document.getElementById("fruits").options[i].text))
{
var fruitslist = document.getElementById("fruitslist");
var option = document.createElement("option");
option.text = document.getElementById("fruits").options[i].text;
fruitslist.add(option);
}
}
}
function isAddedAlready(text) {
var fruitslist = document.getElementById("fruitslist");
if(fruitslist.length ==0) return false;
for(var i=0; i<fruitslist.length; i++) {
if(fruitslist.options[i].text === text) return true;
}
return false;
}
</script>
</head>
<body>
<select id="fruits" name="fruits[]" multiple>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
<option value="grape">Grape</option>
</select>
<input type="submit" name="submit" value=">>" onclick="addfruits()" />
<select id="fruitslist" name="fruitslist[]" style="width: 70px;" multiple>
</select>
</body>
</html>
Try changing your addFruits function to the following:
function addfruits()
{
for (var i = 0; i < document.getElementById("fruits").options.length; i++)
{
if (document.getElementById("fruits").options[i].selected)
{
var optionText = document.getElementById("fruits").options[i].text;
var fruitslist = document.getElementById("fruitslist");
var found = false;
//Does the item clicked on already exist in the destination list?
for (var j = 0; j < fruitslist.length; j++) {
if (fruitslist[j].text == optionText) {
found = true;
break;
}
}
//If the item does not exist, add it to the list.
if (!found) {
var option = document.createElement("option");
option.text = optionText;
fruitslist.add(option);
}
}
}
}
The important thing to do here is first check that the fruitslist does not contain the item that was clicked on, hence that additional for-loop.

Get first value of selected items from a multiple select in JavaScript?

I have this code to get the text of the selected option from a in JavaScript:
form_name.select_name.options[form_name.select_name.selectedIndex].text
For example, with
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
When user selects 3, the code would return 3.
My question is, when it's a multiple select such as:
<select multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
How to return the text of the first selected item in JavaScript? For example, when 2 and 3 are selected, it would return 2.
Any help would be appreciated. Thanks!
see below
<html>
<body>
<form name="myForm">
<select name="myOption" multiple>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<BR><BR>
<input type=submit value="Print First" onClick="printMe()">
<input type=submit value="Print All" onClick="printAll()">
</body>
<script>
function printMe() {
alert ("Selected option is " + myForm.myOption.value);
}
function printAll() {
var str="",i;
for (i=0;i<myForm.myOption.options.length;i++) {
if (myForm.myOption.options[i].selected) {
str = str + i + " ";
}
}
alert("Options selected are " + str);
}
</script>
</html>
Hope this is what you want...
I have also provided print all and print first option...
Good Luck
You can do it like so with jQuery:
$('select option:selected').first().text()
Something like this should do the job, and is easily modified to get all values, or a specific index.
var selected = ''; // make this into an array to get all / specific value
var mySelect = form_name.select_name;
while(mySelect.selectedIndex != -1)
{
if(mySelect.selectedIndex != 0)
{
selected = mySelect.options[mySelect.selectedIndex].text; // change this to selected.push(...) for all/specific values
}
}
if (selected.length)
{
// at least one thing was selected, have fun
}
HTML
<select id="your-select" multiple="multiple">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
JavaScript
function getFirstSelected(yourSelectId)
{
var yourSelect = document.getElementById(yourSelectId);
var optionLength = yourSelect.options.length;
for (i = 0; i < optionLength; i++) {
var option = yourSelect.options[i];
if (option.selected) {
return option.value;
}
}
return "";
}
Usage
var firstSelectedOption = getFirstSelected("your-select");
Edit
Just realized that this will give you the first selected value and the function is not needed
var firstSelectedOption = document.getElementById("your-select").value;

Categories

Resources