showing one of 3 divs depending on which select is chosen [duplicate] - javascript

This question already has answers here:
jQuery select change show/hide div event
(10 answers)
Closed 8 years ago.
I have a select box with 3 option body, strength, distance. I want to use javascript / jquery to show a div depending on which of those options is selected. so far I have just got it working on a button push http://codepen.io/Irish1/pen/iwKam
html
<form>
<p>
<label for="select">
Goal Type
</label>
<select class="typeselect">
<option value=""></option>
<option value="body">
Body
</option>
<option value="strength">
Strength
</option>
<option value="distance">
Distance
</option>
</select>
<button class="toggle">push</button>
</p>
<div class="body">
<p>
<label for="body">
Body
</label>
</p>
</div>
<div class="strength">
<p>
<label for="strength">
Strength
</label>
</p>
</div>
<div class="distance">
<p>
<label for="distance">
Distance
</label>
</p>
</div>
</form>
css
.body {
display: none;
}
.strength {
display: none;
}
.distance {
display: none;
}
javascript
$('.toggle').click(function(){
$('.body').toggle();
});

Try
//dom ready handler
jQuery(function () {
//all the elements that has to be shown/hidden, it is cached for easy access later
var $targets = $('.body, .strength, .distance');
//chang handler for the select element
$('.typeselect').change(function () {
//hide previously displayed elements
$targets.hide()
//find the element with the selected option's value as class, if empty option is selected set it to an empty set
if (this.value) {
$('.' + this.value).show()
}
})
})
Demo: Fiddle
If you want to make the button handler work then
//dom ready handler
jQuery(function () {
//all the elements that has to be shown/hidden, it is cached for easy access later
var $targets = $('.body, .strength, .distance');
var $select = $('.typeselect');
//click handler for the button
$('.toggle').click(function (e) {
//prevent the default form action of the button click
e.preventDefault();
//hide previously displayed elements
$targets.hide()
//selected value
var val = $select.val();
//find the element with the selected option's value as class, if empty option is selected set it to an empty set
if (val) {
$('.' + val).show()
}
})
})
Demo: Fiddle

$('#typeselect').change(function(event) {
$('.target').hide();
var option = $(this).val();
if (option != "") $('.'+option).show();
});
and a few minor mods to the html
<form>
<p>
<label for="select">Goal Type</label>
<select id="typeselect" class="typeselect">
<option value=""></option>
<option value="body">Body</option>
<option value="strength">Strength</option>
<option value="distance">Distance</option>
</select>
</p>
<div class="body target">
<p><label for="body">Body</label></p>
</div>
<div class="strength target">
<p><label for="strength">Strength</label></p>
</div>
<div class="distance target">
<p><label for="distance">Distance</label></p>
</div>
</form>
You can view and edit here at codepen: http://codepen.io/anon/pen/ktesh

Give a name / Id to Select and Div's.
var x = document.getElementById("SelectId / Name").selected;
if(x==0) {
document.getElementById("body").style.display = "block";
} else {
\\ Similarly for other div to display on the basis of x
}

Try this:
$('.typeselect').change(function(){
$('div').hide();
if($(this).val() == ""){
$(this).children('option:first-child').show();
}
else
$('.' + $(this).val()).show();
});

Related

HTML - Create multiple forms out of one form template

I currently have multiple forms that are similar but have small changes. First, the user choses the form from a drop-down menu and then the form is shown below.
My forms looks like this.
Form 1
Customer Name
Phone Number
Address
Form 2
Customer Name
Is married?
Form 3
Customer Name
Social Security Number
Address
My code looks something like this.
<select onchange="changeOptions(this)">
<option value="" selected="selected"></option>
<option value="form1">f1</option>
<option value="form2">f2</option>
<option value="form3">f3</option>
</select>
<form class="className" name="form1" id="form1" style="display:none">
---form---
<form class="className" name="form2" id="form2" style="display:none">
---form---
<form class="className" name="form3" id="form3" style="display:none">
---form---
<script>
function changeOptions(selectEl) {
let selectedValue = selectEl.options[selectEl.selectedIndex].value;
let subForms = document.getElementsByClassName('className')
for (let i = 0; i < subForms.length; i += 1) {
if (selectedValue === subForms[i].name) {
subForms[i].setAttribute('style', 'display:block')
} else {
subForms[i].setAttribute('style', 'display:none')
}
}
}
</script>
Is there any way to create a 'main' form that has all the form elements and then specify which element to use in each form? The method I'm using right now works fine but there is too much repeated code and probably won't scale correctly if I try to make a change in one of the elements (since I would have to change each one of them and it will be easy to make mistakes)
You don't need three different forms, just have one form with all of the fields set as hidden. Then give each field a class matching which form that field should be shown. Then simply show the matching fields based on the selected value.
select_form = document.querySelector(".select_form");
fields = document.querySelectorAll(".field");
select_form.addEventListener("change", function() {
fields.forEach(function(el) {
el.style.display = "none";
});
show = document.querySelectorAll("." + this.value);
show.forEach(function(el) {
el.style.display = "block";
});
});
.field {
display: none;
}
<select class="select_form">
<option value="" selected="selected"></option>
<option value="form1">f1</option>
<option value="form2">f2</option>
<option value="form3">f3</option>
</select>
<form>
<div class="field form1 form2">ONLY form1 and 2</div>
<div class="field form3">ONLY form3</div>
</form>

make diffrence between objects that created with clone() in java script

Good Day Friends. I have a problem... Thanks, if you help me
I have a couple of inputs into a div. I copied that div with Clone function in java script (by click a button) and right now, I have two divs. but my problem:
1- I don't know, How can I get the values of inputs correctly (the input's names are the same)?
2- and I have a select input in div, that some inputs add or remove by choose each option of select input. Now after copied div, choose one option in div2, create changes in div1... and I don't want it !!
<div class="levels">
<div class="add_senario_level">
<span>Level 1</span>
<form>
<select name="condition" onchange="show_div(this,'shop during');">
<option selected="selected" disabled="disabled">choose condition</option>
<option>shop after registration</option>
<option>shop during</option>
</select>
<div id="shop_during" style="display:none;">
<input type="number" id="shop_during_num" name="shop_during_num" placeholder="Enter number">
<select id="shop_during_time" name="shop_during_time">
<option selected="selected">hour after registeration</option>
<option>day after registeration</option>
<option>week after registeration</option>
<option>month after registeration</option>
</select>
</div>
<div>
<button type="button" class="newLevel"> Add New Level </button>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function()
{
$(".newLevel").click(function()
{
$(".add_senario_level").clone().appendTo(".levels");
});
});
function show_div(obj, id)
{
txt = obj.options[obj.selectedIndex].text;
if (txt.match(id))
{
document.getElementById("shop_during").style.display = 'block';
}
else
{
document.getElementById("shop_during").style.display = 'none';
}
}
</script>
You can use jQuery's find function to find a child element and the attr function to get and set attribute values. You will want to do this to change on the id and name attributes for the input and select like below:
HTML
<input type="number" id="shop_during_num0" name="shop_during_num0" class="shop_input" placeholder="Enter number">
JavaScript
$(".newLevel").click(function()
{
const count = $('.add_senario_level').length;
const clone = $(`#add_senario_level${count - 1}`).clone();
const input = clone.find(`#shop_during_num${count - 1}`);
const select = clone.find(`#shop_during_time${count - 1}`);
input.attr('name', `shop_during_num${count}`);
input.attr('id', `shop_during_num${count}`);
select.attr('name', `shop_during_time${count}`);
select.attr('id', `shop_during_time${count}`);
clone.appendTo(".levels");
});
In the show_div method, you can use $(obj) to reference the select that called the function and show or hide the correct element with
$(obj).parent().find('#shop_during').css('display', 'block');

If a user selects a option from the select box, hidden div should appear

so I am trying to display a div if user select a specific option value from a select drop down list. for example, if the user selects "trade" in the select box then the div with the company name should come up while the div containing the "first name and last name" should disappear. and If the user selects the "customer" in the select box then the the opposite should happen. Here is my code
Javascript
var custDetails = document.getElementById('retCustDetails');
var tradeDetails = document.getElementById('tradeCustDetails');
var SelectMenu = document.getElementById('makeBooking');
if (makeBooking.value == trd) {
document.getElementById('tradeDetails').style.display = 'block';
document.getElementById('custDetails').style.display = 'none';
}
else {
document.getElementById('custDetails').style.display = 'block';
}
HTML
<section id="makeBooking">
<h2>Make booking</h2>
Your details
Customer Type:
<select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName">
</div>
You should be using an if / else if to handle the different values that the user could select - this also allows you to hide all the divs by default, if no valid selection is picked
You can use .addEventListener('change', function ()) on your Select element to call a function every time the value is updated, and then you can use this.value inside the function to access the selected element's value
Also, be sure that you're wrapping strings with ' or " - You were using makeBooking.value == trd, which is checking for a variable called trd, not the String 'trd' as you were aiming for
Finally, You could hide your divs by default using CSS, so that only the correct div is showing when selected
.custDetails {
display: none;
}
var custDetails = document.getElementById('retCustDetails');
var tradeDetails = document.getElementById('tradeCustDetails');
var SelectMenu = document.getElementById('makeBooking');
document.querySelector('select[name="customerType"]').addEventListener('change', function() {
if (this.value == 'trd') {
custDetails.style.display = 'none';
tradeDetails.style.display = 'block';
} else if (this.value == 'ret') {
custDetails.style.display = 'block';
tradeDetails.style.display = 'none';
} else {
custDetails.style.display = 'none';
tradeDetails.style.display = 'none';
}
});
.custDetails {
display: none;
}
<section id="makeBooking">
<h2>Make booking</h2>
Your details Customer Type:
<select name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename"> Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails">
Company Name <input type="text" name="companyName">
</div>
First, you had different names in your JavaScript than you had as ids in your HTML. You were also trying to work with the section element instead of the select element.
After that, you need to set up an event handling function to handle when the select gets changed.
Also, instead of working with inline styles. It's much simpler to set up a CSS class and then just add or remove it.
Finally, don't use an HTML heading element (h1...h6) because of the formatting applied to it. Formatting is done with CSS. Choose the right heading because it makes sense. You can't have the first heading in a section be an h2 because and h2 is for a subsection of an h1. The first heading in any section should always be h1.
See comments inline:
var custDetails = document.getElementById('retCustDetails');
var tradeDetails = document.getElementById('tradeCustDetails');
// You must get a reference to the <select> element
var selectMenu = document.getElementById('customerType');
// Then, you must configure a JavaScript function to run as a "callback"
// to a specific event that the <select> element could trigger:
selectMenu.addEventListener("change", function(){
// The value of the select will be a string, so you must wrap it in quotes
if (selectMenu.value == "trd") {
// Now, just add or remove the pre-made CSS class as needed.
tradeDetails.classList.remove("hidden");
custDetails.classList.add("hidden");
} else {
tradeDetails.classList.add("hidden")
custDetails.classList.remove("hidden");
}
});
.hidden { display:none; }
<section id="makeBooking">
<h1>Make booking</h1>
Your details<br>
Customer Type:
<select name="customerType" id="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails hidden">
Forename <input type="text" name="forename">
Surname <input type="text" name="surname">
</div>
<div id="tradeCustDetails" class="custDetails hidden">
Company Name <input type="text" name="companyName">
</div>
</section>

Show Hidden Form Field with Jquery

I seem to be having an issue with Jquery not displaying a hidden DIV after a selected form value is chosen. When a user clicks yes, I want the hidden div to then be revealed. Am I missing something? You can take a look here https://jsfiddle.net/73merxk9/
Javascript
<script>
$(document).ready(function() {
$('#permit').on('permit', function() {
$("#hiddenform").toggle($(this).val() == 'Yes');
}).trigger('permit');
});
</script>
Form
<div>
<label for="permit">Permit</label>
<select id="permit" name="permit">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div id="hiddenform">
<div>
<label for="permit_submitted">Permit Submitted</label>
<input placeholder="Permit Input Here..." name="job_number" type="text" id="job_number">
</div>
</div>
There is no such event "permit". You need to listen onchange event instead. Then you need to compare select value with "1" because Yes is a label, not value:
$(document).ready(function () {
$('#permit').on('change', function () {
$("#hiddenform").toggle($(this).val() == '1');
}).trigger('change');
});
Demo: https://jsfiddle.net/73merxk9/1/

Hide elements using jquery based on option select

I have two forms and a selector.
This is my code --
<select>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<form id="pp">
<input type="text">
</form>
<form id="cc">
<input type="text">
</form>
Now if option 1 is selected i want to hide form CC. if 2 hide form PP.
How do i do it with js or jquery? thanks
Try this (using jQuery):
$("select").bind("change", function() {
if ($(this).val() == "1") {
$("#pp").show();
$("#cc").hide();
}
else if ($(this).val() == "2") {
$("#pp").hide();
$("#cc").show();
}
});
Additionally, you could hide both forms using .hide() as shown above before the user selects any option.
bind is attaching an event handler to the "change" event of the select box. This is fired when the user changes what option is selected.
Inside the handler, val is used to determine the value of the currently selected option.
show() and hide() are used on the correct forms, depending on which option was selected.
Working example: http://jsfiddle.net/andrewwhitaker/faqZg/
<script>
function Hide(val)
{
if(val==1)
{
document.getElementById('cc').style.display='none';
document.getElementById('pp').style.display='inline';
}
if(val==2)
{
document.getElementById('pp').style.display='none';
document.getElementById('cc').style.display='inline';
}
}
</script>
<select onchange="Hide(this.value);">
<option value="">Please Select</option>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<div id="pp">
<input type="text">
</div>
<div id="cc">
<input type="text">
</div>

Categories

Resources