i am creating a webpage using html,php and javascript.
i have used script for select option. The problem i am encountering on executing the code is that the first input field doesn't disappear on selecting the option again. instead i get the second input box and first input box as well. i.e. i get both even if i use if else condition.
var fil = document.getElementById("filter");
fil.onchange = function filteron() {
var filtertag = document.getElementById("filter");
var tag = filtertag.options[filtertag.selectedIndex].value;
var searchbox = document.createElement("input");
var filter = document.getElementById("criteriain");
searchbox.setAttribute("id", "criteria");
if (tag === 'ed') {
searchbox.setAttribute("type", "date");
searchbox.setAttribute("name", "searchin");
} else if (tag === 'gw') {
searchbox.setAttribute("type", "number");
searchbox.setAttribute("name", "searchin");
}
filter.appendChild(searchbox);
};
<form action="" method="post">
<label for="filter" id="filterin">Filter by</label>
<select id="filter" size="1" name="filter" onchange="filteron()">
<option value='slno' >Sl No</option>
<option value='ed' >Entry Date</option>
<option value='lot' >Lot No</option>
<option value='par' >Party</option>
<option value='var' >Variety</option>
<option value='cst' >Current status</option>
<option value='gw' >Gray width</option>
</select>
<br/>
<label for='criteria' id='criteriain'>Search for</label>
It is because irrespective of your selection you are creating a new element every time and only changing the type in if/else block for new element.
var fil = document.getElementById("filter");
fil.onchange = function filteron() {
var filtertag = document.getElementById("filter");
var tag = filtertag.options[filtertag.selectedIndex].value;
var searchbox = document.getElementById("criteria");
var filter = document.getElementById("criteriain");
if(undefined === searchbox || null === searchbox) {
searchbox = document.createElement("input");
searchbox.setAttribute("id", "criteria");
}
if (tag === 'ed') {
searchbox.setAttribute("type", "date");
searchbox.setAttribute("name", "searchin");
} else if (tag === 'gw') {
searchbox.setAttribute("type", "number");
searchbox.setAttribute("name", "searchin");
}
filter.appendChild(searchbox);
};
<form action="" method="post">
<label for="filter" id="filterin">Filter by</label>
<select id="filter" size="1" name="filter" onchange="filteron()">
<option value='slno' >Sl No</option>
<option value='ed' >Entry Date</option>
<option value='lot' >Lot No</option>
<option value='par' >Party</option>
<option value='var' >Variety</option>
<option value='cst' >Current status</option>
<option value='gw' >Gray width</option>
</select>
<br/>
<label for='criteria' id='criteriain'>Search for</label>
Related
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>
I am new to html javascript and trying to learn it. I am having an issue that when I select a value of a dropdown it will select another dropdown value when certain criteria matches.
If they Select the option 4 (takeout) from service_type dropdown, the counter dropdown will automatically selected the option 2 driveway. else user are free to select any value on both dropdown. Only if they select Takeout, it will make driveway selected and also make the table service option inactive.
if they select 1,2 or 3 from the Service type dropdown then option 1 will be enabled.
I need a javascript and no jquery. Please help me
<div class="form-group col-md-12">
<select name="service_type" id="service_type" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Counter</option>
<option value="1">Table Service</option>
<option value="2">Driveway</option>
</select>
</div>
You can use javascript like this:
function Checker(el){
const select = document.getElementById('counter');
removeOptions(select);
if(el.value == '4'){
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);
}else{
var option2 = document.createElement("option");
option2.text = "Table Service";
option2.value = "1";
select.add(option2);
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);
}
}
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for (i = L; i >= 0; i--) {
selectElement.remove(i);
}
}
<div class="form-group col-md-12">
<select name="service_type" id="service_type" class="form-control form-control-line" onChange="Checker(this)" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service Fist</option>
</select>
</div>
Create two function one for create option base to first choise and second for remove option everytime function is called.
const firstSelect = document.querySelector('#serviceType');
const secondSelect = document.querySelector('#counter');
firstSelect.addEventListener('change', (event) => {
if (event.target.value === '4') {
secondSelect.value = '2';
secondSelect.disabled = true;
} else if (typeof event.target.value === 'string' && event.target.value.length > 0) {
secondSelect.disabled = false;
secondSelect.value = '1';
} else {
secondSelect.disabled = false;
secondSelect.value = '';
}
});
<div class="form-group col-md-12">
<select name="service_type" id="serviceType" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Counter</option>
<option value="1">Table Service</option>
<option value="2">Driveway</option>
</select>
</div>
How does it work?
You need to select your Select controls from DOM and then listen to change event on first select, then you can get value from it and depending on your choice change value of Select #2. In order to disable ability to choose another option in second dropdown, you can disable it.
I am trying to show a table of reviews by taking the value of two dropdowns. When I was having one dropdown(positive, negative etc) that works fine but when I introduce another dropdown(food, drinks etc) it is not working.
It only works when I change the first dropdown and second dropdown but if I kept the first dropdown unchanged then it's not working
I tried by adding onchange method to the second dropdown. I just started with Javascript so not much idea about what to try.
function printResult(form) {
var output = {
{
output | safe
}
};
var sel = form.list;
var sel2 = form.list2;
var selectedVal = sel.options[sel.selectedIndex].value;
var selectedVal2 = sel2.options[sel.selectedIndex].value;
//document.getElementById("showResult").innerText = "Your number is: " + selectedVal;
//console.log(output);
document.getElementById("showResult").innerText = "Your number is: " + selectedVal2;
}
<form action="dropdown" onSubmit="return printResult(this);">
<label for="sentiment">Sentiment</label>
<div class="styled-select blue semi-square">
<select name="list">
<option value="all">All</option>
<option value="positive">Positive</option>
<option value="negative">Negative</option>
<option value="neutral">Neutral</option>
</select>
</div>
<div>
<select name="list2" onChange="printResult()">
<option value="menu">Menu Range</option>
<option value="food">Food</option>
<option value="drinks">Drinks</option>
<option value="desserts">Desserts</option>
</select>
</div>
<input type="submit" value="Filter">
<span id="showResult"></span>
</form>
You need to pass the form on the change too and return false to not submit the form:
function printResult(form) {
var sel = form.list;
var sel2 = form.list2;
var selectedVal = sel.value;
var selectedVal2 = sel2.value;
document.getElementById("showResult").innerText = "Your number is: " + selectedVal2;
return false;
}
<form action="dropdown" onSubmit="return printResult(this);">
<label for="sentiment">Sentiment</label>
<div class="styled-select blue semi-square">
<select name="list">
<option value="all">All</option>
<option value="positive">Positive</option>
<option value="negative">Negative</option>
<option value="neutral">Neutral</option>
</select>
</div>
<div>
<select name="list2" onChange="printResult(this.form)">
<option value="menu">Menu Range</option>
<option value="food">Food</option>
<option value="drinks">Drinks</option>
<option value="desserts">Desserts</option>
</select>
</div>
<input type="submit" value="Filter">
<span id="showResult"></span>
</form>
Perhaps you wanted this instead
window.addEventListener("load", function() {
document.getElementById("form1").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
var sel = this.list;
var sel2 = this.list2;
var selectedVal = sel.value;
var selectedVal2 = sel2.value;
document.getElementById("showResult").innerText = (selectedVal && selectedVal2) ? selectedVal + ":" + selectedVal2 : "Please select both";
});
});
<form action="dropdown" id="form1">
<label for="sentiment">Sentiment</label>
<div class="styled-select blue semi-square">
<select name="list">
<option value="">All</option>
<option value="positive">Positive</option>
<option value="negative">Negative</option>
<option value="neutral">Neutral</option>
</select>
</div>
<div>
<select name="list2">
<option value="">Menu Range</option>
<option value="food">Food</option>
<option value="drinks">Drinks</option>
<option value="desserts">Desserts</option>
</select>
</div>
<input type="submit" value="Filter">
<span id="showResult"></span>
</form>
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>
I don't know much about javascript and unfortunately don't have time to learn before this project is due (wish I did!). I assume it is possible to pass the value of a drop-down selection into a hidden text input field on a form before the form is submitted. Could anyone help me figure out how to do that with javascript? Thank you! Here are my drop-down and text box details:
<div class="formEntryArea">
<div class="formEntryLabel">
<span class="formLabel"><label for=" langdropdown">Would you like to receive library notices in English or Spanish? ><span class="formRequired">*</span></label></span>
</div>
<div class="formMultiSelect" id=”langdropdown”>
<select name=" langdropdown ">
<option value="0" selected="selected">Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
<input type="text" id="ddepartment" name="ddepartment" value=””>
</select>
</div>
This is simply. First of all, you have to bind a change event handler for your select. Then, you have to set input text with value selected from dropdown.
var select=document.getElementsByTagName('select')[0];
var input=document.getElementById('ddepartment');
select.onchange=function(){
input.value=select.options[select.selectedIndex].text;
}
<div class="formEntryArea">
<div class="formEntryLabel">
<span class="formLabel"><label for=" langdropdown">Would you like to receive library notices in English or Spanish? ><span class="formRequired">*</span></label></span>
</div>
<div class="formMultiSelect" id=”langdropdown”>
<select name=" langdropdown ">
<option value="0" selected="selected">Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
</select>
<input type="text" id="ddepartment" name="ddepartment">
</div>
You can use this code:
var myselect = document.getElementById("MySelect");
myselect.onchange = function(){
alert(myselect.options[myselect.selectedIndex].value);
document.getElementById("ddepartment").value = myselect.options[myselect.selectedIndex].value;
};
Result: https://jsfiddle.net/fh5myefw/
Mind to close the tags, it's better practice.
var select = document.getElementById('selectElem');
var outputElem = document.getElementById('ddepartment');
select.addEventListener('change',function(){
var newValue = !this.selectedIndex ? "":this.options[this.selectedIndex].text;
outputElem.value = newValue;
});
<select name="langdropdown" id="selectElem" required>
<option value="" selected="selected">Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
</select>
<input type="text" id="ddepartment" name="ddepartment" value="">
this is javascript function
function func(selectObject)
{
document.getElementById('ddepartment').value = selectObject.value;
}
add onchange event to select element like this
<select name="langdropdown" onchange="func(this)">
Here use this:
var sel = document.getElementById('lang');
sel.onchange = function() {
var val = this.options[this.selectedIndex].value;
var che = document.getElementById('cache').value;
che = val;
console.log(che);
}
SNIPPET
var sel = document.getElementById('lang');
sel.onchange = function() {
var val = this.options[this.selectedIndex].value;
var che = document.getElementById('cache').value;
che = val;
console.log(che);
}
<select id='lang' name="lang">
<option value="" selected>Choose language</option>
<option value="eng">English</option>
<option value="spa">Spanish</option>
<option value="jpn">Japanese</option>
<option value="zho">Chinese</option>
<option value="fin">Finnish</option>
<option value="nav">Navajo</option>
</select>
<input type="hidden" id="cache" name="cache" value=””>