I'm trying to create a function that reveals additional content by clicking a button.
I've got a script that displays the content by default - How do I switch it so the content is hidden by default and only displays when the button is clicked?
function revealContent() {
var x = document.getElementById("additionalContent");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<div class="col-10 text-center">
<button class="btn btn-sm btn-primary" onclick="revealContent()">Show More Options...</button>
</div>
<div class="col-10" id="additionalContent">
<p>Content!</p>
</div>
You just have to have the style display: none applied by default and then toggle it. classList.toggle is a good use for this. You can do something like:
.hidden {
display: none;
}
<div class="col-10 text-center">
<button class="btn btn-sm btn-primary" onclick="revealContent()">Show More Options...</button>
</div>
<div class="col-10 hidden" id="additionalContent">
<p>Content!</p>
</div>
<script>
function revealContent() {
var x = document.getElementById("additionalContent");
x.classList.toggle('hidden');
}
</script>
<div class="col-10" id="additionalContent" style="display:none">
<p>Content!</p>
</div>
EDIT: You've to add the style="display:none" to make this as default when the page is loaded.
The div works perfectly, but adding a new value to it results in NaN. But when updating the page, the div shows the updated value.
Would there be any way to add an automatic refresh to this div?
$(function () {
$(".but").on("click",function(e) {
e.preventDefault();
$(".content").hide();
$("#"+this.id+"div").show();
});
});
.content { display:none };
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="but" type="button" id="Id">Load</button>
<div id="Iddiv" class="content">
<h2>content div</h2>
</div>
$(function () {
$(".but").on("click",function(e) {
if ($("h2")[0].innerHTML=='content div'){
$("h2")[0].innerHTML="";
}else {
$("h2")[0].innerHTML='content div';
}
});
});
.content { display:block };
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="but" type="button" id="Id">Load</button>
<div id="Iddiv" class="content">
<h2></h2>
</div>
Given that hadent supplied where the new data comes from. Here are 2 examples.
Example one:
<button class="btn1" type="button" id="Id" data-newtxt="Example Text">Load</button>
<div id="section1">
<h2>content div</h2>
<span class="new-data"></span>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('.btn1').click(function() {
$('.section1 .new-data').text( $(this).data('newtxt') );
})
});
</script>
Example two:
<button class="btn2" type="button" id="Id" data-newtxt="Example Text">Load</button>
<div class="hidden-div">Some example content</div>
<div id="section2">
<h2>content div</h2>
<span class="new-data"></span>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('.btn2').click(function() {
$('.section2 .new-data').text( $('.hidden-div').text() );
})
});
</script>
I need the input value from the user to adjust the number of buttons available/visible to the user to choose from.
I assume since each button has a unique value I could run some sort of JavaScript if...else <= function and toggle between display: none and display: block but everything I have tried has failed to this point.
<body>
<div><input type="text" id="runners" />Select No. of runners</div>
<br /><br />
<div id="runner1"><button class="open-button btn1" onclick="openForm()" style="display:block;">1</button></div>
<div id="runner2"><button class="open-button btn2" onclick="openForm()" style="display:block;">2</button></div>
<div id="runner3"><button class="open-button btn3" onclick="openForm()" style="display:block;">3</button></div>
<div id="runner4"><button class="open-button btn4" onclick="openForm()" style="display:block;">4</button></div>
<div id="runner5"><button class="open-button btn5" onclick="openForm()" style="display:block;">5</button></div>
<div id="runner6"><button class="open-button btn6" onclick="openForm()" style="display:block;">6</button></div>
<div id="runner7"><button class="open-button btn7" onclick="openForm()" style="display:block;">7</button></div>
<div id="runner8"><button class="open-button btn8" onclick="openForm()" style="display:block;">8</button></div>
<div id="runner9"><button class="open-button btn9" onclick="openForm()" style="display:block;">9</button></div>
<div id="runner10"><button class="open-button btn10" onclick="openForm()" style="display:block;">10</button></div>
</body>
So if the user enters in "6" for the number of runners, I need only 6 buttons visible.
This should do it:
function updateRunners(el) {
let runners = document.querySelector('#runners');
runners.innerHTML = '';
for (let i = 1; i < Math.min(Number(el.value) + 1, Number(el.max) + 1); i++) {
let button = document.createElement('button');
button.id = 'runner-' + i;
button.innerText = i;
button.setAttribute('onclick', "openForm(this.innerText)");
runners.appendChild(button);
}
}
function openForm(i) {
console.log('openForm() was called from ' + i);
}
updateRunners(document.querySelector('#runControl'));
#runners {
display: flex;
flex-direction: column;
align-items: flex-start;
}
<input id="runControl"
type="number"
value="5"
min="0"
max="10"
oninput="updateRunners(event.target)">
<hr>
<div id="runners"></div>
You could, obviously, place them inside <div>s but I thought there's no need for it since CSS can be used to display them one below each other without extra markup.
Assign the the input box to a variable, say val.
Retrieve each number from inside the 10 buttons and assign all of them to a variable, say runners.
Use parseInt() to convert the retrieved string numbers on both your variables val and runners to integers.
Compare the parsed values of each number inside the runners variable with the parsed value of val and based on the condition result, set the css display property accordingly.
N.B. You should really avoid using inline on-* handlers (onclick, oninput, etc.) and use event listeners instead.
Check the following Code Snippet for a practical example of what I have described above:
/* JavaScript */
var btn = document.getElementById("btn");
var val = document.getElementById("runners");
function toggleRunners() {
var runners = document.querySelectorAll('div[id*="runner"]'); // 'div[id*="runner"]' basically means all div elements whose "id" attribute values has "runner" in them
runners.forEach(runner => {
var value = parseInt(val.value);
var run = parseInt(runner.innerText);
if (run === value || run < value) {
runner.style.display = "block";
} else {
runner.style.display = "none";
}
})
}
btn.addEventListener("click", toggleRunners);
<!-- HTML -->
<div>
<input type="text" id="runners">Select No. of runners
<hr />
<button id="btn">Click Me</button>
</div>
<hr />
<div id="runner1"><button class="open-button btn1" style="display:block;">1</button></div>
<div id="runner2"><button class="open-button btn2" style="display:block;">2</button></div>
<div id="runner3"><button class="open-button btn3" style="display:block;">3</button></div>
<div id="runner4"><button class="open-button btn4" style="display:block;">4</button></div>
<div id="runner5"><button class="open-button btn5" style="display:block;">5</button></div>
<div id="runner6"><button class="open-button btn6" style="display:block;">6</button></div>
<div id="runner7"><button class="open-button btn7" style="display:block;">7</button></div>
<div id="runner8"><button class="open-button btn8" style="display:block;">8</button></div>
<div id="runner9"><button class="open-button btn9" style="display:block;">9</button></div>
<div id="runner10"><button class="open-button btn10" style="display:block;">10</button></div>
Just add this function to input <input type="text" id="runners" oninput="checkNumber(this.value)"/>
and add the function below in script tags
Simple and elegant
function checkNumber(val){
var elements = document.getElementsByClassName("open-button");
for(var i = 0; i < elements.length; i++){
elements[i].style.display = "block";
}
if (val != null) {
while (val < 10) {
val++;
var class_name = '.btn' + val;
if (document.querySelector(class_name) !== null) {
document.querySelector(class_name).style.display = 'none';
}
}
}
}
function openForm() {
console.log('openForm() was called');
}
<body>
<div><input type="text" id="runners" oninput="checkNumber(this.value)"/>Select No. of runners</div>
<br /><br />
<div id="runner1"><button class="open-button btn1" onclick="openForm()" style="display:block;">1</button></div>
<div id="runner2"><button class="open-button btn2" onclick="openForm()" style="display:block;">2</button></div>
<div id="runner3"><button class="open-button btn3" onclick="openForm()" style="display:block;">3</button></div>
<div id="runner4"><button class="open-button btn4" onclick="openForm()" style="display:block;">4</button></div>
<div id="runner5"><button class="open-button btn5" onclick="openForm()" style="display:block;">5</button></div>
<div id="runner6"><button class="open-button btn6" onclick="openForm()" style="display:block;">6</button></div>
<div id="runner7"><button class="open-button btn7" onclick="openForm()" style="display:block;">7</button></div>
<div id="runner8"><button class="open-button btn8" onclick="openForm()" style="display:block;">8</button></div>
<div id="runner9"><button class="open-button btn9" onclick="openForm()" style="display:block;">9</button></div>
<div id="runner10"><button class="open-button btn10" onclick="openForm()" style="display:block;">10</button></div>
</body>
you could manually do this by saying something along these lines:
if (#runner1) {
then runner2,3,4,5,6... would have display: none
}
if (#runner2) {
then runner3,4,5,6... would have display: none
}
that's not the syntax but it's the logic for the function, using JavaScript
check this out, i did it with jquery
https://jsfiddle.net/emeka247/x5sk2gh8/4/
the html
<div>
<input type="text" id="runners">Select No. of runners
</div>
<br><br>
<div id="runner1">
<button class="open-button btn1" onclick="openForm()" style="display:none;">1</button>
</div>
<div id="runner2">
<button class="open-button btn2" onclick="openForm()" style="display:none;">2</button>
</div>
<div id="runner3">
<button class="open-button btn3" onclick="openForm()" style="display:none;">3</button>
</div>
<div id="runner4">
<button class="open-button btn4" onclick="openForm()" style="display:none;">4</button>
</div>
<div id="runner5">
<button class="open-button btn5" onclick="openForm()" style="display:none;">5</button>
</div>
<div id="runner6">
<button class="open-button btn6" onclick="openForm()" style="display:none;">6</button>
</div>
<div id="runner7">
<button class="open-button btn7" onclick="openForm()" style="display:none;">7</button>
</div>
<div id="runner8">
<button class="open-button btn8" onclick="openForm()" style="display:none;">8</button>
</div>
<div id="runner9">
<button class="open-button btn9" onclick="openForm()" style="display:none;">9</button>
</div>
<div id="runner10">
<button class="open-button btn10" onclick="openForm()" style="display:none;">10</button>
</div>
the jquery here
$(document).ready(function(){
$(document).on('keyup','#runners',function(){
$input=$('#runners').val();
if($input==1){
$('.btn1').css('display','block');
$('.btn2,.btn3, .bt4, .btn5, .btn6, .btn7').css('display','none');
}else if($input==2){
$('.btn1, .btn2').css('display','block');
$('.btn3, .btn4, .btn5, .btn6, .btn7').css('display','none');
}else if($input==3){
$('.btn1, .btn2, .btn3').css('display','block');
$('.btn4, .btn5, .btn6, .btn7').css('display','none');
}else if($input==4){
$('.btn1, .btn2, .btn3, .btn4').css('display','block');
$('.btn5, .btn6, .btn7').css('display','none');
}else if($input==5){
$('.btn1, .btn2, .btn3, .btn4, .btn5').css('display','block');
$( '.btn6, .btn7').css('display','none');
}else if($input==6){
$('.btn1, .btn2, .btn3, .btn4, .btn5, .btn6').css('display','block');
$(' .btn7').css('display','none');
}
});
});
Please help, new web developer alert!
MVC + JavaScript :)
I have a .cshtml page that has a submit button. When I press that button I want to call a JavaScript function contained on my _Layout.cshtml page.
Unfortunately I get a function not found error.
'ReferenceError: validateCheckBoxesInForm is not defined'
Here is the cshtml page...
#model FrontEnd.Web.Areas.PresentationToPolicy.ViewModels.CaseSummary.InsurersReferralViewModel
#{
ViewBag.Title = "Refer To Insurers";
}
<div>
<form asp-area="PresentationToPolicy" asp-controller="CaseSummary" asp-action="ReferToInsurers" method="POST" id="documentDownload">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</div>
Here a cut down version of my _Layout.cshtml (the script is loaded just after bootstrap etc, at the start of the body)
#inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body style="background-color: #f6f8fa">
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-ui/jquery-ui.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/dist/manifest.js"></script>
<script src="~/js/dist/vendor.js"></script>
<script src="~/js/dist/scripts.js" asp-append-version="true"></script>
</environment>
<div class="container body-content">
#RenderBody()
<hr style="margin-bottom: 2px; padding-bottom: 2px" />
<footer>
<p style="vertical-align: baseline">© 2017 - ABACUS Portfolio Portal</p>
</footer>
</div>
#RenderSection("Scripts", required: false)
</body>
</html>
Oh and the script that contains the function!
function validateCheckBoxesInForm(event, formId, title, message) {
let validated = false;
let form = $(`#${formId}`);
let elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>')
.appendTo('body')
.html(
`<div id="validateModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content" style="border-color: #f00">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">
${title}
</h3>
</div>
<div class="modal-body">
<h4>${message}</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>
</div>
</div>
</div>
</div>`
);
$('#validateModal').modal('show');
}
}
And finally a cut down version of 'View Source'
<body style="background-color: #f6f8fa">
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/jquery-ui/jquery-ui.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/dist/manifest.js"></script>
<script src="/js/dist/vendor.js"></script>
<script src="/js/dist/scripts.js?v=iHOVZCmLJ7F7ev0DnwzRmkZgp-zu74ZoPGBIra9EaIk"></script>
<div class="container body-content">
<form method="POST" id="documentDownload" action="/PresentationToPolicy/CaseSummary/ReferToInsurers/43cffe87-2d8f-43eb-8ad2-e0b046fc8d20">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
If I press view source and click on the script link I get this...
webpackJsonp([19],{
/***/ 749:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(750);
/***/ }),
/***/ 750:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//Global Functions that will be run of every page
//Called via _Layout.cshtml
function validateCheckBoxesInForm(event, formId, title, message) {
var validated = false;
var form = $('#' + formId);
var elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>').appendTo('body').html('<div id="validateModal" class="modal fade">\n <div class="modal-dialog">\n <div class="modal-content" style="border-color: #f00">\n <div class="modal-header">\n <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>\n <h3 class="modal-title">\n ' + title + '\n </h3>\n </div>\n <div class="modal-body">\n <h4>' + message + '</h4>\n </div>\n <div class="modal-footer">\n <button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>\n </div>\n </div>\n </div>\n </div>');
$('#validateModal').modal('show');
}
}....
So I guess my question is how to I call the function contained on the _Layout page from the child cshtml page?
I guess I could use a script section on the page, but this function is shared by multiple places. So I kinda need a central location to keep the code dry.
I have a grid of 4 buttons and once one of them is clicked it will call a function called doSearch which checks which button was clicked and based on that assigns a string to the last_search value.
However, when I click any of the four buttons, I always seem to only press the edm button and reads 'i am edm' to console.
Could anyone explain why that is?
html
<!-- grid for music -->
<ng-container *ngIf="show" >
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="edm-btn" type="submit" (click)="doSearch($event)">EDM</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="house-btn" type="submit" (click)="doSearch($event)">House</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="pop-btn" type="submit" (click)="doSearch($event)">Pop</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="dubstep-btn" type="submit" (click)="doSearch($event)">Dubstep</button>
</div>
</div>
</ng-container>
function code
doSearch(event): void {
if (document.getElementById('edm-btn')) {
this.last_search = 'edm';
console.log('i am edm');
} else if (document.getElementById('house-btn')) {
this.last_search = 'house';
console.log('i am house');
} else if (document.getElementById('pop-btn')) {
this.last_search = 'pop';
console.log('i am pop');
} else if (document.getElementById('dubstep-btn')) {
this.last_search = 'dubstep';
console.log('i am dubstep');
}
}
FIX:
instead of passing the id of the button, I decided to pass a string directly into the function call of doSearch
html
<!-- grid for music -->
<ng-container *ngIf="show" >
<div class="mdl-grid">
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="edm-btn" type="submit" (click)="doSearch('edm')">EDM</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="house-btn" type="submit" (click)="doSearch('house')">House</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="pop-btn" type="submit" (click)="doSearch('pop')">Pop</button>
</div>
<div class="mdl-cell mdl-cell--1-col">
<button mat-button id="dubstep-btn" type="submit" (click)="doSearch('dubstep')">Dubstep</button>
</div>
</div>
</ng-container>
function
doSearch(category): void {
console.log(JSON.stringify(category, null, 2));
if (category === 'edm') {
this.last_search = 'edm';
console.log('i am edm');
} else if (category === 'house') {
this.last_search = 'house';
console.log('i am house');
} else if (category === 'pop') {
this.last_search = 'pop';
console.log('i am pop');
} else if (category === 'dubstep') {
this.last_search = 'dubstep';
console.log('i am dubstep');
}
}
It's because no matter what event you pass, your 1st condition is always true. You are passing an event, not the actual data, as well as checking if an element exists even if it already is.
You actually don't need here if and else, it's enough:
public doSearch(category: string) {
this.last_search = category;
}