Working now
Ok so hello, im looking for help with the code below:
When i click the increment button the values increment by one on each click, which is essentially what i want it do to. But I also want the blue progress bar to fill the bar as the numbers increase.
I have a run able piece of code which may help with de-bugging here below.
All help appreciated as i am new to this site Thanks.
function getProgress() {
return document.getElementById("progressbar").getAttribute("aria-valuenow");
return document.getElementById("progressbar").getAttribute("style","width");
return document.getElementById("progressbar").innerHTML;
}
function setProgress(value) {
document.getElementById("progressbar").setAttribute("aria-valuenow",value);
document.getElementById("progressbar").setAttribute("style","width: " +value+ "%");
document.getElementById("progressbar").innerHTML = (value+ "%");
}
function increment() {
var i = getProgress();
if(i < 100){
i++;
setProgress(i);
}else{
alert("Progress Complete!");
}
}
function decrement() {
var d = getProgress();
setProgress(d - 1);
}
function resetButton() {
var r = getProgress();
setProgress(r = 0);
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<title>Progress Bar</title>
</head>
<body>
<!-- Container -->
<div class="container">
<h1>This Process bar is animated using <br>JavaScript!</h1>
<br>
<!-- Div For Progress Bar -->
<div class="progress">
<div class="progress-bar progress-bar-striped" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="progressbar" >0%</div>
</div>
<br>
<!-- Buttons -->
<button type="button" class="btn btn-primary" onclick = "increment()">Increment</button>
<button type="button" class="btn btn-dark" onclick="resetButton()">Reset</button>
<button type="button" class="btn btn-success" onclick="decrement()">Decrement</button>
<button type="button" class="btn btn-warning" onclick="">Start Auto Progress!</button>
<button type="button" class="btn btn-danger" onclick="">Stop Auto Progress!</button>
<p id="value"> </p>
<!-- End of Container -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="Assignment4.js"></script>
</body>
</html>
You're only missing a single colon in your line to set width. Should be "width: " + value instead.
Related
My goal is to create a collapse element when the form data has been processed by the server, to notify the user whether the data was successfully sent to the server or an error occurred.
function sendForm(event, form) {
const wrapper=document.createElement('div');
wrapper.setAttribute('role', 'alert');
wrapper.classList.add('alert', 'alert-dismissible', 'alert-success');
wrapper.innerHTML='<span>Success!</span><button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
form.prepend(wrapper);
const bsWrapperCollapse = bootstrap.Collapse.getOrCreateInstance(wrapper);
bsWrapperCollapse.show();
setTimeout(() => {
bsWrapperCollapse.hide();
}, 4000);
setTimeout(() => {
wrapper.remove();
}, 7000);
form.reset();
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<main class="container-fluid my-5" style="max-width:300px">
<form action="#" method="post" onsubmit="sendForm(event, this)">
<button type="submit" class="btn btn-primary">My form submit btn</button>
</form>
<button class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-bs-target
</button>
<div class="collapse" id="collapseExample">
<div class="alert alert-dismissible alert-success" role="alert">
<span>Success!</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
I added two implementations to the test html - the first button calls my implementation, which is in the form and when it is pressed, data should be sent, but the animation of appearing and hiding is jerky. The second button is taken from the bootstrap documentation, with the correct animation, which is what I want to achieve in my implementation using js.
I think the problem is that the element created in js haven't the collapse class, the transition is applied only if the element has collapse class. I modified the code , I added the class collapse to the wrapper and added the alerts classes to a div inside the wrapper element.Now it seems the animation works properly
function sendForm(event, form) {
const wrapper=document.createElement('div');
wrapper.setAttribute('role', 'alert');
wrapper.classList.add("collapse");
wrapper.innerHTML='<div class="alert alert-dismissible alert-success"><span>Success!</span><button type="button" class="btn-close" data-bs-dismiss="alert"></button> </div>';
form.prepend(wrapper);
const bsWrapperCollapse = bootstrap.Collapse.getOrCreateInstance(wrapper);
bsWrapperCollapse.show();
setTimeout(() => {
bsWrapperCollapse.hide();
}, 4000);
setTimeout(() => {
wrapper.remove();
}, 7000);
form.reset();
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<main class="container-fluid my-5" style="max-width:300px">
<form action="#" method="post" onsubmit="sendForm(event, this)">
<button type="submit" class="btn btn-primary">My form submit btn</button>
</form>
<button class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-bs-target
</button>
<div class="collapse" id="collapseExample">
<div class="alert alert-dismissible alert-success" role="alert">
<span>Success!</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
So, I figured out how I can make the animation normal without even checking the answers here. I noticed that the alert container in the html code is wrapped in another container. But when I created the alert via js, I didn't wrap it. After I wrapped this element, the animation worked as it should. #Nick suggested that the animation doesn't work as expected due to the lack of a collapse class, but I tested his code without it and the animation still works. The reason the animation works correctly is that he wrapped my code in a container via innerHTML, essentially doing the same thing I did. Here's what I ended up with.
function sendForm(event, form) {
const alert=document.createElement('div');
alert.setAttribute('role', 'alert');
alert.classList.add('alert', 'alert-dismissible', 'alert-success');
alert.innerHTML='<span>Success!</span><button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
const alertWrapper=document.createElement('div');
alertWrapper.append(alert);
form.prepend(alertWrapper);
const alertWrapperCollapse = bootstrap.Collapse.getOrCreateInstance(alertWrapper);
alertWrapperCollapse.show();
setTimeout(() => {
alertWrapperCollapse.hide();
}, 4000);
setTimeout(() => {
alertWrapper.remove();
}, 7000);
form.reset();
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
</head>
<body>
<main class="container-fluid my-5" style="max-width:300px">
<form action="#" method="post" onsubmit="sendForm(event, this)">
<button type="submit" class="btn btn-primary">My form submit btn</button>
</form>
<button class="btn btn-primary" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-bs-target
</button>
<div class="collapse" id="collapseExample">
<div class="alert alert-dismissible alert-success" role="alert">
<span>Success!</span>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
</div>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>
</html>
Anyway, I marked #Nick's answer as helpful.
How can i code my calc function so that it subtracts 1 to the main counter if clicked on the "lower count" button or add 1 if clicked on the "add counter".
I could use separate functions for each one, but im trying to learn how to create a single functions that will work for both scenarios based on the value of the button clicked.
The issue is 100% in the if else statement line 17.
Code below.
(function () {
//create a main counter to store the calculations
let value = 0;
//variables to use as selectors
const counter = document.getElementById("counter");
const lower = document.querySelector(".prevBtn");
const upper = document.querySelector(".nextBtn");
//set the html text to the counter value
counter.textContent = value;
// function to add or subtract value
let calc = function (event) {
//here is my problem the target value please help
let target = event.target;
if (target.classList.contains("Prevbtn")) {
value -= 1;
counter.textContent = value;
} else {
value += 1;
counter.textContent = value;
}
};
//add functionality to the buttons
lower.addEventListener("click", calc);
upper.addEventListener("click", calc);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<!-- bootstrap css -->
<link rel="stylesheet" href="css/bootstrap.min.css" />
<!-- main css -->
<link rel="stylesheet" href="css/main.css" />
<!-- google fonts -->
<link
href="https://fonts.googleapis.com/css?family=Courgette"
rel="stylesheet"
/>
<!-- font awesome -->
<script src="js/all.js"></script>
<title>Counter Project</title>
<style></style>
</head>
<body>
<div class="container">
<div class="row max-height align-items-center">
<div class="col-10 mx-auto col-md-6 text-center main-container p-5">
<h1 class="text-uppercase">counter</h1>
<h1 id="counter"></h1>
<div class="btn-container d-flex justify-content-around flex-wrap">
<button class="btn counterBtn prevBtn text-uppercase m-2">
lower count
</button>
<button class="btn counterBtn nextBtn text-uppercase m-2">
add count
</button>
</div>
</div>
</div>
</div>
<!-- jquery -->
<script src="js/jquery-3.3.1.min.js"></script>
<!-- bootstrap js -->
<script src="js/bootstrap.bundle.min.js"></script>
<!-- script js -->
<script src="js/app.js"></script>
</body>
</html>
typo, prevBtn is not the same as Prevbtn, fix that and it works
answer given by user CertainPerformance
I have a problem with the do-while. When I type into an input form a different number than 15, it still says 'success', but it shouldn't, because the right number is 15. How could I change the do-while to recognize when I type other number than 15? Thanks for any suggestions.
//works when type only 15
do {
var guess = prompt("Guess a number between 1 and 20");
} while (guess !=15)
alert("Success!");
//this part works when I type 15 or different number
function guessWage() {
do {
var guess = document.getElementById("guessNumber")
if (guess.value != 15) {
guess.value = false;
}
} while (guess.value === 15)
alert('you guessed the number');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>While loop</h2>
<h5><span class="badge badge-secondary">Array backwards:</span></h5>
<div class="alert alert-success" role="alert" id="resultMonthly">
</div>
<h5><span class="badge badge-secondary">Array forwards:</span></h5>
<div class="alert alert-info" role="alert" id="resultDaily">
</div>
<h5><span class="badge badge-secondary">Guess, how much full-stack dev earns</span></h5>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">$</span>
<input type="text" class="form-control" placeholder="Type the number" aria-label="Number" aria-describedby="basic-addon1" id="guessNumber">
</div>
<button onclick="guessWage()" type="button" class="btn btn-info">Guess it!</button>
</div>
<!-- Scripts -->
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- JS -->
<script type="text/javascript" src="whileloop.js"></script>
</body>
</html>
Ok, I changed the string to Number with Number(var), but now it's giving me an infinite loop. I'm little bit confused. Someone knows what to add into this do-while?
function guessWage() {
do {
var guess = document.getElementById("guessNumber")
} while (Number(guess.value) !== 15)
alert('you guessed the number');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Issue App</title>
<link rel="stylesheet" type="text/css" href="wageup.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>While loop</h2>
<h5><span class="badge badge-secondary">Array backwards:</span></h5>
<div class="alert alert-success" role="alert" id="resultMonthly">
</div>
<h5><span class="badge badge-secondary">Array forwards:</span></h5>
<div class="alert alert-info" role="alert" id="resultDaily">
</div>
<h5><span class="badge badge-secondary">Guess, how much full-stack dev earns</span></h5>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">$</span>
<input type="text" class="form-control" placeholder="Type the number" aria-label="Number" aria-describedby="basic-addon1" id="guessNumber">
</div>
<button onclick="guessWage()" type="button" class="btn btn-info">Guess it!</button>
</div>
<!-- Scripts -->
<!-- Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- JS -->
<script type="text/javascript" src="whileloop.js"></script>
</body>
</html>
Javascript uses == !=, but you should always use === and !==.
Since the former can have unpredictable results sometimes. Moreover, you are comparing a string to an integer. Try converting them beforehand using Number(var)
Basically what you are trying to achieve is not clear.. if you simply want to compare the values on button click you dont need a loop in that case.so something like..
function guessWage() {
var guess = document.getElementById("guessNumber")
if (guess.value != "15") {
// do what you want here if guess is wrong.
alert('wrong guess');
}
else
{
// do what you want if guess is right
alert('right guess');
}
}
OR
function guessWage()
{
var guess = document.getElementById("guessNumber")
if (Number(guess.value) != 15) {
// do what you want here if guess is wrong.
alert('wrong guess');
}
else
{
// do what you want if guess is right
alert('right guess');
}
}
feel free to comment about if anything is there i will update my answer.
I already have my own solution for this problem, but then I don't know if I'm using the best techniques/practices to solve this particular scenario, which involves removing and adding DOM elements with unique id's.
I have just used jQuery, the requirements where only a button to add any amount of rows, once another row is added be able to delete that row too, the first row is always mandatory, here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <title>Simple form</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<style type="text/css">
label{
display: block;
}
</style>
</head>
<body>
<div class="container">
<div class="row inputRows">
<div class="col-sm-12" id="newRow-1">
<label>Some label over input</label>
<input type="text" name="txt">
</div>
</div>
<div class="row">
<div class="col-sm-12">
<button id="addRow"><span class="fa fa-plus"></span> Add </button>
<button id="viewInfo"><span class="fa fa-plus"></span> Info </button>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="result">
</p>
</div>
</div>
</div>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
$('.inputRows').on('click', 'button' ,function(){
$(this).parent().remove();
});
$('#addRow').click(function(){
var $newRow = $('div[id^="newRow"]:first').clone(),
newId = Number($('div[id^="newRow"]:last').attr('id').split('-')[1]) + 1;
$newRow.append('<button><span class="fa fa-trash-o"></span></button>');
$newRow.find('input').val('');
$newRow.attr('id','newRow-' + newId);
$('.inputRows').append($newRow);
});
$('#viewInfo').click(function(){
$('#result').text(JSON.stringify(objectifyForm($('div[id^="newRow"]'))));
});
function objectifyForm(formArray) {
var resultArray = {},
inputValue = '';
for (var i = 0; i < formArray.length; i++){
inputValue = $(formArray[i]).find('input').val();
if(inputValue){
resultArray[$(formArray[i]).attr('id')] = inputValue;
}
}
return resultArray;
}
</script>
</body>
</html>
So the code works, the only problem I see is that the numeration of the id's, can sometimes be 1,5,8,7,6,12 depending on which ones you delete, but then it's fine because in the end, it doesn't even matter (joke, RIP Chester, but kind of true). My main concern or question is, is there any other way of achieving this more efficiently using jQuery? Am I doing something wrong by cloning the first element multiple times? If you can share some knowledge on DOM manipulation that would be great.
Thanks in advance,
Leo.
The main goal is to show different divs depending on which button I click, so they all start with the display style at "none" (except a default one called "atualizacoes"). And after I click a button ALL of the divs should be set to
display="none" and after that the one I associated that button with is set to display="block".
However something isn't right because when I click one of the buttons, the default div does disappear however nothing ever appears.
This is how I'm trying to accomplishing it:
In order:
snippet 1 - function I use inside my index.html to change all the
displays
snippet 2 - rule in my stylesheet
snippet 3 - parts of my index.html code (I didn't want to paste
EVERYTHING)
<script type="text/javascript">
function replace(show) {
document.getElementById('default').style.display="none";
document.getElementById('ecra').style.display="none";
document.getElementById(show).syle.display = "block";
}
</script>
.ecra
{
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>University Platform</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="dashboard.css" rel="stylesheet">
<!-- jquery -->
<script src="assets/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<!-- these are the buttons that are located on a sidebar -->
<div class="row">
<h3>Options</h3>
<button type="button" class="btn btn-default botao pull-left" onclick="replace('addestudante')">Adicionar Estudante</button>
</div>
<div class="row">
<button type="button" class="btn btn-default botao pull-left" onclick="replace('adduc')">Adicionar UC</button>
</div>
<!-- these are the divs I want to switch around -->
<div class="row" id='default'>
<p> Hello World </p>
</div>
<!-- in CSS I also made a rule that makes all "ecra" divs be invisible from the start-->
<div class="row ecra" id='addestudante'>
<button type="button" class="btn btn-default"> TEST 1</button>
</div>
<div class="row ecra" id='adduc'>
<button type="button" class="btn btn-default"> TEST 2</button>
</div>
</body>
Why is this function not working properly? Is there something wrong with my code?
There are a couple of issues with what you've written.
For one, you don't have any elements with ID "ecra" — what you want to do is affect all the elements that have the class "ecra". You can do this by looping or mapping over document.getElementsByClassName("ecra").
Secondly, you've misspelt style when you try to show the show element.
Try using this adapted function instead:
function replace(show) {
document.getElementById("default").style.display = "none";
Array.from(document.getElementsByClassName("ecra")).map(element => element.style.display = "none");
document.getElementById(show).style.display = "block";
}
By what I thought, you want to get elements by class name. They're ecra, so you can use querySelectorAll and do a loop for its length. I'll not use getElementsByClassName because it will make the line more longer and return an array.
function replace(show){
var q=document.querySelectorAll('.ecra'),
document.getElementById('default').style.display="none";
for(var i=0,l=q.length;i<l;i++){
!function(i){
q[i].style.display="none"
}(i)
}
document.querySelector('#'+show).style.display = "block"
}
I saw jQuery imported in your page. So I suggest to use jQuery.
<script type="text/javascript">
function replace(show) {
jQuery(function($){
$("#default").css({
"display" : "none"
});
$(".ecra").css({
"display" : "none"
});
$("#"+show).css({
"display" : "block"
});
});
}
</script>
Edited, missing characters.
JS corrected : http://jsfiddle.net/csfd8x35/
.ecra
{
display: none;
}
<!-- these are the buttons that are located on a sidebar -->
<div class="row">
<h3>Options</h3>
<button type="button" class="btn btn-default botao pull-left" onclick="replace1('addestudante')">Adicionar Estudante</button>
</div>
<div class="row">
<button type="button" class="btn btn-default botao pull-left" onclick="replace1('adduc')">Adicionar UC</button>
</div>
<!-- these are the divs I want to switch around -->
<div class="row" id='default'>
<p> Hello World </p>
</div>
<!-- in CSS I also made a rule that makes all "ecra" divs be invisible from the start-->
<div class="row ecra" id='addestudante'>
<button type="button" class="btn btn-default"> TEST 1</button>
</div>
<div class="row ecra" id='adduc'>
<button type="button" class="btn btn-default"> TEST 2</button>
</div>
<script>
function replace1(show) {
document.getElementById('default').style.display="none";
var allByClass = document.getElementsByClassName('ecra');
for (var i=0;i< allByClass.length; i++) {
allByClass[i].style.display = "none";
}
document.getElementById(show).style.display = "block";
}
</script>