Checking if a select tag has been answered - javascript

I have a working script that checks all inputs that have the class "required", it detects if the input has content and then passes the answers to Googles Invisible Recaptcha.
I'm running into an issue with select drop downs.
The following JS is an example that works with the text:
var questions = document.getElementsByClassName('required');
var valid = true;
for (var i=0; valid && i<questions.length; i++) {
if (!questions[i].value.trim()) {
valid = false;
}
}
A sample of one of my dropdowns are:
<select id="q6" class="required" name="designation">
<!-- Disabled -->
<option disabled selected>Select one of the following:</option>
<!-- Options -->
<option value="#">Regisitered Nurse</option>
<option value="#">Regisitered Practical Nurse</option>
<option value="#">Personal Support Worker (Developmental Service Worker)</option>
<option value="#">Nursing Student (Completed First Year)</option>
<!-- Options // END -->
</select>
I was wondering if anyone knows how to add the function to detect an unanswered select drop down to my script above. It would be excellent if we could make this work with a "file" input as well.

Try adding: value="" to your first select option, so by default it is empty, and will fail the validation check.
let validate = function() {
var questions = document.getElementsByClassName('required');
var valid = true;
for (var i = 0; valid && i < questions.length; i++) {
if (!questions[i].value.trim()) {
valid = false;
}
}
console.log(valid);
}
<input id="q5" class="required" name="name" type="text" />
<select id="q6" class="required" name="designation">
<!-- Disabled -->
<option disabled selected value="">Select one of the following:</option>
<!-- Options -->
<option value="#">Regisitered Nurse</option>
<option value="#">Regisitered Practical Nurse</option>
<option value="#">Personal Support Worker (Developmental Service Worker) </option>
<option value="#">Nursing Student (Completed First Year)</option>
<!-- Options // END -->
</select>
<button onclick="validate();">Validate</button>

You can validate using the selectedIndex attribute of the select element and then try getting the value attribute from the selected option if any:
validate = function(){
// Validate Select Elements
var selectElements = document.getElementsByTagName("select");
for(var i = 0; i < selectElements.length; i++)
{
var selectedIndex = selectElements[i].selectedIndex;
if (selectedIndex < 0 || !selectElements[i][selectedIndex].getAttribute("value"))
{
return false;
}
}
// Validate other elements here...
return true;
}
//Clear the selection of the first select element to show how validations work for empty selection
document.getElementById('select1').selectedIndex = -1;
<select id="select1">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="">Option With Empty Value Attribute</option>
<option>Option With No Value Attribute</option>
</select>
<br>
<select id="select2">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="">Option With Empty Value Attribute</option>
<option>Option With No Value Attribute</option>
</select>
<br><br>
<button onclick="alert(validate());">Validate</button>

Related

How to refresh a select list in html

I have a drop-down list where depending on the selected value, the next drop-down list shows specific values. when changing the value of the first list and then going back to the old value, the second list does not update. keeps the same value selected before. How can I make the second list update to the value I marked as selected by default whenever I change the value of the first list?
I hope you guys were able to understand me, and I thank you for your time.
Here's the code:
<select onchange="showprd('hidevalue', this), showprd2('hidevalue2', this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="hidevalue">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="hidevalue2">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
</body>
<script>
function showprd(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 0 ? 'block' : 'none';
}
function showprd2(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 1 ? 'block' : 'none';
}
</script>
TL;DR. Control the input value changes in one place.
Please see the updated snippet below. html structure hasn't been changed, but I've removed the inline js call and updated the id names. JavaScript blocks are commented in details.
In a nut-shell, this code listens for any change to the parent select dropdown. Whenever a change occurs, its child dropdowns will reset their values and toggle their visibility accordingly.
// Assign each dom element to a variable
const primarySelect = document.querySelector('#primary');
const childSelect1 = document.querySelector('#child1');
const childSelect2 = document.querySelector('#child2');
const defaultValues = document.querySelectorAll('.default');
function resetInputs() {
// Reset the child select options to default
defaultValues.forEach(option => option.selected = true);
}
function handlePrimary(e) {
// Reset the child select values whenever the parent value changes
resetInputs();
// `input` value is always a string. Here we're converting it to a number
const val = parseFloat(e.target.value);
// Toggle visibility of child select dropdowns
[childSelect1, childSelect2].
forEach((select, i) => select.style.display = val === i ? 'block' : 'none');
}
primarySelect.addEventListener('change', handlePrimary);
<select id="primary">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="child1">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="child2">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
If I understood correctly, the expected behavior is when the second or third <select> is hidden, the <select> should go back to default (the first <option>?). If so, then remove disabled and hidden from the first <option> of the second and third <select> then add the following:
selectObj.hidden = true;
selectObj.selectedIndex = 0;
The example below has a <form> wrapped around everything (always use a form if you have more than one form control. By using HTMLFormElement interface I rewrote the code and can reference all form controls with very little code. Inline event handlers are garbage so don't do this:
<select id='sel' onchange="lame(this)">
Instead do this:
selObj.onchange = good;
OR
selObj.addEventListener('change', better)
Read about events and event delegation
const UI = document.forms.UI;
UI.onchange = showSelect;
function showSelect(e) {
const sel = e.target;
const IO = this.elements;
if (sel.id === "A") {
if (sel.value === '0') {
IO.B.hidden = false;
IO.C.hidden = true;
IO.C.selectedIndex = 0;
} else {
IO.B.hidden = true;
IO.B.selectedIndex = 0;
IO.C.hidden = false;
}
}
}
<form id='UI'>
<select id='A'>
<option disabled selected hidden>Pick</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<br>
<br>
<select id="B" hidden>
<option selected>Pick B</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<select id="C" hidden>
<option selected>Pick C</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
</form>
I give you an example for your reference:
let secondList = [
[{
value: "pleno",
text: "Pleno"
},
{
value: "integrado",
text: "Integrado"
}
],
[
{
value: "junior",
text: "Junior"
},
{
value: "senior",
text: "Senior"
}
]
]
function update(v){
let secondSelectBox=document.getElementById("second");
secondSelectBox.style.display="none";
let optionList=secondList[v.value];
if (optionList){
let defaultOption=new Option("Selecione o produto","");
secondSelectBox.innerHTML="";
secondSelectBox.options.add(defaultOption);
optionList.forEach(o=>{
let vv=new Option(o.text,o.value);
secondSelectBox.options.add(vv);
})
secondSelectBox.style.display="block";
}
}
<select onchange="update(this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<select hidden id="second">
</select>

Function to check option list validation not working

I have a select option list for my form and I want to make sure the user has selected one of the options. My function logic implies that if the user keeps the dropdown on the default option, an alert will pop up prompting them to change it. However, no alert shows up whatsoever. What am I doing wrong?
function isOption(form) {
var type = form.getElementByID("pastimetype")
var selectedValue = type.options[type.selectedIndex].value;
if (selectedValue == "selectpastime") {
alert("Please select a pastime.")
return false
}
return true
}
<p><label for="pastime"> Favourite pastime: </label>
<select name="pastime" select id="pastimetype">
<option value="selectpastime">---Please choose an option---</option>
<option value="surfingtheweb">Surfing the Web</option>
<option value="playingsport">Playing Sport</option>
<option value="listeningtomusic">Listening to Music</option>
<option value="watchingtv">Watching TV</option>
<option value="playinggames">Playing Games</option>
<option value="communityservice">Community Service</option>
<option value="daydreaming">Daydreaming</option>
<option value="reading">Reading</option>
<option value="meditation">Meditation</option>
</select>
</p>
you need to add the function to the submit event of the form.
you misspelled getElementById
no need to use form.getElementById
easier to get the value using select.value
use preventDefault instead of returning true/false
Also
function isOption(e) {
var sel = document.getElementById("pastimetype");
var selectedValue = sel.value;
if (selectedValue == "") { // I removed the value from the "Please select"
alert("Please select a pastime.")
e.preventDefault(); // stop submission
}
}
window.addEventListener("load",function() {
document.getElementById("form1").addEventListener("submit",isOption)
})
<form id="form1">
<p><label for="pastime"> Favourite pastime: </label>
<select name="pastime" select id="pastimetype">
<option value="">---Please choose an option---</option>
<option value="surfingtheweb">Surfing the Web</option>
<option value="playingsport">Playing Sport</option>
<option value="listeningtomusic">Listening to Music</option>
<option value="watchingtv">Watching TV</option>
<option value="playinggames">Playing Games</option>
<option value="communityservice">Community Service</option>
<option value="daydreaming">Daydreaming</option>
<option value="reading">Reading</option>
<option value="meditation">Meditation</option>
</select>
</p>
<input type="submit" />
</form>

Add removed select options

Currently I have a function I created that removes some options from a select menu based on a value passed from another select. I want to revert back to normal each time the function is called (add all the original options back)
HTML
<select id="Current-Tier" onchange="removetier();" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500">Diamond</option>
</select>
<select id="Desired-Tier" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500">Diamond</option>
</select>
JS
function removetier(){
var currentTierValue = document.getElementById("Current-Tier");
var current = currentTierValue.options[currentTierValue.selectedIndex].value;
var desiredDivisionValue = document.getElementById("Desired-Tier");
for(var i=0;i<desiredDivisionValue.length;i++){
if(desiredDivisionValue[i].value < current){
desiredDivisionValue.remove(desiredDivisionValue[i]);
}
}
Update_Desired_Rank_image();
}
Have you considered adding the hidden attribute rather than deleting them?
Then the next time you receive a request, you can go through the list programmatically and remove the hidden attribute from each option.
An example of the hidden label, BTW, is
<select id="Desired-Tier" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500" hidden>Diamond</option>
</select>
If you run it you will see that Diamond is hidden. This way you always have access to all your options.
You can easily iterate over the select input and either store the removed items in an array or leverage the hidden attribute on the option tag:
Fiddle: https://jsfiddle.net/gLwwmh82/2/
HTML
<select id="mySelect">
<option value="">Select...</option>
<option value="test1">Test1</option>
<option value="test2">Test2</option>
<option value="test3">Test3</option>
<option value="test4">Test4</option>
<option value="test5">Test5</option>
<option value="test6">Test6</option>
</select>
<button id="btnRemove" onclick="remove()">Remove Half of Entries</button>
<button id="btnReset" onclick="reset()">Reset</button>
JS
function reset() {
var select = document.getElementById('mySelect');
var options = select.querySelectorAll('option');
for (var i = 0; i < options.length; i++) {
options[i].removeAttribute('hidden');
}
}
function remove() {
var select = document.getElementById('mySelect');
select.value = "";
var entries = select.querySelectorAll('option');
for (var i = 1; i < 5; i++) {
// Wrap the below line in your logic to know what to delete/not to delete
entries[i].setAttribute('hidden', true);
}
}

How to get the OPTION's TEXT value

In this case, only primary dropdown will change, other dropdowns' values will change automatically according to it (so users wont be changing them) I'm trying to get the Option's TEXT value using PHP with $_POST. But i can only get it when i manually changed the other dropdown .
I have tried to use the trigger() method, but it fails to get the option text value. Any idea why the code fails to work. Thank you.
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}
}
<!-- try to get the option text value and pass it to input field-->
<!-- Then in the php code use $_POST[] to retrieve the input value-->
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.options[ddl.selectedIndex].text;
}
$("select").trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications" onChange="setTextField(this)">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<input id="make_text" type="hidden" name="make_text" value="" />
<div> <b>Other dropdown 2</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</form>
PHP Code
$value =$_POST['make_text'];
Html element <select> onchange doesn't fire for programmatic changes, you need to fire it yourself with
$(".secondary").trigger("change");
or by Id
$("#Qualifications").trigger("change");
The problem is that your hidden <input> never had the value. if you remove the hidden it on your code you can check it.
So when you POSTED the values the value on make_text was empty string. So if you fire the trigger after the for loop then it will work.
function setDropDown() {
var index_name = document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.querySelectorAll('.secondary');
for (var i = 0; i < others.length; i++) {
others[i].selectedIndex = index_name;
}
$("#Qualifications").trigger("change");
}
function setTextField(ddl) {
document.getElementById('make_text').value = ddl.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post">
<div><b>Primary dropdown:</b>
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</div>
<div>
<b>Other dropdown 1</b>:
<select class='secondary' id="Qualifications" name="Qualifications" onChange="setTextField(this)">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select></div>
<input id="make_text" name="make_text" value="" />
<div> <b>Other dropdown 2</b>:
<select class='secondary' id="Qualifications2" name="Qualifications2">
<option value="select">select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>
</form>
I have to say that I don't see any need to use a hidden input text to POST data to PHP because you can just post the value of the <select> and retrieve it in PHP like this $force = $_POST["ForceSelection"];.
Otherwise, if you want to continue what you started, you can change your setDropDown() function to this :
function setDropDown() {
#Get the selected value of the ForceSelection select :
var index_name = $('#ForceSelection').val();
#Change the value of the other secondary select :
$(".secondary").each(function( index ) {
$(this).val(index_name).change();//This will change the value and trigger the change event.
});
}

HTML select option VALUE calculate

I am trying to make a simple "registry book" from a select HTML
The idea is 3 selecting options click confirm and based on the selected options make a price with a math formula or (don't know what is ) an array (in the sense of a table of like every var there) add a Hour:Minute from machine and place it in a paragraph.
It will work. (just learning HTML and CSS)
Math would be select2 * select3 with one exception in the case of [select2(option1 and option2) * select3 = samevalue)
With that aside can someone post a modular simplistic type of code that would Help.
For those who need to read some more:(copy&paste* - *Sorry for indentation)
document.getElementById("Confirm").onClick = function() {
var entry = ""
document.getElementById("Televizor").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Controllere").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Timp").onChange = function() {
if (this.selectedIndex !== 0) {
entry += this.value;
}
};
document.getElementById("Table").innerHTML = "<br> " + entry + Date();
var entry = ""
}
<h2>TV-uri</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">Date & Time.</button>
<p id="demo">Dunno</p>
<div class="container">
<select id="Televizoare">
<option value="0">Televizoare</option>
<option value="1">Tv 1</option>
<option value="2">Tv 2</option>
<option value="3">TV 3</option>
<option value="4">Tv 4</option>
<option value="5">TV 5</option>
<option value="6">Tv 6</option>
<option value="7">TV 7</option>
</select>
<select id="Controller">
<option value="0">Controllere</option>
<option value="1c">1 Controller</option>
<option value="2c">2 Controllere</option>
<option value="3c">3 Controllere</option>
<option value="4c">4 Controllere</option>
</select>
<select id="Timp">
<option value="0">Timp</option>
<option value="1h">1 ora</option>
<option value="1h2">1 ora 30 minute</option>
<option value="2h">2 ore</option>
<option value="2h2">2 ore 30 minute</option>
<option value="3h">3 ore</option>
</select>
<button id="Confirm" onclick="Confrim)">Confirm</button>
</div>
<p id="Table"></p>
Well, you could start off by making sure the spelling and capitalization of your IDs and function names match.
Also, you should create some form of a validation method to check if all the fields are valid before proceeding to the calculation method.
Not sure what you are multiplying, but if you can at least get the valuse from the form fields, that's half the battle.
You should also enclose all your fields within a form object so you can natively interact with the form in a traditional HTML fashion.
// Define the confirm clicke listener for the Confirm button.
function confirm() {
// Grab all the fields and apply them to a map.
var fields = {
'Televizoare' : document.getElementById('Televizoare'),
'Controllere' : document.getElementById('Controllere'),
'Timp' : document.getElementById('Timp')
};
// Determine if the user selected an option for all fields.
var isValid = doValidation(fields);
if (!isValid) {
document.getElementById("Table").innerHTML = 'Please provide all fields!';
return;
}
// Create listeners ???
fields["Televizoare"].onChange = function(e) { };
fields["Controllere"].onChange = function(e) { };
fields["Timp"].onChange = function(e) { };
// Set the value of the paragraph to the selected values.
document.getElementById("Table").innerHTML = Object.keys(fields)
.map(field => fields[field].value)
.join(' — ');
}
// Validation function to check if ALL fields have options selected other than 0.
function doValidation(fields) {
return [].every.call(Object.keys(fields), field => fields[field].selectedIndex !== 0);
}
<h2>TV-uri</h2>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()">Date & Time.</button>
<p id="demo">Dunno</p>
<div class="container">
<select id="Televizoare">
<option value="0">Televizoare</option>
<option value="1">Tv 1</option>
<option value="2">Tv 2</option>
<option value="3">TV 3</option>
<option value="4">Tv 4</option>
<option value="5">TV 5</option>
<option value="6">Tv 6</option>
<option value="7">TV 7</option>
</select>
<select id="Controllere">
<option value="0">Controllere</option>
<option value="1c">1 Controllere</option>
<option value="2c">2 Controllere</option>
<option value="3c">3 Controllere</option>
<option value="4c">4 Controllere</option>
</select>
<select id="Timp">
<option value="0">Timp</option>
<option value="1h">1 ora</option>
<option value="1h2">1 ora 30 minute</option>
<option value="2h">2 ore</option>
<option value="2h2">2 ore 30 minute</option>
<option value="3h">3 ore</option>
</select>
<button id="Confirm" onclick="confirm()">Confirm</button>
</div>
<p id="Table"></p>

Categories