JavaScript hiding and showing form elements - javascript

Options:
<select id="selectOption" name="Option">
<option value="">Choose Option</option>
<option value="option1">1</option>
<option value="option2">2</option>
</select>
<div id="option1" class="">
//form element here//
</div>
<div id="option2" class="">
//form element here//
</div>
My question is, using JavaScript, how do make it so that at the start you don't see the 2 divs at the bottom? When you choose option 1, it should only show the first div and if you choose option2 it shows the second div.

You can do it like:
<select id="selectOption" name="Option" onchange="optionSelect()">
<option value="">Choose Option</option>
<option value="option1">1</option>
<option value="option2">2</option>
</select>
<div id="option1" style="display:none">
DIV1
//form element here//
</div>
<div id="option2" style="display:none">
DIV2
//form element here//
</div>
Then in script:
function optionSelect(){
var e = document.getElementById("selectOption");
var strUser = e.options[e.selectedIndex].value;
document.getElementById(strUser).style.display = "block";
}
What i'm doing is listening for option change, whenever option is changing im getting its value and making the div with that option value visible display='block'
See the DEMO here

You can make both the divs hidden by default and trigger an onchange on the select.
In the javascript function, check the value and hide/show the corresponding div.
<select id="selectOption" name="Option" onchange='checkOption()'>
Javascript:
function checkOption() {
document.getElementsByTagName('div').style.display = 'none';
document.getElementById(document.getElementById('selectOption').value).style.display = 'block';
}

You could do it like this
<select id="selectOption" name="Option" onChange="showDiv(this)">
<option value="">Choose Option</option>
<option value="option1">1</option>
<option value="option2">2</option>
</select>
<div id="option1" class="" style="display:none;">
//form element here option 1//
</div>
<div id="option2" class="" style="display:none;">
//form element here option 2//
</div>
<script>
function showDiv(selectObj){
var valueSelected= selectObj.value;
// hide all div again
document.getElementById('option1').style.display = "none";
document.getElementById('option2').style.display = "none";
// show the selected
document.getElementById(valueSelected).style.display = "block";
}
</script>
The showDivfunction is called everytime you are selecting an option from the select.
In the function, it gets the value, since the value is the id of the div you can use it as the identifier.
First hide both div then display the selected, doing it when user selects the very first it will hide both.

algorithm to do what you've asked:
Initially hide all the divs
set the id's of div's equal to select option tag values
use onchange function of select tag and call a function
in that function hide all other divs and show corresponding div only.
Here is he jsbin.
http://jsbin.com/pewihumokunu/1/edit

Related

How do I change select to input text while checkbox is checked?

It's my first contact with js so please don't hate me
I have something like this:
function Zmiana(isChecked) {
document.getElementById('test').type = 'text';
}
<div class="dropdown">
<select id="test" name="producent" class="dropdown-select">
<option value="Apple">Apple</option>
<option value="Samsung">Samsung</option>
<option value="Lenovo">Lenovo</option>
</select> <br>
</div>
But it doesn't work
You won't be changing the select into a textbox. Instead, you'll have both a select and a textbox. The checkbox will simply determine which is shown.
Also, your select should include a first choice that is not considered valid so that you don't get a submitted value that the user didn't choose.
.hidden { display:none; }
<input type="checkbox" id="check">Check to enter text directly
<div class="dropdown">
<select id="test" name="producent" class="dropdown-select">
<option value="">--- Choose ---</option>
<option value="Apple">Apple</option>
<option value="Samsung">Samsung</option>
<option value="Lenovo">Lenovo</option>
</select>
<input id="data" class="hidden">
</div>
<script>
let text = document.getElementById('data');
let check = document.getElementById("check");
let select = document.getElementById("test");
// You must set up your function to handle the
// click event of the checkbox
check.addEventListener("click", Zmiana);
function Zmiana(){
// Add or remvoe the hidden class based on
// whether it's already in use
select.classList.toggle("hidden");
text.classList.toggle("hidden");
}
</script>

Set class from <select> if selected option contains ID='answer' in HTML/JavaScript (JQuery)

I am completely new to HTML and JQuery, and I can't figure out how I can set a class for my select element if the currently selected option has an ID="answer". I want to do this to check if the multiple choice question is correct.
If this is impossible to do this in JQuery, JavaScript would also be fine. I just want to prevent making a DataBase query and thought that JQuery would be the best route to take.
This is the current html section that I have:
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class" id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
When I click the button it runs a Javascript function called: "checkAnswers()".
This function should check if the option that is selected in the dropdown box, has an id="answer". In this case, that would be if option one is selected. And if that option is selected, I want the background color of the select element to change.
How would I go about checking the currently selected dropdown options' ID? And how do I do this for more than 1 question at a time?
And how would I add a class programaticly in JavaScript to that select element so it can change BG color?
This is what I tried in JavaScript:
var s = document.getElementsByClassName("select-class");
var idSelectedOption = s[s.selectedIndex].id;
alert(idSelectedOption);
But that returns an error: "Uncaught TypeError: Cannot read property 'id' of undefined"
I think that is because it returns an array from all classes. How would I go about checking every single one of them? And changing the background colors of the ones that have the correct option selected?
Thanks in advance,
Mats.
Use data-* attributes instead of id as you should not have multiple elements having same id value in a document.
getElementsByClassName will return nodelist hence you need to iterate through elements and then apply conditions accordingly. Array.prototype.forEach.call is used in example below to iterate through elements.
Try this:
function checkAnswers() {
var s = document.getElementsByClassName("select-class");
Array.prototype.forEach.call(s, function(elem) {
var idSelectedOption = elem[elem.selectedIndex].getAttribute('data-id');
if (idSelectedOption == 'answer') {
var selectedAnswer = elem[elem.selectedIndex].getAttribute('value');
alert(selectedAnswer);
}
});
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question</label>
<select class="form-control select-class">
<option value="1" class="ans-class" data-id="answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question</label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class" data-id="answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary" onclick="checkAnswers()">Check</button>
</form>
Fiddle here
You can't have two elements with the same id. Use a custom data attribute or a class instead
After fixing that, this code should to the trick. I tried to use vanilla JavaScript since you didn't indicate using jQuery.
// Lazy: Bind the event to the form.
document.getElementById('ansForm').addEventListener('change', function(event) {
var selectElement = event.target;
// Only respond if the clicked element is one of the selects.
if (selectElement.classList.contains('select-class')) {
// Get the option that is currently selected.
var selectedOption = selectElement[selectElement.selectedIndex];
// Check if this option contains the class 'answer'.
var isAnswerSelected = selectedOption.classList.contains('answer');
console.log(isAnswerSelected);
// Remove the indicators. You could easily use classList.toggle, but the second
// argument is not supported in IE.
// selectElement.classList.toggle('right', isAnswerSelected);
// selectElement.classList.toggle('wrong', !isAnswerSelected);
// So, second best. Just remove both and re-add the class we want.
selectElement.classList.remove('right');
selectElement.classList.remove('wrong');
selectElement.classList.add(isAnswerSelected?'right':'wrong');
} else {
// Ignore clicks on any other element.
}
});
.right {
color: green;
}
.wrong {
color: red;
}
<form id="ansForm" class="testClass1">
<div id="QuestionForm" name="QuestionForm">
<label>Question 1: This is a question </label>
<select class="form-control select-class">
<option value="1" class="ans-class answer">Answer1</option>
<option value="2" class="ans-class">Answer2</option>
<option value="3" class="ans-class">Answer3</option>
<option value="4" class="ans-class">Answer4</option>
</select>
<label>Question 2: This is another question </label>
<select class="form-control select-class">
<option value="1" class="ans-class">Another Answer</option>
<option value="2" class="ans-class">Just some text</option>
<option value="3" class="ans-class answer">Test</option>
<option value="4" class="ans-class">Test2</option>
</select>
</div>
<button type="button" class="btn btn-primary"
onclick="checkAnswers()">Check</button>
</form>
Try this for jQuery approach,
$(function(){
// This will bind 'click' event handler to element with id 'checkBtn'
$('#checkBtn').on('click', function(){
// This gets all selects element which has class containing 'select-class'.
var $selects = $('select.select-class');
// Iterate all the selects element.
$selects.each(function(k, v){
// Get the option for this current select element which has an id of 'answer'.
var $selectAnswerOpt = $(this).children('option#answer');
// Get the value attribute of the option element.
var answer = $selectAnswerOpt.attr('value');
// Get the selected value for the select element.
var selectedValue = $(this).val();
// Checking if the selected value for the select element is the option that has an id of 'answer'
if (selectedValue == answer)
{
// If the selected value has the id of 'answer'
$(this).css('background-color', 'green');
}
else
{
// Else
$(this).css('background-color', 'yellow');
}
});
});
});
And the FIDDLE

What is a better way to use less code to hide and display select menu content? javascript

UPDATE The option values are not incremental, does that matter? Eg. one option could be apples, the next could be dog
I have multiple drop down menus with multiple options and every time I select an option I display different information but in order to hide it to display a different option's information, I have to compare the current option's value and if it matches, hide it, then show the new option's information.
As an example:
drop-down select menu
<select name="name_of_select_menu" onchange="showContent(value);">
<option value="">label option</option>
<option value="apple">apple</option>
<option value="dog">dog</option>
<option value="shoes">shoes</option>
</select>
javascript
<script type="text/javascript">
function showContent($i) {
if($i=="apple"){
document.getElementById('apple').style.display = "inline-block";
document.getElementById('dog').style.display = "none";
document.getElementById('shoes').style.display = "none";
}
if($i=="apple"){
document.getElementById('apple').style.display = "none";
document.getElementById('dog').style.display = "inline-block";
document.getElementById('shoes').style.display = "none";
}
if($i=="apple"){
document.getElementById('apple').style.display = "none";
document.getElementById('dog').style.display = "none";
document.getElementById('shoes').style.display = "inline-block";
}
}
content to be displayed
<div class="content">
<div id="apple">
<p>
I am an apple
</p>
</div>
<div id="dog">
<p>
I am a dog
</p>
</div>
<div id="shoes">
<p>
I am a pair of shoes
</p>
</div>
</div>
As you can see, this can become a lot... I have like 20 options for one menu... 19 things to check if open and close, then open the actual one that you want to see.
Update:
function showContent(i) {
$(".content>div").hide(); //for arbitrary keywords.
$('div#' + i).css("display", "inline-block");
}
Change the function to:
function showContent(i) {
$("[id*=option]").hide();
$('#' + i).css("display", "inline-block");
}
Read more about attribute selectors
use below code. Check working DEMO
JQUERY
$(document).ready(function(){
$('.content div').hide();
$(document).on('change','select[name="name_of_select_menu"]',function(){
$('.content div').hide();
$('#'+$(this).val()).show();
});
});
HTML
<select name="name_of_select_menu">
<option value="">label option</option>
<option value="apple">apple</option>
<option value="dog">dog</option>
<option value="shoes">shoes</option>
</select>
<div class="content">
<div id="apple">
<p>
I am an apple
</p>
</div>
<div id="dog">
<p>
I am a dog
</p>
</div>
<div id="shoes">
<p>
I am a pair of shoes
</p>
</div>
</div>
Using jquery, you can write:
function showContent(i)
document.getElementById(i).style.display = "inline-block";
$("select[name=name_of_select_menu]").find("option").not("option[id=="+i+"]").hide();
}
jsFiddle (Updated)
You can simplify this in a few different ways. Move the change handler out of the HTML and bind to the DOM element directly from your JS. Then capture the value of the form element dynamically, and use that to determine which element to show.
Since you're toggling the visibility of the elements, you need a way to hide all of the elements at once. You can do this using$('.content > div').hide() to hide all of the elements and then $('#yourId').show() to show a specific one.
HTML:
<select name="name_of_menu">
<option value="">label option</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
JS (using jQuery):
$(function () {
$('[name="name_of_menu"]').change(function () {
$('.content > div').hide();
$('#' + $(this).val()).css("display", "inline-block");
});
});

force Select option to default on page load

I have a select box that uses JS to hide/show divs based on selection. The challenge I have is that when the page is reloaded it defaults to the last selection (and no associated div) rather than the default.
CSS:
#div1,#div2,#div3 {
display: none
}
JS:
function showHide(elem) {
if(elem.selectedIndex != 0) {
//hide the divs
for(var i=0; i < divsO.length; i++) {
divsO[i].style.display = 'none';
}
//unhide the selected div
document.getElementById('div'+elem.value).style.display = 'block';
}
}
window.onload=function() {
//get the divs to show/hide
divsO = document.getElementById("frmMyform").getElementsByTagName('div');
}
HTML:
<form action="#" method="post" id="frmMyform">
<select name="selMyList" onchange="showHide(this)">
<option value="">Select an option</option>
<option value="1">Show div 1</option>
<option value="2">Show div 2</option>
<option value="3">Show div 3</option>
</select>
<div id="div1">This is Div 1</div>
<div id="div2">This is Div 2</div>
<div id="div3">This is Div 3</div>
</form>
I tried setting #div0 to hidden and then adding it to the list of divs but it does'nt seem to work. Also tried using jquery but this is a WordPress site and one of the plugin's interferes with this functionality. This is very close to working perfectly, but just need to resolve this weirdness.
Any ideas?
Try to use selected attribute for option tag:
<select name="selMyList" onchange="showHide(this)">
<option value="" selected="selected">Select an option</option>
<option value="1">Show div 1</option>
<option value="2">Show div 2</option>
<option value="3">Show div 3</option>
</select>

How do I select a specific option value from a drop down list to show a hidden div?

I have a drop down list that has 4 options, so what I want is when I click on the value "from" it shows a hidden div (used CSS to hide this div "display: none;"). anyone can help me with that? THANKS!
Html:
<select id="type">
<option value="">--select--</option>
<option value="category">Category</option>
<option value="brand_name">Brand</option>
<option value="campaign_name">Campaign</option>
<option value="from">Recap date</option>
</select>
</label>
<div id="showfrom">
<input type="text" class="filter" value="02-16-2012" id="from">
</div>
Js:
$("#type").change(function() {
var selected = $(this).find(':selected').val();
if (selected == from) {
$("#showfrom").show();
}
});
from should be a string literal. Also you need to hide if something else is selected so better if you can use .toggle()
$("#type").change(function () {
$("#showfrom").toggle(this.value == 'from');
}).change();//to set the initial state
Demo: Fiddle

Categories