How to enable button upon dropdown item selection in js? - javascript

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>

Related

Loop through select from fields and validate

Im trying to loop through multiple text and select boxes in a form and validate they have been answered.
I have used the following code to loop through the text boxes but can work out how to do something similar on the select boxes.
<form name="Form1"></form>
<label>Question 1</lable>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>';
</form>
<script>
(function (){
$('#Go').on('click', function(e){
e.preventDefault();
genericValidationText('form[name="Form1"]');
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationText (formName) {
document.forms.noValidate = true;
var notValid;
// PERFORM GENERIC CHECKS
// INPUT form fields
$(formName + ' *').filter(':input').each(function(){
var formElement = formName + ' input[name="'+ (this.name) + '"]' ;
performValidation(formElement);
});
function performValidation(formElement){
if ($(formElement).hasClass('required')) {
notValid = false;
if (!($.trim($(formElement).val()))){
notValid = true;
};
if (notValid === true) {
showErrorMessage(formElement);
};
};
}
}
function genericValidationSelect (formName) {
?????
}
</script>
You can validate <select> elements in much that same way as <input /> elements, by examining the result of the select element's .val().
Something to keep in mind is that the <select> will have a value by default (that corresponds to the <option> that is initially visible to the user in the browser). This will in effect cause validation on the <select> to pass (even when a selection option hasn't been explicitly picked by the user).
To address this, consider adding a default <option> to the <select> like this:
<option selected disabled>Please select something</option>
Adding this option means that validation on the <select> will fail until the user has actually engaged with the <select> by picking a valid option (after which, validation on the select will pass):
(function() {
/* Consider using submit on form, rather than a click event
listener on the Go button */
$('form[name="Form1"]').submit(function(e) {
e.preventDefault();
/* Exclude call to genericValidationText() for
this snippet to simplify it
genericValidationText('form[name="Form1"]');
*/
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationSelect(formName) {
let notValid = false;
/* Iterate each select in the form */
$('select', formName).each(function() {
/* Check value in similar way. If null value,
then consider the select invalid */
var selectedOption = $(this).val();
if (selectedOption === null) {
notValid = true;
}
});
if(notValid) {
alert('Please select an option');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Fixed : remove closing form tag -->
<form name="Form1">
<!-- Fixed : typo -->
<label>Question 1</label>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<!-- Added default "no value option" to demonstrate validation -->
<option selected disabled>Please select something</option>
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>
</form>
Hope this helps!
The following should work:
const changeEventHandler = e => {
const value = e.target.options[e.target.selectedIndex].value;
console.log(value); //Validate value...
}
const select = document.querySelector('select[name=question3]').onchange = changeEventHandler;

Show the second dropdown once first dropdown's value selected is equal to 'Courier'

My problem is on how to make the second drop-down display once my first dropdown value selected is Courier
First the user must check the checkbox to show the first drop-down and this is my code
<p> <input type="checkbox" id="contract" class="icheckbox_flat-green" onclick="myFunctionCons()"> Contract </p>
Once checked, this contract via dropdown (first dropdown) will be visible
<select id="contractvia" style="display:none" class="form-control">
<option value="0">Via..</option>
<option value="1">Email</option>
<option value="2">FB Messenger</option>
<option value="3">Courier</option>
<option value="4">Others..</option>
</select>
My goal is to display this second dropdown once the contractvia's selected option is Courier
<select id="contractCourier" style="display:none" class="form-control">
<option value="">Courier</option>
<option value="scanned">Scanned</option>
<option value="net">Original</option>
<option value="mouth">Photocopy</option>
</select>
My first task to show the first dropdown once the checkbox is checked is achieved using this code, but it doesn't work for displaying the second dropdown once first dropdown's selected option is 'Courier'
<script>
function myFunctionCons() {
var con = document.getElementById("contract");
var conv = document.getElementById("contractvia");
var conc = document.getElementById("contractCourier");
if (con.checked == true) {
conv.style.display = "block";
} else {
conv.style.display = "none";
}
if ($("#contractvia").val() == 3)
conc.style.display = "block";
else
conc.style.display = "none";
}
</script>
Please check this in Vanilla Javascript
var con = document.getElementById("contract");
var conv = document.getElementById("contractvia");
var conc = document.getElementById("contractCourier");
//On checkbox return first select
con.addEventListener('click', myFunctionCons );
//if value of option is 3 show next select
conv.addEventListener('change', showSecondSelect );
function showSecondSelect() {
//3 is the index of courier
if (conv.selectedIndex == 3) {
conc.style.display = "block";
} else {
conc.style.display = "none";
}
}
function myFunctionCons() {
if (con.checked == true) {
conv.style.display = "block";
} else {
conv.style.display = "none";
}
}
#contractvia,
#contractCourier {
display: none;
}
<p><input type="checkbox" id="contract" class="icheckbox_flat-green">Contract</p>
<select id="contractvia" class="form-control">
<option value="0">Via..</option>
<option value="1">Email</option>
<option value="2">FB Messenger</option>
<option value="3">Courier</option>
<option value="4">Others..</option>
</select>
<select id="contractCourier" class="form-control">
<option value="Courier">Courier</option>
<option value="scanned">Scanned</option>
<option value="net">Original</option>
<option value="mouth">Photocopy</option>
</select>

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.

Disable option when clicked in select

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)

How to get the index of a selected item in listbox and add to listbox two with button?

I am looking to get the index of the selected item in a list box to add the selected item to list box 2.
The listbox was created in HTML.
<div class="clearfix">
<div class="select-container">
<select name="sometext" size="5">
<?
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheets()[1]);
var lastRow = sheet.getLastRow();
var myRange = sheet.getRange("A1:A"+lastRow);
var data = myRange.getValues();
?>
<? for (var i = 0; i < data.length; ++i) { ?>
<option><?!= data[i] ?></option>
<? } ?>
</select>
</div>
<div class="buttons">
<div><button onclick='addMonitoredFolder()' id='button1'>Add</button></div>
</div>
So when I press button 'Add', I want the currently selected item in list box 1 to be added to listbox 2. It would be good that if the user selects multiple options in the list then it will add these or at least know how to handle this. I have function addMonitoredFolder in there because I was trying to figure it out by just can't get my head around it.
<div class="select-container">
<select name="sometext" size="5">
<option>option</option>
</select>
</div>
Thanks!
Here is code that can get multiple selections from a list, and transfer the choices to the second list:
index.html
<!DOCTYPE html>
<html>
<body>
<div>List Box One</div>
<select id="slctOne" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<div>List Box Two</div>
<select id="slctTwo" multiple>
<option value="one">Value One</option>
<option value="two">Value Two</option>
<option value="three">Value Three</option>
<option value="four">Value Four</option>
</select>
<button onmouseup="getAndTransfer()">Get Choices</button>
<p>Hold down the Ctrl (windows) / Command (Mac) button to select multiple options.</p>
<!-- Use a templated HTML printing scriptlet to import JavaScript. -->
<?!= HtmlService.createHtmlOutputFromFile('JavaScript').getContent(); ?>
</body>
</html>
JavaScript.html
<script>
window.getAndTransfer = function() {
var allChoices = getMultiple();
putChoicesIntoSelectTwo(allChoices);
};
window.getMultiple = function() {
//console.log('getMultiple ran')
var allOptionNodesSelected = document.getElementById('slctOne').querySelectorAll('option:checked');
var howManySelected = allOptionNodesSelected.length;
console.log('number of option nodes: ' + howManySelected);
var optionElmt1 = allOptionNodesSelected[0];
console.log('optionElmt1.selected: ' + optionElmt1.selected);
var i=0,
arryAllOptions = [];
for(i=0;i<howManySelected;i+=1) {
console.log('optionElmt1.selected: ' + allOptionNodesSelected[i].value);
arryAllOptions.push(allOptionNodesSelected[i].value);
};
return arryAllOptions;
};
window.putChoicesIntoSelectTwo = function(theChoices) {
//Get select list two element
var selectListTwo = document.getElementById('slctTwo');
var allOptions = selectListTwo.getElementsByTagName("option"); //Get all current options inside of this select tag
var i = 0, thisOptionVal="";
//console.log(allOptions.length);
for (i=0;i<allOptions.length;i+=1) {
thisOptionVal = allOptions[i].value;
if (theChoices.indexOf(thisOptionVal) !== -1) {
allOptions[i].selected = true;
} else {
allOptions[i].selected = false;
};
};
};
</script>

Categories

Resources