Hide fields based on selection from dropdown - javascript

I have dropdown menu for categories where you can select a type of property like (colocation, sell, buy)
and based on that selection fields will show to add extra information's
But every selection need specific type of fields
For I'm using jQuery but I don't know how to show fields based on every selection
Html code for menu :
<select name="prop_category" id="prop_category_submit" class="select-submit2">
<option value="-1">Aucun</option>
<option class="level-0" value="149">Colocation</option>
<option class="level-1" value="150">colocation études</option>
<option class="level-1" value="151">Colocation pour travail</option>
<option class="level-1" value="440">Vacance</option>
<option class="level-0" value="72">Luxe</option>
<option class="level-1" value="76">Appartement</option>
</select>
jQuery
jQuery("#prop_category_submit").change(function(){
const currentVal = jQuery("#prop_category_submit").val();
let imputList = ["property_size","property_lot_size"];
if (['149','150','151','440','72','76'].includes(currentVal)) {
for (let i = 0; i < imputList.length; i++) {
const elmnt = imputList[i];
jQuery("#"+elmnt).parent().css({'display':'none'});
}
}else{
for (let i = 0; i < imputList.length; i++) {
const elmnt = imputList[i];
jQuery("#"+elmnt).parent().css({'display':'block'});
}
}
});
Submit form
<div class="profile-onprofile row">
<div class="col-md-6">
<label for="property_size"> Superficie en m<sup>2</sup> .</label>
<input type="number" id="property_size" size="40" class="form-control" name="property_size" value="">
</div>
<div class="col-md-6 ">
<label for="property_lot_size"> Superficie du lot en m<sup>2</sup> . </label>
<input type="number" id="property_lot_size" size="40" class="form-control" name="property_lot_size" value="">
</div>

I fixed this question by using this code
jQuery("#prop_category_submit").change(function(){
const currentVal = jQuery("#prop_category_submit").val();
let imputList = ["property_rooms","property_bedrooms","property_bathrooms", "meuble","property_size"];
if (['65','37','66','68','70','69','67','71','27'].includes(currentVal)) {
if(currentVal=="65"){ //Terrains
jQuery("#property_rooms").parent().css('display','none');
jQuery("#property_bedrooms").parent().css('display','block');
jQuery("#property_bathrooms").parent().css('display','block');
jQuery("#meuble").parent().css('display','block');
jQuery("#property_lot_size").parent().css('display','none');
jQuery("#property-garage").parent().css('display','block');
jQuery("#property_size").parent().css('display','block');
}
}else{
for (let i = 0; i < imputList.length; i++) {
const elmnt = imputList[i];
jQuery("#"+elmnt).parent().css({'display':'block'});
}
}
});

Related

How to get value from select box in html table

I'm trying to retrieve a value from a select box in my HTML table. How can I select the selected value?
What I've tried so far:
this.cells[14].innerHTML;
this.cells[14].children[0].innerhtml;
this.cells[14].children[0].innerText;
The last one .innerText returns all the items in my select box......
var table2 = document.getElementById('table_items_program');
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function () {
document.getElementById("id").value = this.cells[0].innerHTML;
document.getElementById("select").value = this.cells[14].children[0].innerText;
}
}
<td><select class="selectpicker" multiple>
<?php while ($row9 = mysqli_fetch_assoc($result9)):; ?>
<option value="<?php echo $row9['id']; ?>"><?php echo $row9['id'];?>
</option>
<?php endwhile; ?>
</select></td>
<input style="display: inline" id="id" name="id">
<input style="display: inline" id="select" name="select">
The selected value from my selection box in my HTML table
How can I select the selected value?
You can get the selected index with the method HTMLSelect​Element​.selected​Index
But if I understand your trouble. You try to get the current values of your select. So you need to get the value of your selected options.
You can do it like:
document.getElementById('mySelect').onchange = function() {
let options = this && this.options;
let selectedValues = []
for (var i = options.length; i--;) {
let opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
console.log(selectedValues)
}
<select id="mySelect" multiple>
<option value="a"> a </option>
<option value="b"> b </option>
<option value="c"> c </option>
</select>
Implementation into your code example
for (var i2 = 1; i2 < table2.rows.length; i2++) {
table2.rows[i2].onclick = function() {
document.getElementById("id").value = this.cells[0].innerHTML;
var options = this && this.cells[14].children[0].options;
var selectedValues = []
for (var i = options.length; i--;) {
var opt = options[i];
if (opt.selected) {
selectedValues.push(opt.value || opt.text);
}
}
document.getElementById("select").value = JSON.stringify(selectedValues);
}
}
so simple...
ShowSelected.onclick = function()
{
console.clear()
document.querySelectorAll('.selectpicker option:checked').forEach(opt=>console.log(opt.value))
}
.selectpicker {
vertical-align: text-top;
}
choose one or more :
<select class="selectpicker" multiple size=6 >
<option value="a"> A element</option>
<option value="b"> B element</option>
<option value="c"> C element</option>
<option value="d"> D element</option>
<option value="e"> E element</option>
<option value="f"> F element</option>
</select>
<button id="ShowSelected"> Show Selected</button>
Welcome to Stack Overflow!
So, your <select> has the class selectpicker. We can use this to select your <select>!
Try the following to get your value:
document.querySelector(".selectpicker").value;
Or, if you have multiple <select>'s, you can use
[...document.querySelectorAll(".selectpicker")].forEach(opt => {
console.log(opt.value)
});
Hope that clears things up a little.

How to manipulate selected option's value to be the same as option text with JavaScript

I have this dynamic HTML / JavaScript form that is working great, but I found that when I click submit it is bringing over the value of the option as its index and not as the text within the option.
I have tried altering the JavaScript code but can not seem to figure out how to resolve this.
HTML
<!-- Category -->
<label for="type">Category<span class="required-input"> *</span></label>
<select id="type" name="type" onchange="ChangeTypeList()">
<option value="">--Select--</option>
<option value="Order Inquiry">Order Inquiry</option>
<option value="Product Inquiry">Product Inquiry</option>
</select>
<!-- Sub Category -->
<label for="reason">Sub Category</label>
<select id="reason" name="reason"></select>
JavaScript
var reasons = {};
reasons['Order Inquiry'] = ['Order Status','Order Issue', 'X'];
reasons['Product Inquiry'] = ['Product Weight', 'Product Quality'];
function ChangeTypeList() {
var typeList = document.getElementById("type");
var reasonsList = document.getElementById("reason");
var reasonsType = typeList.options[typeList.selectedIndex].value;
while (reasonsList.options.length) {
reasonsList.remove(0);
}
var decisions = reasons[reasonsType];
if (decisions) {
var i;
for (i = 0; i < decisions.length; i++) {
var decision = new Option(decisions[i], i);
reasonsList.options.add(decision);
// console.log('decision', decision);
}
}
}
When I select the first Category option 'Order Inquiry' and console.log:
console.log('decision', decision);
I see the following in the Console for the Sub Categories:
<option value="0">Order Status</option>
<option value="1">Order Issue</option>
<option value="2">X</option>
Ideally I want to see this is the Console for the Sub Categories:
<option value="Order Status">Order Status</option>
<option value="Order Issue">Order Issue</option>
<option value="X">X</option>
You need to pass decisions[i] as second parameter in Option.
Syntax:new Option(text, value, defaultSelected, selected); More details Option
var reasons = {};
reasons['Order Inquiry'] = ['Order Status','Order Issue', 'X'];
reasons['Product Inquiry'] = ['Product Weight', 'Product Quality'];
function ChangeTypeList() {
var typeList = document.getElementById("type");
var reasonsList = document.getElementById("reason");
var reasonsType = typeList.options[typeList.selectedIndex].value;
while (reasonsList.options.length) {
reasonsList.remove(0);
}
var reason = document.getElementById('reason');
var decisions = reasons[reasonsType];
if (decisions) {
var i;
for (i = 0; i < decisions.length; i++) {
//This line is changed
var decision = new Option(decisions[i], decisions[i]);
reasonsList.options.add(decision);
console.log('decision', decision);
}
}
}
<label for="type">Category<span class="required-input"> *</span></label>
<select id="type" name="type" onchange="ChangeTypeList()">
<option value="">--Select--</option>
<option value="Order Inquiry">Order Inquiry</option>
<option value="Product Inquiry">Product Inquiry</option>
</select>
<!-- Sub Category -->
<label for="reason">Sub Category</label>
<select id="reason" name="reason"></select>
option HTML element has a value and text attribute.
var options = document.getElementById("dropdown").children;
for (var i = 0; i < options.length; i++) {
options[i].value = options[i].text;
}
<select id="dropdown">
<option value="0">A</option>
<option value="1">B</option>
<option value="2">C</option>
</select>

Dynamically adding input text field with label in place of drop down menu

I want to replace drop down menu when a specific option selected from a drop down menu.
Here is drop down menu
When ever a user select other from drop down menu , I want to replace this drop down menu with input field
like
I tried with following code but it didn't work for me
<div class="form-group">
<label for="location" class="col-sm-2 control-label" style="color: #0E0E0E;white-space: nowrap;">Your Location</label>
<div class="col-sm-10">
<select class="selectpicker form-control" id="location" name="location" required="true">
<option value="jaipur" disabled="disabled" selected="selected">Jaipur</option>
<option value="shimla">Shimla</option>
<option value="bangalore">Bangalore</option>
<option value="hyderabad">Hyderabad</option>
<option value="mumbai">Mumbai</option>
<option value="varansi">Varanasi</option>
<option value="dehradun">Dehradun</option>
<option value="masoori">Masoori</option>
<option value="goa">GOA</option>
<option value="udaipur">Udaipur</option>
<option value="kokata">Kolkata</option>
<option value="agra">Agra</option>
<option value="allahabad">Allahabad</option>
<option value="amritsar">Amritsar</option>
<option value="chandigarh">Chandigarh</option>
<option value="chennai">Chennai</option>
<option value="lucknow">Lucknow</option>
<option value="nanital">Nanital</option>
<option value="ludhiana">Ludhiana</option>
<option value="patiala">Patiala</option>
<option value="others" onclick="addElement();">other</option>
</select>
<input type="hidden" value="0" id="theValue" />
<div id="myDiv"> </div>
</div>
</div>
JavaScript that I am using is
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = 'Element Number '+num+' has been added!';
ni.appendChild(newdiv);
}
Can someone guide me to achieve the desired goal?
try to use this.
HTML:
<div class="form-group">
<label for="location" class="col-sm-2 control-label" style="color: #0E0E0E;white-space: nowrap;">Your Location</label>
<div class="col-sm-10">
<select class="selectpicker form-control" id="location" onchange="addElement(this.value)" name="location" required="true">
<option value="jaipur" disabled="disabled" selected="selected">Jaipur</option>
<option value="shimla">Shimla</option>
<option value="bangalore">Bangalore</option>
<option value="hyderabad">Hyderabad</option>
<option value="others">other</option>
</select>
<input type="hidden" value="0" id="theValue" />
<div id="myDiv" class="hide"><input type="text"> </div>
</div>
</div>
JQuery:
function addElement(value)
{
if(value == 'others')
{
$('#location').addClass('hide');
$('#myDiv').addClass('show');
}
}
CSS:
.hide
{
display : none
}
.show
{
display : block
}
Did you get any console errors (F12)? Because you're missing a ' in your code.
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = 'Element Number '+num+' has been added!';
ni.appendChild(newdiv);
}

How do I have my drop down selections submit in the HTML form?

I have these conditional drop lists behaving on screen as expected, but I cannot get the selected values from the drop downs to output in the HTML form (I can if I don't include the javascript). Only the text inputs are outputing as per the xml result below (Company & Add1). I want the xml to contain the Location from the first drop down, and the selected city from the conditional 2nd drop down.
<body>
<form action="http://TESTPLANETPRESS:8080/ObtainQuote" method="GET" >
<fieldset>
<legend>Location</legend>
<select id="country" class="source" onchange="updateSelectTarget()">
<option value="England">England</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<select id="England">
<option value="Birmingham">Birmingham</option>
<option value="Liverpool">Liverpool</option>
<option value="London">London</option>
</select>
<select id="France" class="hidden">
<option value="Lyon">Lyon</option>
<option value="Marseille">Marseille</option>
<option value="Paris">Paris</option>
</select>
<select id="Germany" class="hidden">
<option value="Berlin">Berlin</option>
<option value="Hamburg">Hamburg</option>
<option value="Munich">Munich</option>
</select>
<label for="Company">Company:</label><input type="text" name="Company" value="Google">
<label for="Add1">Add1:</label><input type="text" name="Add1" value="1 Nowhere Street">
</fieldset>
<input type="submit" value="Submit">
</form>
<script>
function updateSelectTarget () {
var id = this.options[this.selectedIndex].value;
var targets = this.parentNode.getElementsByTagName("select");
var len = targets.length;
for (var i = len - 1; i > 0; --i) {
if (targets[i].id == id) {
targets[i].style.display = "block";
}
else {
targets[i].style.display = "none";
}
}
}
function initChangeHandler () {
var el = document.getElementById("country");
el.onchange = updateSelectTarget;
el.onchange();
}
window.onload = initChangeHandler;
</script>
</body>
Current XML result, (Does not include the results from the two drop downs).
<?xml version="1.0"?>
-<request type="GET">
<paths count="0"/>
-<values count="2">
<Company>Google</Company>
<Add1>1 Nowhere Street</Add1>
</values>
Do you want the value attribute or the text? Based on Get selected value in dropdown list using JavaScript? (similar to the first part), .value should work for the value attribute and .text for the text that is selected.
Also, please make two different questions instead of one question with 2 questions nested inside.

Javascript hide values depending on a selected option

I need help with some javascript. The idea is to hide some values from a depending on a parent
here is the html
<div class="form-group" style="margin-top: 20px;">
<label for="inputPassword3" class="col-sm-2 control-label">Phase</label>
<div class="col-sm-10">
<select class="form-control" name="phase" id="phase">
{%if phases is defined%}
{%for phase in phases%}
<option value="{{phase.id}}">{{phase.nom}}</option>
{%endfor%}
{%endif%}
</select>
</div>
</div>
<div class="form-group" >
<label for="inputPassword3" class="col-sm-2 control-label">Sous phase</label>
<div class="col-sm-10">
<select class="form-control" name="ssphase" id="ssphase">
{%if ssphases is defined%}
{%for ssphase in ssphases%}
<option value="{{ssphase.id}}" id="{{ssphase.phaseid}}">{{ssphase.nom}}</option>
{%endfor%}
{%endif%}
</select>
</div>
</div>
Do you have any idea to make the javascript hide options with the id that doesnt match with the value of the option selected on the first select?
Thanks for helping !
You can do it like this:
phase.onchange = function () {
show_sphases (this.value);
}
function show_sphases (phase) {
var subphases = document.querySelectorAll("[data-phase='" + phase + "']");
var allSubphases = document.querySelectorAll("#ssphase option");
for (var i = 0; i <= allSubphases.length; i++ ){
var item = allSubphases.item(i);
$(item).hide();
}
for (var i = 0; i <= subphases.length; i++ ){
var item = subphases.item(i);
$(item).show();
}
}
You also have to add a data-phase attribute to your ssphases options so that you can link them together, like this:
<option value="11" id="11" data-phase="1">Subphase #1-1</option>
I used jQuery for $().hide and $().show.
Here's a fiddle.

Categories

Resources