Javascript hide values depending on a selected option - javascript

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.

Related

Hide fields based on selection from dropdown

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'});
}
}
});

set the value of select option dynamically

This is my code. I am trying to set the value of select tag from database. but it's not working as expected. My requiremnet is value='Auto' then 0th index should be selected else 1sst index should be selected. But its not happening that way. can some one help me?
<div class="form-group">
<label class="medium mb-1" for=""> Select Mode of Update </label>
<select class="form-control" name="avupdatemode" value="<%= data.updatemode %>" >
<option value="Auto" >Auto Update</option>
<option value="Manual">Manual</option>
</select>
</div>
<script>
var sel= document.getElementById('avupdatemode');
if(document.getElementById('avupdatemode').value =='Auto'){
sel.options.selectedIndex = 0;}
else{
sel.options.selectedIndex = 1;
}
</script>
First there is no id attribute on your select.
Second .value will take the value from the selected option and not the value attribute from the select.
So i've added data-value="sAuto" to the select and then done document.getElementById('avupdatemode').dataset.value == 'Auto'
DEMO
var sel = document.getElementById('avupdatemode');
if (document.getElementById('avupdatemode').dataset.value == 'Auto') {
sel.options.selectedIndex = 0;
} else {
sel.options.selectedIndex = 1;
}
<div class="form-group">
<label class="medium mb-1" for=""> Select Mode of Update </label>
<select class="form-control" id="avupdatemode" name="avupdatemode" data-value="sAuto">
<option value="Auto">Auto Update</option>
<option value="Manual">Manual</option>
</select>
</div>
I am getting my backend data in an array to my ejs page.
So I tried this and it worked:
var sos = <%- JSON.stringify(sos) %>;
I iterated the array and based on the value i set my index for the select option.

Get ID of all child elements and its input/select data

How can I get the id of each child element and its tag name so I can save the data of each column to a string?
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text">
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</div>
</div>
I've got the loop so far, but I don't know how to get the data depending on the input/select:
for (var j = 0; j < (nCols / nRows); j++) {
}
You could use .find('*') to get all the childs :
$('.row').find('*').each(function(){
//Get the id and value
})
Hope this helps.
$('.row').find('*').each(function(){
if($(this).prop('tagName')!='OPTION')
console.log("id = "+$(this).prop('id')+" / value = "+$(this).val());
else
console.log("id = "+$(this).prop('id')+" / value = "+$(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='first input'>
</div>
<div class="col-md-4">
<input id="poz-3" placeholder="numv" type="text" value='second input'>
</div>
<div class="col-md-4">
<select id="poz-3-s">
<option value="1">-Pick-</option>
<option value="2" selected>test2</option>
<option value="3">test3</option>
</select>
</div>
</div>
If I understood you correctly you can get all input's values simply by iterating through them with jQuery:
$.each($('.col input, .col select'), function(index, item) {
console.log('ELEMENT ID ' + $(item).attr('id') + ' VAL - ' + $(item).val());
});
of simply use serializeArray method like this:
$('input, select').serializeArray()
Working example of both ways here: https://jsfiddle.net/hc882g27/
P.S.: in pure javascript it could be done with querySelectorAll function:
var items = document.querySelectorAll('.col input, .col select');
for (var i = 0; i < items.length; i++) {
console.log(items[i].value);
}

How to get option value of only the selected checkboxes?

I want to get option value of only selected checkbox, but I am getting value from all the checkboxes.
My HTML code:
<div class= "outer">
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">BBQ Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane"> Alfredo Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
</div>
<input type="submit" value="Submit">
My JavaScript code:
function myAction(){
var vals = [];
var machine = document.getElementsByName('machine');
var m2 = document.getElementById('m2');
for(var i=0, n= machine.length; i<n; i++){
if(machine[i].checked){
vals.push(m2.value);
}
}
}
IDs must be unique.
Instead, you could use querySelectorAll() on the existing weight classes to grab only the select elements that follow a checked input (using the general sibling selector):
document.querySelectorAll('input:checked ~ .weight')
The select element values will be the same as their selected options' values.
Snippet
document.querySelector('input[type=submit]').addEventListener('click', myAction);
function myAction() {
var vals = [], //no need for new Array()
weights= document.querySelectorAll('input:checked ~ .weight');
for(var i = 0 ; i < weights.length ; i++) {
vals.push(weights[i].value);
}
console.log(vals);
}
<div class="outer">
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">I have a plane
<br>
<select class="weight" name="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">I have 2 planes
<br>
<select class="weight" name="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
</div>
<input type="submit" value="Submit">
You have m2 repeated twice in your code. HTML spec specifies undefined behavior when id is repeated (m2). Also your select box isn't a multi-select. You should just be able to get the value from the select box directly if that is the case.
You can use querySelector also on nested nodes,
so you could filter the div.inner blocks which have the input checked and then get the values from there:
function myAction() {
//var vals = new Array();
var inner = [].slice.call(document.querySelectorAll('.inner'));
var checked = inner.filter(function(x) {
var chk = x.querySelector('input');
if (chk.checked) return x;
})
var vals = checked.map(function(x){
var i = x.querySelector('select').value;
return i
});
}
BTW as Rick said your markup contain some errors so I would suggest to pass it through a validator_
for calling your function on click event of the input submit:
document.querySelector('input[type=submit').addEventListener('click', myAction)

Fill select list with values depending on preselection

I want to have one select list populated with different values (price) depending on which option was chosen in other select list (sale or rent)
So what I have done is first create the arrays for sale and rent.
Then get the jquery and do an change event to pick which selection was made.
then a Switch statement that should populate the select list in question, but it is not showing anything. While jquery is a library for javascript I dont know if mixing them like I have done is alright:
$('#transaction').change(function(){
$value = $('#transaction').val();
var sale = [];
for (var i = 350000; i <= 2000000; i+100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i+100) {
rent.push(i);
}
switch($value) {
case 'sale':
$.each(sale, function(key, value){
$('#price').append('<option value="' + index+ '">' + value + '</option>')
break;
case 'rent':
break;
}); // end of each
} // end of switch
}) ; //end of jquery snippet
<div class="row">
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('transaction', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="select">Select</option>
<option value="sale">Sale</option>
<option value="rent">Rent</option>
<option value="holiday">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>
You dont have the options element in your select tag, so it never gets the $value from this statement :- $value = ('#transaction').val();
Insert the option tags and then run your example.
All credits go to Keith Wood (Sydney)
$(function() {
$('#transaction').change(function() {
var sale = [];
for (var i = 350000; i <= 2000000; i += 100000) {
sale.push(i);
}
var rent = [];
for (var i = 500; i <= 6000; i += 100) {
rent.push(i);
}
var option = $('#transaction').val();
var prices = (option === '1' ? sale : (option === '2' ? rent : []));
var options = '';
$.each(prices, function(key, value) {
options += '<option value="' + value + '">' + value + '</option>';
});
$('#price').html(options);
});
});
<div class="col-md-2 col-md-offset-1">
<div class="form-group">
{{Form::label('street', 'Transaction')}}
<select name="transaction" id="transaction" class="form-control">
<option value="0">Select</option>
<option value="1">Sale</option>
<option value="2">Rent</option>
<option value="3">Holiday</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
{{Form::label('price', 'Price')}}
<select name="price" id="price" class="form-control">
</select>
</div>
</div>

Categories

Resources