JavaScript localStorage - Text input from Multiple User Cards - javascript

Please kindly let me know if this belongs in another thread.
I have a project involving user cards.
Objective:
1. add the ability to enter comments/tag in the provided text input for each user card.
2. save entered comments/tag using localStorage JavaScript.
3. saved comments/tag to be displayed in the user card where comments/tag was entered.
eg.
3 user cards, comments/tag entered on cards 1 & 3 only, onload tags comments/tag should appear on cards 1 & 3 only and card 2 will show placeholder or blank.
Problem:
If I enter a comment/tag on card 1, onload it displays as expected on card 1.
when comments/tags are entered on cards 2 or 3, onload comments/tag will appear on card 1 only, nothing on card where comments/tag were entered.
Am I forgetting something when i do forEach (or am i misusing it all together).
Appreciate any help/guidance, Im sorry Im new to JavaScript.
**prefer plain JavaScript code samples if possible.
My code link to CodePen - https://codepen.io/marcusnapoleon/pen/GRKzpeE
//SAVE
function saveTag(event) {
var tagTerm = event.target.value;
var tagTextInput = document.querySelectorAll("p.tagFilter");
tagTextInput.forEach(function (cardTags) {
localStorage.setItem("tag", tagTerm)
});
}
//RETRIEVE
function show(event) {
tagTextInput = document.querySelectorAll("p.tagFilter");
tagTextInput.forEach(function (getTags) {
var y = localStorage.getItem("tag");
document.getElementById("name").innerHTML = y
});
}
.card{
width: 300px;
border: 1px solid lightgrey;
padding: 5px 20px;
}
.container{
width: 60%;
margin-left: auto;
margin-right: auto;
display: flex;
justify-content: space-evenly;
padding: 100px 250px;
font-size: 1.2rem;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="show()">
<div class="container">
<div class="card">
<h2>Name : User One</h2>
<h2>Title : Job One</h2>
Enter your name: <input id="tagInput" onkeyup="saveTag(event)" type="text" placeholder="Comment here" >
<b>TAG:</b><p class="tagFilter" id="name">tag goes here</p>
<input onclick="clear()" type="button" value="CLEAR" />
</div>
<div class="card">
<h2>Name : User Two</h2>
<h2>Title : Job Two</h2>
Enter your name: <input id="tagInput" onkeyup="saveTag(event)" type="text" placeholder="Comment here" >
<b>TAG:</b><p class="tagFilter" id="name">tag goes here</p>
<input onclick="clear()" type="button" value="CLEAR" />
</div>
<div class="card">
<h2>Name : User Two</h2>
<h2>Title : Job Two</h2>
Enter your name: <input id="tagInput" onkeyup="saveTag(event)" type="text" placeholder="Comment here" >
<b>TAG:</b><p class="tagFilter" id="name">tag goes here</p>
<input onclick="clear()" type="button" value="CLEAR" />
</div>
</div>
</body>
</html>

You are setting values with same name, even though they are different values.
You should set values with different names. It can be editted like:
function saveTag(event) {
var tagTerm = event.target.value;
var tagTextInput = document.querySelectorAll("p.tagFilter");
tagTextInput.forEach(function (cardTags, itemIndex) {
localStorage.setItem("tag" + itemIndex, tagTerm);
});
}
This will save values with individual name, distingiushing indexes by 0,1,2.
EDIT 2019-09-27
I made some changes to your code, here it is: https://codepen.io/firesped1/pen/ExYJQgy?editors=1010
Before explaining what I did, I have to tell this:
HTML must not have duplicate IDs.
It's against the HTML standards, causing errors in ID selectors. If you want to select multiple elements at once, use class or tag selector.
The problem was you were saving the same values to different localStorage keys.I changed the logic to save directly to localStorage.
If you don't have parts that you don't understand, feel free to ask me.

Related

Submit dynamical form using JQuery

I´m not really sure I can do this, but it's worth the try.
I have a table with at least 10 items coming from a Mysql database. They are items for which you can bid. The idea is that every row (therefore, every item) has a button that can be clicked to enter the bid. This button opens a popup with a text field to enter the bid and a button to submit the form.
In order to identify the item the user is bidding for, I need its id, as well as the amount bid. The amount is really easy to get, but I´m struggling a lot with the item id.
Here is what I have:
$(document).ready(function(){
$(".show").click(function() {
$("#popup").show();
var $id = document.getElementsByClassName('show')[0].value;
console.log($id);
$("#jugador").val($id);
});
$("#close, #submit").click(function() {
$("#popup").hide();
});
});
#popup {
position: relative;
z-index: 100;
padding: 10px;
}
.content {
position: absolute;
z-index: 10;
background: #ccc;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: #000;
z-index: 5;
opacity: 0.4;
}
<td><button class="show" id="bid" value="<?php echo $row2["id"];?>"><img src="pictures/bidIcon.png" width="30" height="30"></button></td>
/*Popup*/
<div id="popup" style="display: none;">
<div class="overlay"></div>
<div class="content">
<header>
<div id="close">✖</div>
</header>
<form name="form1" method="post" action="bid.php">
<fieldset>
<label for="bid">Bid:</label>
<input type="text" name="bidAmount" id="bidAmount" size="8" />
<input type="hidden" name="item" id="item" />
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
<footer>
<button type="button" id="submit">Bid Now</button>
</footer>
</form>
</div>
</div>
I´ve been trying for a while with no luck. I will always get the item id for the first element no matter in which button I click.
Is it feasible what I want? Is this the correct approach? Should I use a different one?
Thanks a lot in advance.
Just change this line:
var $id = document.getElementsByClassName('show')[0].value;
To this:
var $id = $(this).val();
The problem is that with document.getElementsByClassName('show')[0].value you are querying the first occurrence of the .show button. With $(this) instead you will be accessing the current clicked button.
JQuery binds the events to the target where you attach the event, so this will always be a reference to the target of the event. Using $(this) will create a jQuery object of the target element permitting to apply jQuery functions to the element.
As a side note, you shouldn’t duplicate the elements ids. Every id must be unique in the html document, so it will be a good practice to make that id different for each button.
Hope it helps.
To access the current div element's Id you can use the ($this), which refers to the current javascript object.
$("div").click(function(){
alert($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1">Num 1</div>
<div id="2">Num 2</div>
<div id="3">Num 3</div>
<div id="4">Num 4</div>
Here in this example, i have created div's which when clicked return's the id of that div.
When you do it like this var $id = document.getElementsByClassName('show')[0].value; it will always take the first element having class="show".
Which will contain the first item hence always gives the id of first item.
So instead of doing it like that you can do it like this:
var $id = $(this).val();
This will select the current item on which user has clicked so will give the id of that item.

UI problems - How do I trigger an image loading on choice made by dropdown box? Then add text to overlay the image result?

I'm new to coding, I've learned the very basics of html/css/js/java, at least I thought I had, until I went to make a simple game.
I made a simple choose your own adventure game that worked, as each choice just went to a new page.
Then, I thought I'd make it a bit more complex, so I want to have the user enter their name, and store that to show next to the player's stats.
I've got a dropdown box with 4 choices for characters.I want to have Strength/Mana/Lives stats and have the player's choice of character to be able to adjust these stats accordingly before the game starts i.e. Male Warrior would have 2 extra Strength, Female Mage 2 extra mana etc.
Then, I'd like an image based on their character choice displayed next to their stats, so that the game can begin.
So far, I've been pulling my hair out in great clumps and have tried many different methods but so far, I've only got to the stage where I place the page with user input into an iframe. I can get to reflect their choices with text, but I can't get an image to load on submit. Ideally I'd like a permanent box in the top corner of the iframe, and have the statistics variables passed into the stats shown alongside the character's image.
I'd really really appreciate any help here, especially if it can be solved using HTML/CSS/JS as I'm not too familiar with JQuery, and would like to keep it as simple as possible really.
I've gone through as many q's and a's as I can to find relevant help, but I'm mainly finding answers for PHP or other languages.
I must apologise in advance for my waffling above, and sloppy coding. (I seriously thought this would be easy heh).
I'm unsure if my code so far will help, but I'll just paste it below anyway.
HTML for the UI page is:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Character Selection</title>
<link rel="stylesheet" href="css/style2.css">
<style>
img {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<div id='gamestitle'>
<p>
<img src = "GAMETITLE.jpg"
alt = "Steve's Perilous Capers"/>
</p>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLable' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p></div>
</div>
<div>
</div>
<div>
<form>
Select your Hero please:
<select id="mySelect">
<option>Male Warrior</option>
<option>Male Mage</option>
<option>Female Warrior</option>
<option>Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<script src="js/index.js"></script>
<script>
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
</script>
<p id="demo"></p>
</body>
</html>
The CSS is:
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide { display: none;}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
The JS file: (I've tried using icons and background image but I couldn't get them to show)
// the function which handles the input field logic
function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');
if (nameField.length < 3) {
result.textContent = 'Username must contain at least 3 characters';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your Hero is: ' + nameField;
//alert(nameField);
}
}
function getOption() {
var obj = document.getElementById("mySelect");
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
}
function swapImage(){
var image = document.getElementById("imageToSwap");
var dropd = document.getElementById("dd");
image.src = dropd.value;
};
// use an eventlistener for the click event
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
var subButtonTwo = document.getElementById('subButtonTwo');
subButtonTwo.addEventListener('click', getOption, false);
$(function () {
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
_renderItem: function (ul, item) {
var li = $("<li>"),
wrapper = $("<div>", {text: item.label});
if (item.disabled) {
li.addClass("ui-state-disabled");
}
$("<span>", {
style: item.element.attr("option-style"),
"class": "ui-icon " + item.element.attr("data-class")
})
.appendTo(wrapper);
return li.append(wrapper).appendTo(ul);
}
});
$("#mySelect")
.iconselectmenu()
.iconselectmenu("menuWidget")
.addClass("ui-menu-icons avatar");
});
/*
function getcurrentChoice() {
var characterSelection = ['MaleWarrior'], ['MaleMage'], ['FemaleWarrior'], ['FemaleMage'];
var currentChoice = document.getElementById('currentChoice').value;
var resultChoice = document.getElementById('resultChoice');
var subButtons = document.getElementById('subButtons');
subButtons.addEventListener('click', getcurrentChoice, false);
}
*/
Sorry for the messy coding, it's not helped that I've tried so many workarounds for each problem I've encountered that I've lost track of what is and isn't working.
I'm pretty sure this is out of control by now, and a waste of your time, but I'm so confused. I'm sure i'm over complicating the matter.
Thanks in advance again,
Steve.
Check this:
https://jsfiddle.net/digitalrevenge/q9z1x6vv/
I've added an img src and made some changes to your JS.
I'm not sure if it does exactly what you want but there's no harm in giving it a try ;)
I am not sure how to do this in Javascript, but I have achieved it with jQuery, maybe you can adapt it to Javascript if you like.
Basically...
Give each option a value
On selection, or change, empty div#change_this, and check for the value
If value = # then add html code to div#change_this
You can change the image/add in the stats, I just used some filler.
You will also need to add css and all that, if you have any specific questions about that, please let me know.
Functionality is there though.
Best,
Levi
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide {
display: none;
}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
<div>
<div id='gamestitle'>
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLabel' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p>
</div>
</div>
<div>
<form>
Select your Hero please:
<select name="hero_type" id="mySelect">
<option value="0">Male Warrior</option>
<option value="1">Male Mage</option>
<option value="2">Female Warrior</option>
<option value="3">Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<div id="change_this">
<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select[name="hero_type"]').click(function() {
$('#change_this').empty();
if ($('select[name="hero_type"]').val() == "0"){
$('#change_this').append('<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "1"){
$('#change_this').append('<p>Yayyy, Male Mage.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "2"){
$('#change_this').append('<p>Yayyy, Female Warrior</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "3"){
$('#change_this').append('<p>Yayyy, Female Mage</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
})
});
</script>
The src attribute of an image tag points to the location of the image file to use.
You should be somewhat aware of this as your code contains:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
To change the image, simply change the src attribute to point to the location of the new image.
The source of an image tag can be accessed and changed via:
document.getElementById("imageId").src="fileToUse";
This means you need to add an id to your image tag as so:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers" id="imageId"/>
In your case, you want to get the image src from a select field. This means you need to tie the image file locations to your select form as values.
<select id="mySelect">
<option value="location-of-this-image.png">Male Warrior</option>
<option value="location-of-this-image.png">Male Mage</option>
<option value="location-of-this-image.png">Female Warrior</option>
<option value="location-of-this-image.png">Female Mage</option>
</select>
To use these values and assign them to the image src:
document.getElementById("imageId").src=document.getElementById("mySelect").value;
If you correctly id your image and select form, give the select form proper values, and put the above line of code in the function you call when choosing and image, your image should change.
Important Note
JQuery is a JavaScript library and isn't part of the base language. To use JQuery, you must import it in your html code. You seem to be using JQuery functions, but I don't see where you imported JQuery. This may be causing you problems/breaking your code.
If you do have JQuery imported, the above code can be rewritten using JQuery rather than vanilla JavaScript and it'll look a lot cleaner.

How do I change HTML Label Text Once File Has Been Selected using Javascript

Thanks for viewing my question. I have a form below that has a file input field. Safe to say I have hidden this input field, and am now using the label as the primary "button" to select the files. Once a user clicks on the "Upload Picture..." label, I want the text inside the label to change from "Upload Picture..." to the file name. I'm following this tutorial below however the javascript written (in the tutorial) is for multiple files being able to be selected by the user. I only am allowing my users to select ONE file. This is a change your profile picture page to give a little insight as to what this form does.
Here is the code:
<!-- Change Picture Form -->
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
Here is the tutorial:
http://tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/
Can someone help explain to me what i have to do? I'm thinking something along the lines of an eventlistener but i'm not sure about javascript. I'm a backend dev and know very little about javascript. I do NOT WISH TO USE JQUERY. Straight javascript only.
Thanks again for your help StackOverflow members! :D
Edit:
Some people have said that the text is changing already. It's not... I want the LABEL text to change. The "File Input" tag has two parts to it. The button, and the text next to the button. I've hidden the input tag using the following SASS code. This way only the "Upload Picture..." label text is displayed. Please make sure to add this SASS code to your file so you can see that the LABEL text does not change.
.inputfile
width: 0.1px
height: 0.1px
opacity: 0
overflow: hidden
position: absolute
z-index: -1
You can use the javascript onchange event to detect when the value of the #profilepic input changes.
When it does, you can capture the new value of the #profilepic input and replace the text of the label with that value.
Example:
var profilePic = document.getElementById('profilepic'); /* finds the input */
function changeLabelText() {
var profilePicValue = profilePic.value; /* gets the filepath and filename from the input */
var fileNameStart = profilePicValue.lastIndexOf('\\'); /* finds the end of the filepath */
profilePicValue = profilePicValue.substr(fileNameStart + 1); /* isolates the filename */
var profilePicLabelText = document.querySelector('label[for="profilepic"]').childNodes[2]; /* finds the label text */
if (profilePicValue !== '') {
profilePicLabelText.textContent = profilePicValue; /* changes the label text */
}
}
profilePic.addEventListener('change',changeLabelText,false); /* runs the function whenever the filename in the input is changed */
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>
You can use change event, select element having for attribute value equal to event.target: #profilepic element id, set the .innerHTML of selected element to event.target.files[0] .name
document.getElementById("profilepic")
.addEventListener("change", function(e) {
document.querySelector("[for=" + e.target.id + "]")
.innerHTML = e.target.files[0].name;
})
.inputfile {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
<!-- Change Picture Form -->
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>

Create cloned numbered forms dynamically with jQuery

I have a page where only one form appears. This form is:
<div style="display: none" class="article_properties">
<form id="article_properties_form">
<p>Page Number</p>
<p id="pageNumber"></p>
<p>Subtitle</p>
<input type="text">
<p>Text</p>
<textarea></textarea>
<input type="submit" value="Submit/Update">
</form>
<div id="addOne" style="width: 25px; height: 25px; background-color: orange; border-radius: 50%">
<p style="text-align: center; line-height: 25px">+</p>
</div>
</div> <!--End of article properties div-->
When the user clicks the #addOne div, a clone of that form is made. BUT, this form is technically not the same form, because it will have one small detail that will make it uniquely different. This detail is the page number. Every time the #addOne div is clicked, the page number becomes one less. The page number is chosen by the user prior to seeing this current page. For example, let's say the user picks 10 pages. The first form's page number will be 10, the next form when the user clicks the #addOne div it'll be 9 and so on. The first form will always stay at 10 and the second form will always stay at 9, the third form will always stay at 8 and so on.
Here's my current script:
<script>
var numPages; //Global var: number of pages user wants
$('#addOne').click(function() {
$('#pageNumber').text(numPages);
numPages--;
var articlePropsTemplate = $('#article_properties_form').clone();
$('#article_properties_form').append(articlePropsTemplate);
});
</script>
My current code is producing very weird results. When I click on the #addOne div, the form is being duplicated multiple times instead of once, and the number of pages is not being shown correctly in a logical countdown order. This form never refreshes and all information is relayed through Ajax.
Here's the jsFiddle: https://jsfiddle.net/9dzgg8m6/6/
Alter your form :
<div class="article_properties">
<form id="article_properties_form">
<div class="form-body">//add a class to wrap the elements for cloning
<p>Page Number</p><p class="pageNumber"></p>//change the id to class
<p>Subtitle</p>
<input type="text">
<p>Text</p>
<textarea></textarea>
<input type="submit" value="Submit/Update">
</div>
</form>
<div id="addOne" style="width: 25px; height: 25px; background-color: orange; border-radius: 50%"><p style="text-align: center; line-height: 25px">+</p></div>
</div> <!--End of article properties div-->
and your js
var numPages = 10;
$('.pageNumber').text(numPages);//add then number for the first element
$('#addOne').click(function()
{
numPages--;
var articlePropsTemplate = $('.form-body:last').clone();//clone the last wrapped elements
$('#article_properties_form').append(articlePropsTemplate);
$('.pageNumber:last').text(numPages);//append the number after it was placed on the page
});
https://jsfiddle.net/0738u576/

Show table when its tab is clicked but hide other tables

So right now I have a section that has 3 tabs on it. Each tab is supposed to bring up a different table while simultaneously hiding the other 2 tables. When the page loads up it shows the first table (which it is supposed to do), but when I click one of the other two tabs nothing happens. I realize this has to be done with a Javascript onclick but I'm not familiar with it yet to know what I'm doing. I unfortunately have a lot of code that goes into making this work so i wont be able to post it on here but ill grab the code i think is most important and if you need any more info let me know. Please and thankyou for your help.
The tabs are "Pavement Section Editor", "Traffic", and "Condition"
HTML:
<div class='row' style="background-color: white; vertical-align:top; height: 250px;">
<div class="fifthDiv">
<br />
<article style="float: left; width: 100%; margin-left: 25px; height:250px;">
<section class="tabSection" id="tabmain">
<h2 class="large" style="font-size: 12px;">
Pavement Section Grid
</h2>
<p><div id="table_div_Main"></div></p>
</section>
#foreach (var layer in lstLayers)
{
if (layer != "Pavement Section" && layer != "Cores" && layer != "Inventory")
{
<section id="#("tab" + layer.Replace(" ", ""))" class="tabSection">
<h2 class="medium" style="font-size: 12px;">#layer</h2>
<p><div id="#("table_div_" + layer.Replace(" ", ""))"></div></p>
</section>
}
}
</article>
</div>
</div>
JAVASCRIPT:
function drawSectionData(data) {
return drawMe(data, 'Pavement Section Data', 'table_div_Main');
};
function drawTrafficData(data) {
return drawMe(data, 'Traffic Data', 'table_div_Traffic');
};
function drawConditionData(data) {
return drawMe(data, 'Condition Data', 'table_div_Condition');
};
//what i got so far on the javascript
$(".tabSection").children("h2").on('click', function() { console.log(this.closest("section")); })
The best way to implement tabs in your scenatio is to use jQuery Tabs - very easy and almost no additional coding required, and as added benfit it is free
Based on the assumption that:
You want to hide only the content that sits within the p of each
section and not hide the whole section itself because that would
mean that your click-able h2 will also become invisible.
You have removed div from within your section and are only using p
because inline elements do not allow to contain a block (in your
case, a div) element inside it. [Link], [Link] & [Link].
Your JavaScript code then may look like this:
var tabSections=$('.tabSection'); // select all .tabSection elements
tabSections.not('#tabmain').find('p').hide(); // hide all p elements found within tabSections stored above excluding #tabmain
tabSections.find('h2').on('click',function(){ // assign clicks to all h2 elements found within tabSections
tabSections.find('p').hide(); // hide all p elements found within tabSections
$(this).siblings('p').show(); // show the p element which is a sibling to the clicked h2 element
});
Snippet:
var tabSections=$('.tabSection');
tabSections.not('#tabmain').find('p').hide();
tabSections.find('h2').on('click',function(){
tabSections.find('p').hide();
$(this).siblings('p').show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class='row' style="background-color: white; vertical-align:top; height: 250px;">
<div class="fifthDiv">
<br />
<article style="float: left; width: 100%; margin-left: 25px; height:250px;">
<section class="tabSection" id="tabmain">
<h2 class="large" style="font-size: 12px;">
Main
</h2>
<p id="table_div_Main">Pavement Data</p>
</section>
<section class="tabSection" id="tabTraffic">
<h2 class="medium" style="font-size: 12px;">
Traffic
</h2>
<p id="table_div_Traffic">Traffic Data</p>
</section>
<section class="tabSection" id="tabCondition">
<h2 class="medium" style="font-size: 12px;">
Condition
</h2>
<p id="table_div_Condition">Condition Data</p>
</section>
</article>
</div>
</div>
Hope this helps.

Categories