so I want to add some input based on the option value from the drop down that will be selected. For example, the dropdown looks like this:
<form action="#" method="post">
<select name="job" id="job" >
<option value="">position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
</form>
and if the selected value is number 1 or teacher, it will display new input like this below it:
<input type="number" name="student" id="student">
<input type="Text" name="class" id="class">
if you guys know how to make it, maybe you can help me with this please, either using php or js because I've been stuck with this problem for a long time.
There are many different ways to achieve what you want depends on what framwwork you are using.
For
vanilla JS: onchange to control css OR append html.
jQuery: $("#class").hide() / .show();
Angular: ngIf
vueJs: v-if / v-show
etc...
In JS you can do that by adding change event listener to the <select></select> element;
and each time the selected <option></option> changes you should make all inputs hidden then make the ones you want visible.
Example:
const select = document.getElementById('job');
select.addEventListener('change', function() {
// returns the selected option's value
const selectedOption = select.value;
// makes all inputs hidden each time the selected option changes.
document.querySelectorAll('input').forEach(input => input.style.display = "none");
// for 1st parameter, pass the option value.
// for 2nd parameter, pass an array of ids of the inputs you want to make them visible.
const setInputs = (state, id) => {
if (selectedOption === state) {
(id.sup ? id = [id] : id);
id.forEach(i => {
try {
document.getElementById(i).style.display = 'block';
} catch (error) {
console.error(`#${i} doesn't exists!`)
}
});
}
}
/* if the selected option's value is 1(Teacher),
The "student" and "class" inputs will be visible. */
setInputs('1', ['student', 'class']);
/* if the selected option's value is 2(Principal),
The "id" and "principal" inputs will be visible. */
setInputs('2', ['id', 'principal']);
/* if the selected option's value is 3(Staff),
The "name" input will be visible. */
/* if you want to show just one input,
don't need to pass an array as 2nd parameter
just pass a string */
setInputs('3', 'name');
});
/* Makes all inputs hidden by default */
input {
display: none;
}
<form action="#" method="post">
<select name="job" id="job">
<option selected hidden disabled>Position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<input type="number" name="student" id="student" placeholder="Student">
<input type="Text" name="class" id="class" placeholder="class">
<input type="number" name="id" id="id" placeholder="ID">
<input type="number" name="principal" id="principal" placeholder="Principal">
<input type="Text" name="name" id="name" placeholder="Name">
</form>
before that, set the style of input is hide, then You can try onchange on select, Which is get the value of select. then proceed to show the hide input.
const job = document.getElementById("job");
let add = document.getElementsByClassName("addEx");
job.addEventListener("change",function() {
if (this.value == 1) {
for (let i = 0; i < add.length; i++) {
add[i].style.display = 'block';
}
}
else {
for (let i = 0; i < add.length; i++) {
add[i].style.display = 'none';
}
}
});
.addEx {
display:none;
}
<form action="#" method="post">
<select name="job" id="job" >
<option value="">position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<input type="number" name="student" id="student" class="addEx">
<input type="Text" name="class" id="class" class="addEx">
</form>
You can use like this:
jQuery(document).ready(function() {
$('#job').change(function() {
let job = $('#job').val();
if (job == '1') {
$('#sampleBox').show();
} else {
$('#sampleBox').hide();
}
});
});
#sampleBox {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="job" id="job">
<option selected hidden disabled>Position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<div id="sampleBox">
<input type="number" name="student" id="student">
<input type="Text" name="class" id="class">
</div>
Related
I have a form in my template with a drop down to select an option. how can I change a hidden value to the index of whats selected. So if they pick option 2 with the value of "Mains" it stores 1 or if they choose option 1 with a value of "Starters" it stores 0.
<div class="form-group">
<input type="hidden" id="arrayIndex" name="arrayIndex">
<label for="dishCategory">Choose a category:</label>
<select type="text" class="form-control" name="dishCategory" id="dishCategory">
{{#entries}}
{{#category}}
<option value="{{catName}}">{{catName}}</option>
{{/category}}
{{/entries}}
</select>
</div>
The following snippet adds some logic to your html document. Anytime you select a new option from the dropdown, it performs the following actions:
Updates an output message showing which index was picked among the
options
Sets the value of the hidden type input (#arrayIndex) as that index mentioned before
document.addEventListener("DOMContentLoaded", function() {
let select = document.getElementById('dishCategory');
select.addEventListener('change', (event) => {
//value of the selected option
let selectedValue = select.value;
//index of the selected option
let selectedOptionIndex = select.selectedIndex;
//the entire selected option element
let selectedOption = select.options[select.selectedIndex];
//updates the msg with information about which option was picked
document.getElementById('msg').innerText =
`The index of the option chosen was: ${selectedOptionIndex}`;
//updates the value of the hidden input with such index
document.getElementById('arrayIndex').value =
selectedOptionIndex;
});
});
#msg{
border: solid 1px black;
margin-bottom: 10px;
}
<div class="form-group">
<input type="hidden" id="arrayIndex" name="arrayIndex">
<div id="msg">Select an option in the dropdown...</div>
<label for="dishCategory">Choose a category:</label>
<select type="text"
class="form-control"
name="dishCategory"
id="dishCategory">
<option value="" disabled selected>Select your option</option>
<option value="Tom">01-Tom</option>
<option value="Jerry">02-Jerry</option>
<option value="Mickey">03-Mickey</option>
</select>
</div>
I have a select button with 3 options. I have another text box above. Depending upon the text box's value I want to make one of the option disabled using javascript.
Here is my HTML code:
<label for="name">Name of the candidate: </label><br>
<input type="text" name="e_name" value="<%=e.getName() %>" onfocus="ViewType(this.value);">
<br><br>
<label for="division">Choose Division</label><br>
<select name="e_division" id="selectbtn"><option>Select One</option><option>MECH</option><option>CSE</option><option>CE</option></select>
Here is my JavaScript code:
function ViewType(val){
var op=document.getElementById("selectbtn");
for(var i=0;i<=op.length();i++){
if(val == "Amit"){
op.option[1].disabled=true;
op.option[2].disabled=true;
}
}
}
Means here if the name is "Amit" then only "MECH" option will be visible. For any other name all options will be visible.
I have use onkeyup event in below code so that whenever user will type any name the function will get called to perform necessary operation.
Demo Code :
function ViewType(val) {
var op = document.getElementById("selectbtn").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
if (val.toLowerCase() == "amit") {
//checking if option value is not mceh
if (op[i].value != "MECH") {
//disable other option
op[i].disabled = true;
}
} else {
//enable all options
op[i].disabled = false;
}
}
}
<label for="name">Name of the candidate: </label><br>
<input type="text" name="e_name" onKeyup="ViewType(this.value);">
<br><br>
<label for="division">Choose Division</label><br>
<select name="e_division" id="selectbtn">
<option>Select One</option>
<option value="MECH">MECH</option>
<option value="CSE">CSE</option>
<option value="CE">CE</option>
</select>
HTML
<label for="name">Name of the candidate: </label><br>
<input id="candidate-name" type="text" name="e_name" value="" onfocus="ViewType(this.value);">
<br><br>
<label for="division">Choose Division</label><br>
<select name="e_division" id="selectbtn">
<option>Select One</option>
<option value="MECH">MECH</option>
<option>CSE</option>
<option>CE</option>
</select>
JS
var candidate = document.getElementById("candidate-name");
candidate.addEventListener("change", viewType);
function viewType() {
var select = document.getElementById("selectbtn");
var op = select.getElementsByTagName("option");
if(candidate.value == "Amit") {
op[2].disabled = true;
op[3].disabled = true;
}
}
I am working on a web form and here i want to make it so that you can select one of the three given types of options of contact and based on it a respective input field appears.How can i achieve that?
<select id="contact">
<option value="address">Address</option>
<option value="phone">Phone number</option>
<option value="website">Website</option>
</select>
i tried this at first but didnt know how to proceed further:
<form name="address" id="address" style="display:none">
<input type="text" name="address_"><br>
</form>
<form name="phone" id="phone" style="display:none">
<input type="text" name="phone_"><br>
</form>
<form name="website" id="website" style="display:none">
<input type="text" name="website_"><br>
</form>
Add an onselect handler to the option fields. Then inside the handler, call a function to append a dom node. Something like this:
<option value="address" onselect="handleSelection">Address</option>
function handleSelection() {
document.body.appendChild(someDomNode)
}
It's better to set the onchange EventListener to the parent <select id="contact"> element than it is to set a onselected or some other EvenListener to each of the <option> elements.
Note: I separated the javascript logic a little bit so it's easier to read.
document.getElementById('contact').addEventListener('change', function(e){
let value = e.target.value;
removeCreatedElements(); // remove all previously added, if any, before adding a new one
let input = createElement(value);
document.body.appendChild(input);
input.style.display = "block";
})
function createElement(value) {
let input = document.createElement("input");
input.type = "text";
input.id = value;
input.classList.add("dynamically-added");
input.placeholder = value;
return input;
}
function removeCreatedElements() {
let inputs = document.querySelectorAll(".dynamically-added");
for(let i=0; i < inputs.length; i++) {
document.body.removeChild(inputs[i]);
}
}
#contact {
margin-bottom: 40px;
}
<select id="contact">
<option value="address">Address</option>
<option value="phone">Phone number</option>
<option value="website">Website</option>
</select>
Basically, I want to make a site with a button that repeatedly asks user for input. However, one of the inputs that the site asks for involves a select field and depending on the select field, have a corresponding text field appear or dissapear(values none). My javascript utilizes a for loop as the user can repeatedly press the button to add more and more select fields( and corresponding text field).
Here is jsfiddle
Below is the example code of what I'm trying to do.
HTML
<div><select class="DISPLAYTYPE" id="QBox" data-fieldtype="P">
<option value = "text">TextBox</option>
<option value = "check">CheckBox</option>
<option value = "radio">Radio</option>
</select></div>
<input type="number" min="1" value="LENGTH" class="quantumBox" id="P">
JAVASCRIPT
var textBoxList = document.getElementsByClassName("DISPLAYTYPE");
for (var i=0; i<textBoxList.length;i++){
textBoxList[i].addEventListener('change', function(){
var subParam = textBoxList[i].options[textBoxList.selectedIndex].value;
if(subParam ="text"){
//make ONLY corresponding input box appear
}else{
//make ONLY corresponding input box dissapear
}
})
};
EDIT: This is the Structure
[table id="rootPlacement"]
//insert here
[/table]
[button/] <--This will make a duplicate of invisible html and place it under invisible root
//The invisible html stuff we want to duplicate into //insert here
Given your feedback about the HTML structure in the comments, you can use the following to achieve what you are trying to. Just look into
You are trying to get the selected value inside the change event for the drop-down by using var subParam = textBoxList[i].options[textBoxList.selectedIndex].value; rather than using textBoxList[i] you can use this so that i becomes var subParam = this.options[this.selectedIndex].value.
For showing hiding the inputs you can use the function findRoot() which takes the target element object i.e ``selectand finds a parent with the class namedrootPlacement` and returns the node and then you can iterate it's children to show the selected node and hide the rest.
See a demo below
var textBoxList = document.querySelectorAll(".DISPLAYTYPE");
for (var i = 0; i < textBoxList.length; i++) {
textBoxList[i].addEventListener('change', function() {
var selectedType = this.options[this.selectedIndex].value;
let rootPlacement = findRoot(this, 'rootPlacement');
let children = rootPlacement.children;
for (var c = 0; c < children.length; c++) {
let element = children[c];
let elementType = element.type;
let isInputElement = typeof elementType !== 'undefined';
if (isInputElement) {
if (elementType == selectedType) {
element.style.display = 'inline';
} else {
element.style.display = 'none';
}
}
}
});
};
function findRoot(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
input {
display: none;
}
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox1" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="" class="quantumBox" id="P1">
<input type="checkbox" value="" class="quantumBox" id="q1">
<input type="radio" value="" class="quantumBox" id="r1">
</div>
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox2" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="LENGTH" class="quantumBox" id="P2">
<input type="checkbox" value="" class="quantumBox" id="q2">
<input type="radio" value="LENGTH" class="quantumBox" id="r2">
</div>
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox3" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="LENGTH" class="quantumBox" id="P3">
<input type="checkbox" value="" class="quantumBox" id="q3">
<input type="radio" value="LENGTH" class="quantumBox" id="r3">
</div>
I have 4 select tag with class name select2 assigned to it. I want to make the border turn to red if there's no selected options or has an value equal to empty or 0. I've tried to add class using jquery but it makes all select.select2 border turns red.
Style
<style>
.errorType {
border-color: #F00 !important;
}
</style>
HTML
<select name="category" class="form-control select2" id="category" onChange="search_Operator(this.value)">
<option value="0"> Select Operator Category</option>
<option value="1">one</option> <option value="2"> two</option>
</select>
<select name="operatorName" class="form-control select2" id="operatorName" onChange="">
<option value="0"> Select operator Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="regionName" class="form-control select2" id="regionName">
<option value="0"> Select region Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="type" class="form-control select2" id="type">
<option value="0"> Select type </option>
</select>
JQUERY
$(function () {
$(".select2").select2();
});
$(".select2-selection").addClass('errorType');
Any idea?
Thanks in advance.
I've attached a function to the click event of the submit button, in order to check the value of every select element on the page:
$(function () {
$('.form-control-select2').select2();
$('#submit_btn').on('click', function(){
var submit_form = true;
$(".form-control-select2").each(function(){
var selected_value = $(this).val();
if (selected_value==0 || selected_value=='') {
$(this).next().find('.select2-selection').addClass('errorType');
submit_form = false;
} else {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
return submit_form;
});
});
Fiddle here: https://jsfiddle.net/64a41thz/21/.
Also, if you want to remove the red border when valid selection is made, add the following code:
$('.form-control-select2').on('change', function(){
if ($(this).val()!=0 && $(this).val()!='') {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
Fiddle here: https://jsfiddle.net/64a41thz/24/.
This does the trick. You just need to replace #yourButton with the actual ID you use.
$(document).on("click", "#yourButton", function() {
$(".select2").each(function(index, element) {
$(element).removeClass("errorType");
if ($(element).val() === "0") {
$(element).addClass("errorType");
}
});
});
Put your select tag inside a form with an id="submit" as shown
<form class="" action="" method="post" id="submit">
and add a button below the 4 select tags with this attribute
onclick="return submit_form('form#submit')"
the button should be like this,
<button type="button" class="btn btn-default" onclick="return submit_form('form#submit')">Submit</button>
In your jquery
function submit_form (form_id) {
$(form_id).find('select[name]').each(function (index, node) {
if (node.value == 0) {
var id = "select#" + node.id;
$(id).addClass('errorType');
}
});
}
This will search select tag with name as attribute, if found, it will get the value of the name and check of its empty or not. If found empty it will add new class that turns that select tag into a red border.
Hope this will help