User needs to input Bitcoin address
after bitcoin address is valid modal should open
if bitcoin adress is invalid modal should stay closed
enter image description here
enter image description here
enter image description here
And here is the code
(Bicoin validation works, i only need help with the modal)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>BItmixxer</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style media="screen">
hr.style1{
border-top: 1px solid #8c8b8b;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">Navbar</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron jumbotron-fluid" style="text-align:center" >
<div class="container">
<h1>Crypto Mixxer</h1>
<p>some more Text about crypto mixxer</p>
</div>
</div>
<div class="container" style="text-align:center" >
<h1>BTC Mixxer</h1>
<p>Choose COins to mix:</p> <button type="button" class="btn btn-outline-primary">Bitcoin</button>
<button type="button" class="btn btn-outline-success">Ethereum</button>
<br>
<br>
<br>
<div class="form-group" id="elMessage" class="msg">
<input type="text" class="form-control" id="inpAddress" value="">
</div>
<button type="button" class="btn btn-primary" id="btnValidate" data-toggle="modal" data-target="#myModal">Next</button>
<script>
var normalize = (s) => {
let x = String(s) || '';
return x.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
};
var check = (s) => {
if (s.length < 26 || s.length > 35) {
return false;
}
let re = /^[A-Z0-9]+$/i;
if (!re.test(s)) {
return false;
}
return true;
};
var getEl = (id) => {
return document.getElementById(id) || null;
};
var elMessage = getEl('elMessage');
var inpAddress = getEl('inpAddress');
var btnValidate = getEl('btnValidate');
var lnkClear = getEl('lnkClear');
var setMessage = (txt = '', clss = 'msg') => {
elMessage.className = clss;
elMessage.innerHTML = txt;
};
var validate = (s) => {
let className = 'msg fail';
let textMessage = 'Invalid bitcoin address';
if (!s) {
textMessage = 'Please enter a valid address';
}
let re = check(s);
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
}
setMessage(textMessage, className);
return re;
};
btnValidate.onclick = () => {
let v = normalize(inpAddress.value);
let result = validate(v);
if (result) {
inpAddress.value = v;
}
};
lnkClear.onclick = () => {
inpAddress.value = '';
inpAddress.focus();
setMessage('Enter any text and press "Validate"');
};
</script>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h3>Please send your BTC(min0.5) to</h3>
<p id ="btc-house" style="color:blue;"></p>
<script>
var myArray = ['1QFsuDg4HyCJZFBfC2ivxHCK2CX2i9YvWN', ' 1EhfSjMuyAyrpRRGf5sSCU3YDbVAqjJNxH', '1N2e39vyTrk6HtvZPqWPrHfHKBzsnQNN4V','1GVSGZxwU69fN5oPprSxXRnjsZPvo8bGw3'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("btc-house").innerHTML = rand;
</script>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
I know i need to use
$('#myModal').modal('show');
$('#myModal').modal('hide');
i just dont know where to put it
First remove the data-toggle="modal" target="#myModal" from #btnValidate
<button type="button" class="btn btn-primary" id="btnValidate">Next</button>
Then change your if statment inside your validate function to:
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
$('#myModal').modal('show')
}
Note that you import jquery twice, which can lead to bugs. Remove one import and make sure jquery is imported before bootsrap.js
Related
so i'm currently trying to build search icon on the header clickable where you're able to search for, in this case, pokemon names, however i keep getting a console error
searchQuery.value undefined
Not sure why because the code looks valid.
Also, when you click on the search icon the icon goes above it and once you hit submit on the input it duplicates. I'm sure it's all connected the bug.
No sure why this is happening and would greatly appreciate any advice to fix this.
let pokemonRepository = (function() {
let pokemonList = [];
// API
let apiUrl = "https://pokeapi.co/api/v2/pokemon/?limit=150";
let searchIcon = $(".btn-outline-secondary");
let modalContainer = $(".modal");
let modalDialog = $(".modal-dialog");
let modalContent = $(".modal-content");
let modalBody = $(".modal-body");
let modalTitle = $(".modal-title");
let modalHeader = $(".modal-header");
let modalClose = $(".btn-close");
let listItemArray = $("li");
function add(pokemon) {
if (
typeof pokemon === "object" &&
"name" in pokemon &&
"detailsUrl" in pokemon
) {
pokemonList.push(pokemon);
} else {
console.error("pokemon is not correct");
}
}
function getAll() {
return pokemonList;
}
// filters through pokemon names
function search(pokemonName) {
return pokemonList.filter((pokemon) => pokemon.name === pokemonName);
}
// Function adds a list of pokemon
function addListItem(pokemon) {
let pokemonDisplay = $(".list-group-horizontal");
// Creates li element
let listItem = $("<li>");
listItem.addClass(
"list-group-item text-center col-sm-6 col-md-4 border border-secondary bg-image img-fluid"
);
// Creates h1 for Pokemon Name
let listTitle = $("<h1>");
listTitle.html(`${pokemon.name}`);
listTitle.addClass("display-6");
// Creates div which holds sprites
let listImg = $("<div>");
loadDetails(pokemon).then(function() {
listImg.append(
`<img src=${pokemon.imageUrlFront} alt="${pokemon.name} sprite"/>`
);
});
let listButton = $("<button>");
listButton.text("show More");
// Added Bootstrap Utility Class
listButton.addClass("mp-2 btn btn-secondary");
listButton.attr("type", "button");
listButton.attr("data-bs-toggle", "modal");
listButton.attr("data-bs-toggle", "#pokemonModal");
listItem.append(listTitle);
listItem.append(listImg);
listItem.append(listButton);
pokemonDisplay.append(listItem);
buttonEvent(listButton, pokemon);
}
function buttonEvent(listButton, pokemon) {
listButton.on("click", () => {
showDetails(pokemon);
});
}
function showDetails(pokemon) {
loadDetails(pokemon).then(() => {
// Clears existing content
modalContainer.empty();
modalTitle.addClass("modal-title h5 col-sml-3");
let pokemonType = {
fire: "text-danger",
grass: "text-success",
water: "text-primary",
electric: "text-warning",
flying: "text-info",
poison: "text-secondary",
};
pokemon.types.forEach((type) =>
modalTitle.addClass(pokemonType[type.type.name])
);
modalTitle.html(`${pokemon.name}`);
modalBody.html(`
Entry: ${pokemon.id}<br>
Height: ${pokemon.height}<br>
Weight: ${pokemon.weight}<br>
Types: ${pokemon.types[0].type.name}`);
if (pokemon.types.length === 2) {
modalBody.innerHTML += `, ${pokemon.types[1].type.name}`;
}
modalBody.innerHTML += `<br>Abilities: ${pokemon.abilities[0]}.ability.name}`;
if (pokemon.abilities.length === 2) {
modalBody.innerHTML += `, ${pokemon.abilities[1]}.ability.name}`;
}
modalBody.append(`<br>
<img src=${pokemon.imageUrlFront} alt="${pokemon.name} front sprite">
<img src=${pokemon.imageUrlBack} alt="${pokemon.name} back sprite">
<br>
`);
modalDialog.append(modalContent);
modalContent.append(modalHeader);
modalHeader.append(modalTitle);
modalHeader.append(modalClose);
modalContent.append(modalBody);
modalContainer.append(modalDialog);
});
modalContainer.modal("show");
}
modalContainer.on("shown.bs.modal", () => {
// Jquery eventlistener
modalClose.on("click", () => {
modalContainer.removeClass("fade");
modalContainer.modal("hide");
listItemArray[0].children().click();
});
});
searchIcon.on("click", () => {
// fetching .d-flex class in form
let bodyHeader = $(".d-flex");
// returns the number of child elements
if (bodyHeader.length === 1) {
//creates input element
let searchQuery = $("<input>");
searchQuery.attr("placeholder", "Pokemon Name");
searchQuery.attr("type", "search");
searchQuery.attr("aria-label", "search Pokemon Name");
searchQuery.addClass("form-control my-3 ps-2 col-sm");
searchIcon.blur();
searchQuery.focus();
bodyHeader.append(searchQuery);
searchQuery.on("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
searchQuery.value =
searchQuery.value.charAt(0).toUpperCase() +
searchQuery.value.slice(1);
for (let i = 0; i < listItemArray.length; i++) {
if (
902 >
listItemArray[i].children().last().getBoundingClientRect()[
"top"
] &&
listItemArray[i].children().last().getBoundingClientRect()[
"top"
] > 42
) {
listItemArray[i].children().last().click();
}
}
for (let i = 0; i < listItemArray.length; i++) {
if (listItemArray[i].text().split("\n")[0] === searchQuery.value) {
setTimeout(function() {
listItemArray[i].children().last().click();
}, 5);
}
}
}
});
}
});
// Fetches data from API
function loadList() {
return fetch(apiUrl)
.then(function(response) {
return response.json();
})
.then(function(json) {
json.results.forEach((item) => {
let pokemon = {
name: item.name.charAt(0).toUpperCase() + item.name.slice(1),
detailsUrl: item.url,
};
add(pokemon);
});
})
.catch(function(error) {
console.error(error);
});
}
function loadDetails(item) {
let url = item.detailsUrl;
return fetch(url)
.then(function(response) {
return response.json();
})
.then(function(details) {
item.imageUrlFront = details.sprites.front_default;
item.imageUrlBack = details.sprites.back_default;
item.id = details.id;
item.height = details.height;
item.weight = details.weight;
item.types = details.types;
item.abilities = details.abilities;
})
.catch(function(error) {
console.error(error);
});
}
return {
add: add,
getAll: getAll,
addListItem: addListItem,
search: search,
showDetails: showDetails,
loadList: loadList,
loadDetails: loadDetails,
buttonEvent: buttonEvent,
};
})();
pokemonRepository.loadList().then(function() {
pokemonRepository.getAll().forEach(function(pokemon) {
pokemonRepository.addListItem(pokemon);
});
});
<!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.0" />
<meta name="description" content="The Pokédex is a simple encyclopedia of Pokémon and their characteristics." />
<link rel="shortcut icon" href="img/favicon.png" type="image/x-icon" />
<title>Pokédex App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.8.3/font/bootstrap-icons.css" />
<link rel="stylesheet" href="/dist/style.production.css" />
</head>
<body>
<nav class="navbar navbar-expand-lg sticky-top navbar-light bg-light">
<div class="container-fluid">
<a href="#home" class="navbar-brand">
<img src="img/ball.png" width="30" height="24" alt="" class="d-inline-block align-text-top" /><span class="text-uppercase font-weight-bold text-secondary">Pokèdex</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#home">Home</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
</ul>
</li>
</ul>
<form class="d-flex row" role="search">
<!-- <input
class="form-control me-2"
placeholder="Pokemon Name"
aria-label="Search"
/> -->
<button class="btn btn-outline-secondary" type="submit">
<i class="bi bi-search"></i>
</button>
</form>
</div>
</div>
</nav>
<p class="fw-bold position-absolute top-10 start-50 text-center text-danger"></p>
<!-- Pokemon Display -->
<div class="container">
<ul class="list-group list-group-horizontal flex-fill row mt-4"></ul>
</div>
<!-- Display Ends Here -->
<div class="modal fade" id="pokemonModal" tabindex="-1" role="dialog" aria-labelledby="pokemonModalLabel" aria-hidden="true">
<div class="modal-dialog pt-5 text-center" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title col-sm-3" id="pokemonModalLabel"></h5>
<button type="button" class="btn-close me-3" data-dismiss="modal" aria-label="Close" aria-hidden="true"></button>
</div>
<!-- Content is dynamically created using jquery -->
<div class="modal-body"></div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.11.5/dist/umd/popper.min.js" integrity="sha384-Xe+8cL9oJa6tN/veChSP7q+mnSPaj5Bcu9mPX5F5xIGE0DVittaqT5lorf0EI7Vk" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>
<script src="/src/js/scripts.js"></script>
<script src="/src/js/promise-polyfill.js"></script>
<script src="/src/js/fetch-pollyfill.js"></script>
</body>
</html>
Since searchQuery is a jQuery object, you need to use its .val() method to set and get the value. So change.
searchQuery.value =
searchQuery.value.charAt(0).toUpperCase() +
searchQuery.value.slice(1);
to
searchQuery.val((i, value) => value[0].toUpperCase() + value.slice(1));
Hey there I am just have trouble bringing up a modal working with bootstrap. Theoretically I have a list of pokemon that I fetched from another website. Then each pokemon is supposed to act as a button to where i can then click on and receive more information about. I would appreciate some help as I am pretty lost.
Thanks
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Simple JS App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<header class="page-header">
<nav class="navbar fixed-top navbar-expand-sm navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-target="#myModal" data-toggle="modal" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
</div>
</nav>
</header>
<h1>Pokedex</h1>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="myModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" data-target="#myModal" data-toggle="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<ul class="list-group"></ul>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="js/scripts.js"></script>
</body>
</html>
JS
let pokemonRepository = (function () {
let pokemonList = [];
let apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150';
function add(pokemon) {
pokemonList.push(pokemon);
}
function getAll() {
return pokemonList;
}
function addListItem(pokemon) {
let pokemonList = document.querySelector('.list-group');
let listPokemon = document.createElement('li');
listPokemon.classList.add('group-list-item');
let button = document.createElement('button');
button.innerText = pokemon.name;
button.classList.add('btn');
pokemonList.appendChild(listPokemon);
listPokemon.appendChild(button);
button.addEventListener('click', function(event) {
showDetails(pokemon);
});
}
function loadList() {
return fetch(apiUrl).then(function (response) {
return response.json();
}).then(function (json) {
json.results.forEach(function (item) {
let pokemon = {
name: item.name,
detailsUrl: item.url
};
add(pokemon);
console.log(pokemon);
});
}).catch(function (e) {
console.error(e);
});
}
function loadDetails(item) {
let url = item.detailsUrl;
return fetch(url).then(function (response) {
return response.json();
}).then(function (details) {
// Now we add the details to the item
item.imageUrl = details.sprites.front_default;
item.height = details.height;
item.types = details.types;
}).catch(function (e) {
console.error(e);
});
}
function showDetails(pokemon) {
loadDetails(pokemon).then(function () {
showModal(pokemon);
});
};
function showModal(item) {
let modalContainer = document.querySelector('#myModal');
modalContainer.classList.add('is-visible');
// Clear all existing modal content
modalContainer.innerHTML = '';
modalContainer.addEventListener('click', (e) => {
// Since this is also triggered when clicking INSIDE the modal
// We only want to close if the user clicks directly on the overlay
let target = e.target;
if (target === modalContainer) {
hideModal();
}
});
let modal = document.createElement('div');
modal.classList.add('modal');
// Add the new modal content
let closeButtonElement = document.createElement('button');
closeButtonElement.classList.add('modal-close');
closeButtonElement.innerText = 'Close';
closeButtonElement.addEventListener('click', hideModal);
let titleElement = document.createElement('h1');
titleElement.innerText = item.name + (': ') + ('height = ') + item.height;
let container = document.querySelector('#image-container');
let myImage = document.createElement('img');
myImage.src = item.imageUrl;
modal.appendChild(closeButtonElement);
modal.appendChild(titleElement);
modalContainer.appendChild(modal);
modal.appendChild(myImage);
}
function hideModal() {
let modalContainer = document.querySelector('#myModal');
modalContainer.classList.remove('is-visible');
}
window.addEventListener('keydown', (e) => {
let modalContainer = document.querySelector('#myModal');
if (e.key === 'Escape' && modalContainer.classList.contains('is-visible')) {
hideModal();
}
});
return {
add: add,
getAll: getAll,
addListItem: addListItem,
loadList: loadList,
loadDetails: loadDetails,
showDetails: showDetails
};
})();
pokemonRepository.loadList().then(function () {
pokemonRepository.getAll().forEach(function (pokemon) {
pokemonRepository.addListItem(pokemon);
});
});
1 - There is few errors in your code. To open a bootstrap modal there is a method:
$('#myModal').modal('show');
2 - Then you cleaned the structure of the modal with the innerHTML instead of the modal-body and you are trying to recreate all the elements dynamically.
What you can do is just replacing the content of the modal body or do not forget to re-create every element of the modal which is not what you did.
Here is a working example:
https://codepen.io/alxtaz/pen/WNXYOrd
I have this bootstrap layout, which is a container inside an accordion-item. There is a dropdown button, containing messages and there's another button that opens a modal to insert a new message and display it in the dropdown list, using localStorage.
When the page loads or is refreshed, I can select the dropdown item normally, but when I add the item, it actually shows up in the list, but I can't select it nor any other item and the selected item is kept there, until the page is reloaded again.
I can still add more messages using the modal and they will still show up in the list.
There's no error in the console to guide me.
The JavaScript code is located at the bottom of the code.
Demonstrating video: https://www.youtube.com/watch?hd=1&v=fhNfpOaJbGs
HTML:
<div class="container">
<div class="row justify-content-center">
<div class="col-4">
<div class="dropdown">
<button class="btn btn-secondary" type="button" id="ddMensagens" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Selecione Mensagem
</button>
<div class="dropdown-menu scrollable-menu" id="mensagem" aria-labelledby="ddMensagens">
</div>
</div>
</div>
<div class="col-4">
<button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#staticBackdrop" title="Clique para cadastrar uma nova mensagem">
Cadastrar Nova Mensagem
</button>
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="false" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered"">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalMensagem">Nova Mensagem</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<label for="txtMensagem">Digite sua mensagem</label>
<input type="text" class="form-control" id="txtMensagem" placeholder="Mensagem" style="width: 400px">
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" id="saveMensagem" onclick="addItem();" data-bs-dismiss="modal">Salvar</button>
</div>
</div>
</div>
</div>
</div>
<br />
</div>
</div>
JavaScript:
<script defer>
function updateSelect() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = '';
oldMessage.forEach(element => {
select.innerHTML += `<button class='dropdown-item' type='button'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelect();
text.value = ''
}
}
}
updateSelect()
</script>
LINKS:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Had to change in order to solve my issue (which I still don't know):
function getMensagem() {
let valueMensagem = document.getElementById('mensagem').value;
if (valueMensagem != 0) {
$('select option:selected').each(function (e) {
$('#ContentPlaceHolder1_ddMensagensCopy').val(valueMensagem);
});
}
else {
$('#ContentPlaceHolder1_ddMensagensCopy').val('');
}
}
function updateSelectMensagem() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = "<option value='0'> Selecione uma mensagem </option>";
oldMessage.forEach(element => {
select.innerHTML += `<option class='dropdown-item'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItemMensagem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelectMensagem();
text.value = ''
}
}
}
updateSelectMensagem()
<div class="col-4">
<div class="dropdown-boleto">
<select id="mensagem" class="btn btn-secondary select">
<option value="0">Selecione uma mensagem</option>
</select>
</div>
</div>
.select option {
background: white;
color: #212529;
}
In fact, everything works as expected
https://codesandbox.io/s/shy-cookies-1xt96?file=/index.html
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 three issue in this app.
First issue is that the show button doesn't change its name to "show offer" when the app is closed after we open it.
Second, the app doesn't prevent a user from clicking second and third button. He can click only one offer, but now the user can click on every.
Third, the user can highlight a new offer by clicking once, then he can hide the highlight, but cannot highlight it again and never. Appreciate any help.
//// hide offer before the Dom is loaded
//$('ul').hide()
$(document).ready(function() {
function showHideOffer() {
$('ul').slideToggle();
}
//click to show offers
$('.card').on('click', '.showOffers', showHideOffer, function() {
$('.showOffers').html('Hide Offers');
});
//click to hide offers - change name to show offers doesn't work!!
$('.card').on('click','.showOffers', showHideOfferfunction() {
$('.showOffers').html('Show Offers');
});
// click to book, to show info and close button and span
$('li').on('click', 'button', function(){
var offerName = $(this).closest('.tour').data('name');
var offerPrice = $(this).closest('.tour').data('price')
var message = $('<ol class="breadcrumb"><li class="breadcrumb-item active" style="color:#3CB371">Success! You have booked '+offerName+' offer for '+offerPrice+'!</li></ol>');
$(this).closest('.tour').append(message);
$(this).prev().closest('.details').remove();
$(this).remove();
});
// filter new offers by clicking a "new" button
$('#buttons').on('click','.filterNew', function() {
$('.tour').filter('.newOffer').addClass('highlightnew');
$('.highlightpopular').removeClass('highlightpopular');
//click second time and the highlight is hidden
$('#buttons').on('click', '.filterNew', function() {
$('.highlightnew').removeClass('highlightnew');
});
});
// filter by popular offers
$('#buttons').on('click', '.filterPopular', function() {
$('.tour').filter('.popular').addClass('highlightpopular');
$('.highlightnew').removeClass('highlightnew');
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GuidedTours</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">
<style>
.selected {
color: red;
}
.highlightnew {
background: #3D9970;
}
.highlightpopular {
background: #39CCCC;
}
ul {
display:none;
}
</style>
</head>
<body>
<div class="container">
<h2>Guided Tours</h2>
<hr>
<div id="tours" class="card">
<!-- click to show -->
<button type="button" value="Show Offers" class="btn showOffers btn-primary btn-sm">Show Offers</button>
<ul class="list-group list-group-flush">
<li class="usa tour newOffer list-group-item"; data-name="New York" data-price="$550">
<h3>New York, New York</h3>
<span class="details badge badge-success">$1,899 for 7 nights</span>
<button class="book btn btn-primary">Book Now</button>
</li>
<li class="europe tour newOffer list-group-item" data-name="Paris" data-price="$450">
<h3>Paris, France</h3>
<span class="details badge badge-success">$2,299 for 7 nights</span>
<button class="book btn btn-primary">Book Now</button>
</li>
<li class="asia tour popular list-group-item" data-name="Tokyo" data-price="$650">
<h3>Tokyo, Japan</h3>
<span class="details badge badge-success">$3,799 for 7 nights</span>
<button class="book btn btn-primary">Book Now</button>
</li>
</ul>
<ul id="buttons" class="list-group list list-group-flush">
<button class="filterNew btn btn-info">New</button>
<button class="filterPopular btn btn-info">Popular</button>
</ul>
</div>
</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="guidedtours.js"></script>
</body>
</html>
First Issue Solve : Checkout Here :
Change the code to
$('.card').on('click', '.showOffers', showHideOffer, function() {
//$('.showOffers').html('');
$(this).text( $(this).text() == 'Hide Offers' ? "Show Offers" : "Hide Offers");
});
Instead Of :
$('.card').on('click', '.showOffers', showHideOffer, function() {
$('.showOffers').html('Hide Offers');
});
//click to show offers
$('.card').on('click', '.showOffers', showHideOffer, function() {
//$('.showOffers').html('');
$(this).text( $(this).text() == 'Hide Offers' ? "Show Offers" : "Hide Offers");
});
//click to hide offers - change name to show offers doesn't work!!
$('.card').on('click','.showOffers', showHideOffer);
// click to book, to show info and close button and span
$('li').on('click', 'button', function(){
var offerName = $(this).closest('.tour').data('name');
var offerPrice = $(this).closest('.tour').data('price')
var message = $('<ol class="breadcrumb"><li class="breadcrumb-item active" style="color:#3CB371">Success! You have booked '+offerName+' offer for '+offerPrice+'!</li></ol>');
$(this).closest('.tour').append(message);
$(this).prev().closest('.details').remove();
$(this).remove();
});
// filter new offers by clicking a "new" button
$('#buttons').on('click','.filterNew', function() {
$('.tour').filter('.newOffer').addClass('highlightnew');
$('.highlightpopular').removeClass('highlightpopular');
//click second time and the highlight is hidden
$('#buttons').on('click', '.filterNew', function() {
$('.highlightnew').removeClass('highlightnew');
});
});
// filter by popular offers
$('#buttons').on('click', '.filterPopular', function() {
$('.tour').filter('.popular').addClass('highlightpopular');
$('.highlightnew').removeClass('highlightnew');
});
function showHideOffer() {
$('ul').slideToggle();
}
.selected {
color: red;
}
.highlightnew {
background: #3D9970;
}
.highlightpopular {
background: #39CCCC;
}
ul {
display:none;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<h2>Guided Tours</h2>
<hr>
<div id="tours" class="card">
<!-- click to show -->
<button type="button" value="Show Offers" class="btn showOffers btn-primary btn-sm">Show Offers</button>
<ul class="list-group list-group-flush">
<li class="usa tour newOffer list-group-item"; data-name="New York" data-price="$550">
<h3>New York, New York</h3>
<span class="details badge badge-success">$1,899 for 7 nights</span>
<button class="book btn btn-primary">Book Now</button>
</li>
<li class="europe tour newOffer list-group-item" data-name="Paris" data-price="$450">
<h3>Paris, France</h3>
<span class="details badge badge-success">$2,299 for 7 nights</span>
<button class="book btn btn-primary">Book Now</button>
</li>
<li class="asia tour popular list-group-item" data-name="Tokyo" data-price="$650">
<h3>Tokyo, Japan</h3>
<span class="details badge badge-success">$3,799 for 7 nights</span>
<button class="book btn btn-primary">Book Now</button>
</li>
</ul>
<ul id="buttons" class="list-group list list-group-flush">
<button class="filterNew btn btn-info">New</button>
<button class="filterPopular btn btn-info">Popular</button>
</ul>
</div>
</div>
To Resolve your first issue modify your function like below
var ValuesShowOrHidden = 0;
$('.card').on('click', '.showOffers', showHideOffer, function () {
if (ValuesShowOrHidden == 0) {
$('.showOffers').html('Hide Offers');
ValuesShowOrHidden = 1;
}
else if (ValuesShowOrHidden==1) {
$('.showOffers').html('Show Offers');
ValuesShowOrHidden = 0;
}
});
For the Second Issue try the below modification in your function
$('li').on('click', 'button', function () {
var offerName = $(this).closest('.tour').data('name');
var offerPrice = $(this).closest('.tour').data('price')
var message = $('<ol class="breadcrumb"><li class="breadcrumb-item active" style="color:#3CB371">Success! You have booked ' + offerName + ' offer for ' + offerPrice + '!</li></ol>');
$(this).closest('.tour').append(message);
$(this).prev().closest('.details').remove();
$(this).remove();
$('li').unbind("click");
});