Javascript seems not to be working on mobile - javascript

I have a text toggle option on my (WordPress) website:
If you click on the red "info" link on the right the text under it opens. The problem is that it doesn't seem to work on mobile (iPhone 4). See the screenshot attached. It seems to me the javascript is not loading at all or just not working?
html link:
<div id="<?php the_ID(); ?>" class="projectTitel">
<?php the_title( sprintf( '<h2 class="entry-title"><button rel="bookmark" class="show">', esc_url( get_permalink() ) ), '<div class="info">Info ↓</div><div class="close_info">X</div></button></h2>' ); ?>
</div>
javascript code:
<script type="text/javascript">
var divs = document.getElementsByClassName("projectTitel");
[...divs].forEach(someDiv => someDiv.addEventListener("click", handler));
// by default, all Inhoud divs are hidden
hideElements("Inhoud");
hideElements("close_info");
jQuery('.info').show();
function handler(event) {
// get the clicked project's index :
var projectIndex = getClickedProjectIndex(event);
// toggle the right Inhoud div :
toggleDiv(document.getElementsByClassName("Inhoud")[projectIndex]);
toggleDiv(document.getElementsByClassName("close_info")[projectIndex]);
toggleDiv(document.getElementsByClassName("info")[projectIndex]);
}
// hide all elements that have the provided class name
function hideElements(className) {
var elements = document.getElementsByClassName(className);
[...elements].forEach(element => element.style.display = "none");
}
function getClickedProjectIndex(event) {
var elements = document.getElementsByClassName("projectTitel");
var projectIndex = 0;
[...elements].forEach((element, index) => {
if (element.id == event.currentTarget.id) {
projectIndex = index;
}
});
return projectIndex;
}
function toggleDiv(element) {
if (element.style.display === 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
</script>

Replace "[...divs]" on "Array.from(divs)"
And do it for all other instances of [...{a}].

Related

How to make link sharing in php

Videos come from a folder and are automatically displayed on my website. But I am having a problem at implementing share feature. All I want to do is when share button is pressed, video's whole path like https:\\example.com\vid.mp4 should show up. I tried but it just shows the location of very last video on my page.
My php:
$exten = '.mp4';
$dir = __DIR__ . DIRECTORY_SEPARATOR . "gallery" . DIRECTORY_SEPARATOR;
$videos = glob("$dir*.{mp4}", GLOB_BRACE);
$alt = glob("$dir*.{webm,mp4,ogg}", GLOB_BRACE);
if (count($videos) > 0) { foreach ($videos as $vid) {
$base = basename($vid,'.mp4');
printf("<div class='vi'><video src='gallery/%s' id='basename($vid,'.mp4')' loop='loop'></video>", rawurlencode(basename($vid)));
echo '<div class="sh"><button class="share" onclick="phprun()">SHARE</button></div>' ;
echo "<div class='title'>".basename($vid,'.mp4')."</div></div>";
}}
?>
My js:
var result ="<?php echo('http://victure.freecluster.eu/gallery/'.basename($vid)); ?>"
const copy = document.getElementById("copy");
const h1 = document.getElementById("h1");
const h2 = document.getElementById("h2");
function phprun(){
if (copy.style.display === "none") {
copy.style.display = "block";
} else {
copy.style.display = "none";
}
h1.innerHTML="SHARE: "+"<?php echo(basename($vid,'.mp4')); ?>";
h2.innerHTML=result;
// alert(result)
}
It makes a div appear with video's path but it is showing the path of only one video.
Note:
Keep in mind it is automated.
In short:
How to display path of each video?
You can see working problem here:
Problem
Thanks in advance:)
What you need is to get the onclick target (like explained here) in order to make your content dynamic.
1. 'onclick' event: pass the 'this' parameter to your function phprun(). For an event, 'this' as a parameter refers to the target of the event (the div on which the event has been fired).
<div class="vi">
<video src="..." id="..." loop="..."></video>
<div class="sh">
<button class="share" onclick="phprun(this)"> // <-----(GET THE EVENT TARGET)
<svg class="..."></svg>
</button></div>
<div class="title">Demo from ShazamBolt8</div>
</div>
2. In your function: inject the event target ( phprun(target){...} ) then use it in your logic. Example of code for your function:
function phprun(target) { // <-----( INJECT THE EVENT TARGET)
// get the video element from the target
let videoEl = target.parentNode.parentNode.childNodes[0];
// retrieve the data you want (eg. the video url and title)
let videoUrl = videoEl.getAttribute('src');
let videoTitle = videoEl.documentQuerySelector('.title');
// inject it into the desired containers
h1.innerHTML = 'Share:' + videoTitle;
h2.innerHTML = videoUrl;
// do more stuff...
if (copy.style.display === "none") {
copy.style.display = "block";
} else {
copy.style.display = "none";
}
}

How to add strikethrough in the js tree according condition?

I have created a jsTree to show the folder pathname. My problem is how do I add a strikethrough according to the condition active or inactive in the JSTree ? Hope someone can guide me to solve this problem. Below is my code:
<?php
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$arr_sql5 = db_conn_select($folderData);
foreach ($arr_sql5 as $rs_sql5) {
$active = $rs_sql5['status'];
}
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
if($parentid == '0') $parentid = "#";
$selected = false;$opened = false;
if($row['id'] == 2){
$selected = true;$opened = true;
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $parentid,
"text" => $row['name'] . ' ' . "<span id='category'>". $row['category']."</span>",
"category" => $row['category'],
"state" => array("selected" => $selected,"opened"=>$opened)
);
}
?> -->
<!-- Initialize jsTree -->
<div id="folder_jstree" title=""></div>
<!-- Store folder list in JSON format -->
<textarea style="" id='txt_folderjsondata'><?= json_encode($folders_arr) ?></textarea>
<script style="text/javascript">
$(document).ready(function() {
var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());
$('#folder_jstree').jstree({
'core': {
'data': folder_jsondata,
'multiple': false
},
'plugins': ['sort'],
'sort': function(a, b) {
return this.get_text(a).localeCompare(this.get_text(b), 'en', {
numeric: true
});
}
});
var getColor = function(i) {
if (i >= 100 && i <= 199) {
return "blue";
} else if (i >= 200 && i <= 299) {
return "red";
} else if (i >= 300 && i <= 399) {
return "yellow";
} else if (i >= 400 && i <= 499) {
return "purple";
} else if (i >= 500 && i <= 599) {
return "green";
} else {
return "#000";
}
};
var colorNodes = function(nodelist) {
var tree = $('#folder_jstree').jstree(true);
nodelist.forEach(function(n) {
tree.get_node(n.id).a_attr.style = "color:" + getColor(parseInt(n.text.substr(0, 3), 10));
tree.redraw_node(n.id); //Redraw tree
colorNodes(n.children); //Update leaf nodes
});
};
$('#folder_jstree').bind('load_node.jstree', function(e, data) {
var tree = $('#folder_jstree').jstree(true);
colorNodes(tree.get_json());
});
$('#folder_jstree').bind('hover_node.jstree', function(e, data) {
$("#" + data.node.id).attr("title", data.node.original.category);
});
});
/* $(function() {
$(document).tooltip();
}); */
</script>
Inside json_encode($folders_arr) the content is:
[{"id":"1","parent":"#","text":"100 PENTADBIRAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"2","parent":"#","text":"200 PENGURUSAN TANAH & BANGUNAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":true,"opened":true}},{"id":"3","parent":"#","text":"300 PENGURUSAN ASET <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"4","parent":"#","text":"400 PENGURUSAN KEWANGAN <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"5","parent":"#","text":"500 PENGURUSAN SUMBER MANUSIA <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"6","parent":"1","text":"100-1 PERUNDANGAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"7","parent":"1","text":"100-2 PERHUBUNGAN AWAM <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"8","parent":"6","text":"100-1-1 PENGGUBALAN-PENYEDIAAN-PINDAAN UNDANG-UNDANG-PERATURAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"9","parent":"6","text":"100-1-2 KHIDMAT NASIHAT <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"10","parent":"8","text":"100-1-1-1 UNDANG-UNDANG KECIL KERJA DI JALAN 1996 <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"11","parent":"8","text":"100-1-1-2 UNDANG-UNDANG KECIL PERUNTUKAN MENGENAI LESEN BERSESAMA (MAJLIS PERBANDARAN) <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"12","parent":"8","text":"100-1-1-3 UNDANG-UNDANG KECIL MENGKOMPAUN KESALAHAN-KESALAHAN (MAJLIS PERBANDARAN KLANG), JALAN PARIT DAN <span id='category'>JTM (BERHUBUNG KOD 100-1\/1\/2)<\/span>","category":"JTM (BERHUBUNG KOD 100-1\/1\/2)","state":{"selected":false,"opened":false}},{"id":"13","parent":"9","text":"100-1-2-1 JABATAN PENGUATKUASAAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"14","parent":"9","text":"100-1-2-2 JABATAN BANGUNAN <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}},{"id":"15","parent":"7","text":"100-2-1 PUBLISITI, PROMOSI DAN PROTOKOL <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"16","parent":"15","text":"100-2-1-1 PUBLISITI DAN KENYATAAN MEDIA <span id='category'>JKP<\/span>","category":"JKP","state":{"selected":false,"opened":false}},{"id":"84","parent":"#","text":"201 HAHA <span id='category'>JTM<\/span>","category":"JTM","state":{"selected":false,"opened":false}}]
I want the condition such that if $active = 0 then it will show the strikethrough in the jsTree. Else if $active = 1 then it will back to normal.
Actually I want the actual output like the below sample picture. For the output below I just used Paint software to edit, easier to let you know what I want as the output:
My working JSFiddle code is here: https://jsfiddle.net/ason5861_cs/9x0dsotz/2/
Hope someone can guide me on how to add strikethrough according to the condition active or inactive into my code?
Note:$row['name'] and $row['category']needed to put strikethrough together if inactive.
With PHP you could have your conditional to set the value of a NULL variable to text-decoration that changes to line-through. This would be done with CSS. Simply have a conditional that checks if the value of $active is set to 0, if it is, then set the value of the null variable to display line-through. If the value of active is anything other than 0, then $strikeThrough will stay NULL and output nothing, therefor no change to text style that is wrapped in span tag.
$strikeThrough = null;
if($active = 0){
$strikeThrough = 'text-decoration: line-through;'
$output = "<span style='".$strikeThrough."'>" . $rs_wtpname . "</span>";
}
// no change needed for default Active
IN JS, you could use the #folder_jstree nodelist to run through your list and update there. Likely within your colorNodes function you could have a conditional there to check the value of status, then append css to your value if set to 0 (inactive).
If you are unable to get the status from PHP into JS, you could dump the value in the php code using the aforementioned method into an arbitrary data attribute or even alt attribute added to the #folder_jstree element span tag. Then retrieve that using JS and perform your conditional in JS.
EDIT: (April 25th, 2020)
Okay I think I see what you are doing with the JSON and your $folders_array now and how it is saving the data to be parsed in the JSON file.
Try the following code in your php and see if it works.
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$arr_sql5 = db_conn_select($folderData);
foreach ($arr_sql5 as $rs_sql5) {
$active = $rs_sql5['status']; //--> Here you are setting active state
}
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
if($parentid == '0') $parentid = "#";
$selected = false;$opened = false;
if($row['id'] == 2){
$selected = true;$opened = true;
}
//--> this would be the default state of active = 1 set in $output
$output = $row['name'] . ' ' . "<span id='category'>". $row['category']."</span>";
//--> Now we see if active is set to 0
if($active === 0){
//--> if active is set to 0 change the value of $output to reflect 'text-decoration'
$output = "<span style='text-decoration: line-through;'>" . $row['name'] . ' ' . "<span id='category'>". $row['category']."</span></span>";
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $parentid,
"text" => $output, //--> save the proper $output in our array
"category" => $row['category'],
"state" => array("selected" => $selected,"opened"=>$opened)
);
}

RadioButtonFor doesn't call onchange after load the page

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)

Javascript - How do i find the current number in a nodelist/querySelectorAll?

I am currently working on a vertical javascript image slider, i am trying to make it dynamic so that i can have more than 1 slider using the same code.. everything works fine except that i cant target the current wrapper..
How do i know which wrapper is currently being used?
I tried to browse the STO for a while but could only find some very old answers, we now have 2017 is there any real solution to this problem?
HTML/PHP which generates the sliders
<div class="profileCosplaysWrapper">
<div id="slideLeftVerticalSlider" class="slideLeftVerticalSlider"><div class="slideLeftVerticalIcon"></div></div>
<div id="slideRightVerticalSlider" clasS="slideRightVerticalSlider"><div class="slideRightVerticalIcon"></div></div>
<div id="profileCosplayImageWrapper" class="profileCosplayImageWrapper">
<?php
while ($stmt->fetch()) {
?>
<a class="profileCosplayInnerWrapper" href="index.php?page=cosplay&id=<?php echo $profileCosplayId; ?>">
<!--<div class="profileCosplayInnerWrapper">-->
<img class="profileCosplayImages" src="uploads/<?php echo $profileCosplays; ?>" alt="rate a cosplay latest 10 profile cosplays">
<!--</div>-->
</a>
<?php
}
$stmt->close();
?>
</div>
</div>
<div class="profileCosplaysWrapper">
<div id="slideLeftVerticalSlider" class="slideLeftVerticalSlider"><div class="slideLeftVerticalIcon"></div></div>
<div id="slideRightVerticalSlider" clasS="slideRightVerticalSlider"><div class="slideRightVerticalIcon"></div></div>
<div id="profileCosplayImageWrapper" class="profileCosplayImageWrapper">
<?php
while ($stmt->fetch()) {
?>
<a class="profileCosplayInnerWrapper" href="index.php?page=cosplay&id=<?php echo $profileCosplayRandomId; ?>">
<!--<div class="profileCosplayInnerWrapper">-->
<img class="profileCosplayImages" src="uploads/<?php echo $profileCosplaysRandom; ?>" alt="rate a cosplay latest 10 profile cosplays">
<!--</div>-->
</a>
<?php
}
$stmt->close();
?>
</div>
</div>
Javascript
var slideLeftVerticalSlider = document.querySelectorAll('.slideLeftVerticalSlider');
var slideRightVerticalSlider = document.querySelectorAll('.slideRightVerticalSlider');
var imagesWrapper = document.querySelectorAll('.profileCosplayImageWrapper');
var profileRightInterval;
var profileLeftInterval;
slideLeftVerticalSlider.forEach(function(e){
e.addEventListener('mouseover', profileMouseOverLeft, false);
});
slideRightVerticalSlider.forEach(function(e){
e.addEventListener('mouseover', profileMouseOverRight, false);
});
slideLeftVerticalSlider.forEach(function(e){
e.addEventListener('mouseout', function (e) {
clearInterval(profileLeftInterval);
});
});
slideRightVerticalSlider.forEach(function(e){
e.addEventListener('mouseout', function (e) {
clearInterval(profileRightInterval);
});
});
function profileMouseOverLeft(e) {
profileLeftInterval = setInterval(function () {
profileMoveLeft(0);
}, 7);
}
function profileMouseOverRight(e) {
profileRightInterval = setInterval(function () {
profileMoveRight(0);
}, 7);
}
function profileMoveLeft(currentSlider) {
imagesWrapper[currentSlider].scrollLeft += -5;
}
function profileMoveRight(currentSlider) {
imagesWrapper[currentSlider].scrollLeft += 5;
}
If you look at these functions i am passing "0" as a parameter, which ofcourse should be dynamic
function profileMouseOverLeft(e) {
profileLeftInterval = setInterval(function () {
profileMoveLeft(0);
}, 7);
}
function profileMouseOverRight(e) {
profileRightInterval = setInterval(function () {
profileMoveRight(0);
}, 7);
}
function profileMoveLeft(currentSlider) {
imagesWrapper[currentSlider].scrollLeft += -5;
}
function profileMoveRight(currentSlider) {
imagesWrapper[currentSlider].scrollLeft += 5;
}
You should be able to use this or the event target
function profileMouseOverLeft(e) {
console.log(this);
console.log(e.target);
}
based on your HTML using this and parentNode:
Array.from(document.querySelectorAll(".slideLeftVerticalSlider")).forEach( elem => elem.addEventListener("mouseover", left) )
Array.from(document.querySelectorAll(".slideRightVerticalSlider")).forEach( elem => elem.addEventListener("mouseover", right) )
function left (evt) {
var wrapper = this.parentNode.querySelector(".profileCosplayImageWrapper")
wrapper.style.backgroundColor = "red";
}
function right (evt) {
var wrapper = this.parentNode.querySelector(".profileCosplayImageWrapper")
wrapper.style.backgroundColor = "blue";
}
<div class="profileCosplaysWrapper">
<div id="slideLeftVerticalSlider1" class="slideLeftVerticalSlider"><div class="slideLeftVerticalIcon">L</div></div>
<div id="slideRightVerticalSlider1" clasS="slideRightVerticalSlider"><div class="slideRightVerticalIcon">R</div></div>
<div id="profileCosplayImageWrapper1" class="profileCosplayImageWrapper">
foo
</div>
</div>
<div class="profileCosplaysWrapper">
<div id="slideLeftVerticalSlider2" class="slideLeftVerticalSlider"><div class="slideLeftVerticalIcon">L</div></div>
<div id="slideRightVerticalSlider2" clasS="slideRightVerticalSlider"><div class="slideRightVerticalIcon">R</div></div>
<div id="profileCosplayImageWrapper2" class="profileCosplayImageWrapper">
foo
</div>
</div>
In your event handler you already have a reference to the element.
You can search the HTMLElementCollection to find the index of that element:
function getIndex(element) {
for(var i=0; i<slideLeftVerticalSlider.length;i++)
{
if (slideLeftVerticalSlider[i]===element) return i;
}
return -1;
}
The same method can be applied to any element collection.
You should also be giving every element on your page a unique id.

Hiding/displaying Divs onChange

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

Categories

Resources