I have a variety of divs with form fields. Based on a drop-down list, i need it to display the div corresponding to that value, and hide all the other divs. (Perhaps there's a more efficient way to even do that, rather than load all the divs and just hide them, i'm not sure).
What I have right now is this:
<select id="group" name="group">
<option></option>
<option value="8">Testing This Stuff</option>
<option value="9">Testing Other Stuff</option>
</select>
<div id="8" style="display:none;">**form fields**</div>
<div id="9" style="display:none;">**different form fields**</div>
And the current, semi-working javascript:
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.selectedIndex;
document.getElementById(id).style.display = 'block';
}
}
</script>
What i'm getting is 'id' is null, so i haven't been able to work past that part yet.
Part 2 would be hiding the old div and displaying the new div (if they were to change the option selected). Any suggestions?
Solution:
<script type="text/javascript">
window.onload = function() {
var current;
var eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}
</script>
<select id="materialsgroup" class="formInput" name="materialsgroup">
<option value=""></option>
<option value="groupid_8">Testing This Stuff</option>
<option value="groupid_9">Testing Other Stuff</option>
</select>
<div id="groupid_8">**form fields**</div>
<div id="groupid_9">**more form fields**</div>
To make the select and divs, this is what I've done:
foreach($groups as $key=>$value)
{
$valueItem = "groupid_".$value['group_id'];
$text = $value['title'];
$htmlString .= sprintf('<option value="%s">%s</option>', $valueItem, $text);
}
echo '<tr>
<td class="formLabelCell">Group</td>
<td class="formInputCell">
<select id="group" class="formInput" name="group">'.$htmlString.'</select></td></tr>';
foreach($groups as $gkey=>$gvalue)
{
echo '<div id=groupid_'.$groups[$gkey]['group_id'].' style="display:none;">';
//**Draw the form stuff here**
echo '</div>';
}
Try using
var id = eSelect.value;
For the second part, if you are using pure javascript (I mean, you're not using a javascript framework like jQuery) maybe a good solution is to load an array containing the div's ids and iterate it, hiding the div != eSelect.value
var arrDivs = new Array("1","2","3");
for (var i=0; i < arrDivs.length; i++) {
if (arrDivs[i] == eSelect.value)
document.getElementById(arrDivs[i]).style.display = 'block';
else
document.getElementById(arrDivs[i]).style.display = 'none';
}
I'm a javascript novice myself, but what about using a current variable to show which div is shown (and therefore knowing which div to hide)?
window.onload = function() {
var current, eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}
window.onload = function() {
var current, eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}
Related
I created a Select Element which creates Checkbox dropdown elements based on the items on the Google sheet.
Here is my HTML code:
<div class="form-row">
<div class="multiselect form-group">
<div class="selectBox" onclick="showCheckboxes()">
<select class="form-control" >
<option>Select an option</option>
</select>
<div class="overSelect" ></div>
</div>
<div id="checkboxes">
</div>
</div>
Here is my javascript code:
<script>
document.addEventListener("DOMContentLoaded", afterLoad);
document.getElementById("checkboxes").addEventListener("change", loadDisplayPos);
function afterLoad(){
google.script.run.withSuccessHandler(loadPosApp).checkPosApp();
}
function loadPosApp(postOpen){
postOpen.forEach(function(r){
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = r[0];
var label = document.createElement('label')
label.appendChild(checkbox);
label.appendChild(document.createTextNode(" " + r[0]));
var content = document.getElementById('checkboxes');
content .appendChild(label);
});
}
function loadDisplayPos(){
var contentCheck = document.getElementById('checkboxes').value;
console.log(contentCheck);
}
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
</script>
Here is my Google Apps Script function:
function checkPosApp()
{
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName("VacantPositions_Data");
//const myDates = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
var postOpen = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
Logger.log(postOpen)
return postOpen;
}
Upon the load of the Web App, it will load the values from the Google sheet to the Web App as dropdown checkboxes. My problem is how to display the checked items to the Select Element as selected. I tried to get the value of the element ID "checkboxes" but it says undefined. Do you have any suggestions or advice? I am still trying to look for a solution. Thank you in advance for the help.
I got the idea on how to answer my problem in this link: https://www.dyn-web.com/tutorials/forms/checkbox/group.php. I just modified it in a way that I could get all the checked/ selected in an array then display it in the Web App
Here is the modified function in javascript.
function loadDisplayPos(){
var element = document.getElementById('checkboxes');
var tops = element.getElementsByTagName('input');
var tags = [];
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
if (tops[i].checked){
tags.push( tops[i].value);
}
}
}
var selectedPost = document.getElementById('posapp').innerHTML= tags;
}
not sure the title makes sense, but I have the code bellow to hide/show some fields when we select a yes/no radiobutton
<div class="container" style="width:100%;margin-top:2%">
#if (Model != null)
{
using (Html.BeginForm("NextButton_Click", "Questionnaire", FormMethod.Post))
{
<table class="table table-hover">
<tbody>
#for (int i = 0; i < Model.QuestionsPaging.Count(); i++)
{
...
<tr>
<td>
<p>
#Html.RadioButtonFor(n => n.QuestionsAnswers[index].HasAnswer, false, new { #radioIndex = i, #onchange = "CallChangefunc(this)" }) #Html.Label("No")
#Html.RadioButtonFor(n => n.QuestionsAnswers[index].HasAnswer, true, new { #radioIndex = i, #onchange = "CallChangefunc(this)" }) #Html.Label("Yes")
</p>
<div id="div_questions_#i" style="display:none">
...
</div>
</td>
</tr>
}
</tbody>
</table>
}
}
<script type="text/javascript">
function CallChangefunc(myRadioButton) {
var divName = "div_questions_" + myRadioButton.getAttribute("radioIndex");
var divElement = document.getElementById(divName);
if ($(myRadioButton).val().toLowerCase() === "true") {
if (divElement.style.display != 'inline') {
divElement.style.display = 'inline';
}
} else {
if (divElement.style.display != 'none') {
divElement.style.display = 'none'
}
}
}
</script>
The code works fine, I click the radiobutton and it hides/shows the divs as expected. The problem I'm having is that when I load the form it selects the RadioButton as expected but the event 'onchange' doesn't get triggered, so I have all fields hidden even with some radiobuttons set to yes.
I don't have too much experience in web, not sure how can I fix it, I've tried some stuffs but didn't work, any help is welcome.
Thank you.
Solution: Thanks #jom
I added " $(':radio[id^="QuestionsAnswers"]').trigger('change');" and checked if the radiobutton is checked, because ".trigger('change')" trigger the event for every radiobutton, now I have:
<script type="text/javascript">
$(document).ready(function () {
$(':radio[id^="QuestionsAnswers"]').trigger('change');
});
function CallChangefunc(myRadioButton) {
var divName = "div_questions_" + myRadioButton.getAttribute("radioIndex");
var divElement = document.getElementById(divName);
if ($(myRadioButton).val().toLowerCase() === "true" && myRadioButton.checked) {
if (divElement.style.display != 'inline') {
divElement.style.display = 'inline';
}
} else if ($(myRadioButton).val().toLowerCase() === "false" && myRadioButton.checked) {
if (divElement.style.display != 'none') {
divElement.style.display = 'none'
}
}
}
</script>
Do this on either $(document).ready or before the closing </body> tag.
$(':radio[id^="QuestionsAnswers"]').trigger('change');
// Or attach the handlers by script instead of going through Razor engine
$(':radio[id^="QuestionsAnswers"]').change(function () {
CallChangefunc(this);
});
Add $(document).ready before function CallChangefunc(myRadioButton)
Every time a selection is made from a dropdown menu, specific data is pulled from facebook and added to different divs. I am trying to update the contents of the div every time a different selection is made, however at the minute, the contents are just appended on after the initial contents.
This is the code that gets data based on a selection and creates the list from the returned data
<script>
city = document.getElementById("citySelection")
city.addEventListener("change", function() {
var selected = this.value;
var eventsList = document.getElementById("events");
if (selected == "None") {
eventsList.style.display = "none";
} else {
eventsList.style.display = "block";
};
if (selected == 'Bristol') {
getBristolEvents();
};
if (selected == 'Leeds') {
getLeedsEvents();
};
if (selected == 'Manchester') {
getManchesterEvents();
};
if (selected == 'Newcastle') {
getNewcastleEvents();
};
});
function createList(response, listId) {
var list = document.createElement('UL')
for (var i = 0; i < 10; i++) {
var events = response.data[i].name
var node = document.createElement('LI');
var textNode = document.createTextNode(events);
node.appendChild(textNode);
list.appendChild(node)
listId.appendChild(list);
}};
</script
This is the div being targeted:
<html>
<div id="events" style="display: none">
<div id="eventsDiv" style="display: block">
<div id="eventsListOne">
<h3 id='headerOne'></h3>
</div>
<div id="eventsListTwo">
<h3 id='headerTwo'></h3>
</div>
<div id="eventsListThree">
<h3 id='headerThree'></h3>
</div>
</div>
</div>
</div>
</html>
I have tried resetting the innerHtml of the div every time the function to get the data from facebook is called:
<script>
function getEventsThree(fbUrl, title) {
var listId = document.getElementById('eventsListThree');
var headerThree = document.getElementById('headerThree');
listId.innerHtml = "";
headerThree.append(title)
FB.api(
fbUrl,
'GET', {
access_token
},
function(response) {
listId.innerHtml = createList(response, listId)
}
)};
</script>
However, that still doesn't reset the contents of the div.
I've looked at other response but they all use jquery which I am not using.
Can anyone advise on the best way to fix this? Thanks.
I think your Hennessy approach is fine. Generate the inner content, then set .innerHTML.
At least one of your problems, maybe the only one, appears to be that you set .innerHTML to the return value of createList, but that function does not return anything.
Searched the internet. Learnt how to do this. Implemented it. But it doesn't work.
I want to show the div student when student is selected and the div teacher when teacher is selected. This is a part of a jsp file.
HTML code :
<table>
<tr>
<td>
<select id="userType">
<option value="student">STUDENT</option>
<option value="teacher">TEACHER</option>
<option value="admin">ADMIN</option>
</select>
</td>
</tr>
<table>
Javascript code:
<script type="text/javascript">
var elem = document.getElementById('userType');
elem.onchange = function() {
var studentDiv = document.getElementById('student');
var teacherDiv = document.getElementById('teacher');
studentDiv.style.display = (this.value.equals("student")) ? 'block':'none';
teacherDiv.style.display = (this.value.equals("teacher")) ? 'block':'none';
};
</script>
I've been trying to get this right since morning. Tried other methods as well. Nothing works. What am I doing wrong?
Change equals to == in your code and it works DEMO
var elem = document.getElementById('userType');
elem.onchange = function() {
var studentDiv = document.getElementById('student');
var teacherDiv = document.getElementById('teacher');
studentDiv.style.display = (this.value == "student") ? 'block' : 'none';
teacherDiv.style.display = (this.value == "teacher") ? 'block' : 'none';
};
You may get value of selected option like below:
JSFIDDLE
<script type="text/javascript">
var elem = document.getElementById('userType');
elem.onchange = function() {
var studentDiv = document.getElementById('student');
var teacherDiv = document.getElementById('teacher');
studentDiv.style.display = this.options[this.selectedIndex].value == "student" ? 'block':'none';
teacherDiv.style.display = this.options[this.selectedIndex].value == "teacher" ? 'block':'none';
};
</script>
try this
studentDiv.style.display = (this.value==="student") ? 'block':'none';
teacherDiv.style.display = (this.value==="teacher") ? 'block':'none';
Two problems immediately pop out:
You are trying to select items that do not have id's defined.
You are calling a non-existent ".value" on the element value property.
These errors will be reported in your browser developer tools. Use them.
JavaScript
function displayContent()
{
var 1 = getElementById(1);
var 2 = getElementById(2);
var 3 = getElementById(3);
var 4 = getElementById(4);
if(document.form.list.selectedIndex==0) {
1.style.display = "block";
}
if(document.form.list.selectedIndex==1) {
2.style.display = "block";
}
if(document.form.list.selectedIndex==2) {
3.style.display = "block";
}
if(document.form.list.selectedIndex==3) {
4.style.display = "block";
}
}
HTML
<form id="form">
<select onchange="displayContent();" id="list">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</form>
<div id="1">Content1</div>
<div id="2">Content2</div>
<div id="3">Content3</div>
<div id="4">Content4</div>
This is the script and markup that I have put together. I've tried a few different ways before this but all of them result in the same non-solution, just like this one. Nothing happens when I change the option in the select box. Have I missed something?
By default, all the divs are set to display:none;.
Thanks,
Jo
There are several issues with your code, including missing document. from getElementById, not giving your form or select elements a name attribute so you can reference them in js, attempting to create a variable which begins with an integer and having id attributes which begin with integers.
With all that in mind, try this:
function displayContent() {
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
var div3 = document.getElementById("div3");
var div4 = document.getElementById("div4");
if(document.form.list.selectedIndex==0) {
div1.style.display = "block";
}
if(document.form.list.selectedIndex==1) {
div2.style.display = "block";
}
if(document.form.list.selectedIndex==2) {
div3.style.display = "block";
}
if(document.form.list.selectedIndex==3) {
div4.style.display = "block";
}
}
Example fiddle
Also note that this can be massively simplified:
function displayContent() {
document.getElementById("div" + (document.form.list.selectedIndex + 1)).style.display = "block";
}
Example fiddle
instead of
getElementById
use
document.getElementById('1');
document.getElementById('2');
document.getElementById('3');
document.getElementById('4');