how to call a nested jquery function from html? - javascript

I am calling a addtext() function from html onclick() that is nested inside add() function. I want to call the second function. How can i approach this?
Here i have a link with add() function that shows a textbox and an ADD button with addtext().
The add() function checks for text and if text is present, it generates a new text box.
Now i want the add button to take that text and from the textbox and set it in replacement of the textbox.
clicking the ADD button will take it to addtext() which is inside the add() function.
Html code:
<a id = "newcard" href="#" onclick="add()" >
<b style ="color: #444444">Add Card...</b>
</a>
<div>
<span id = "show-ta"><textarea id="txtarea" style ="
display:none"></textarea><span>
<span id = "newbutton"><button id = "firstbutton" class ="btn btn-
success nbutton"onclick="addtext()" style ="display:none">Add</button>
</span>
</div>
Jquery code:
function add(){
var newTextBoxDiv = $(document.createElement('textarea'));
if ( $('#txtarea').css('display') == 'none' ){
$('#txtarea').css('display', 'block');
}
if ( $('#firstbutton').css('display') == 'none' ){
$('#firstbutton').css('display', 'block');
}
var wrapper = $('#show-ta');
var button = $(document.createElement('button'));
if(wrapper.find('textarea').last().val().length) {
var x =wrapper.find('textarea').last().val();
function addtext()
{
}
wrapper.append('<textarea class="t-one"></textarea>');
wrapper.append('<button class ="btn btn-success
nbutton">Add</button>').appendTo('#cardarea').insertAfter('#cardtitle');;
//button.addClass("btn btn-success");
wrapper.appendTo("#cardarea").insertAfter('#cardtitle');
wrapper.addClass('t-one');
// var text =$('textarea:nth-last-child(2)').val().length;
//wrapper.addClass('nbutton');
}

You have to assign the nested function to a property like this addText.add = add; then you can call that function in onClick event.
function addText()
{
// irrelevant code here
function add(arg){
console.log( arg );
}
addText.add = add;
}
addText();
<button onclick="addText.add('Nested function')">Click me</button>
EDIT:
Updated the snippet as per your code
function add() {
var newTextBoxDiv = $(document.createElement('textarea'));
if ($('#txtarea').css('display') == 'none') {
$('#txtarea').css('display', 'block');
}
if ($('#firstbutton').css('display') == 'none') {
$('#firstbutton').css('display', 'block');
}
var wrapper = $('#show-ta');
var button = $(document.createElement('button'));
if (wrapper.find('textarea').last().val().length) {
var x = wrapper.find('textarea').last().val();
function addtext() {
alert('working');
}
add.addtext = addtext;
wrapper.append('<textarea class="t-one"></textarea>');
wrapper.append('<button class="btn btn-success nbutton ">Add</button>').appendTo('#cardarea').insertAfter('#cardtitle');;
wrapper.appendTo("#cardarea").insertAfter('#cardtitle');
wrapper.addClass('t-one');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<a id="newcard" href="#" onclick="add()">
<b style="color: #444444">Add Card...</b>
</a>
<div>
<span id="show-ta">
<textarea id="txtarea" style ="display:none">
</textarea>
</span>
<span id="newbutton">
<button id = "firstbutton" class ="btn btn-success nbutton" onclick="add.addtext()" style="display:none">Add
</button>
</span>
</div>

Related

How to change the innerHTML of various divs when clicking on various buttons?

In my web-page I have various buttons (in the class .addbutton). When the first of these is clicked, a <div> appears with a drop-down, from which the user can select any of 2 options (#p1, `#p2), which vary depending on which button was clicked.
When each of these options is clicked, I want it to appear in the <div> that corresponds with the initial .addbutton that was clicked. (e.g if the first .addbutton is clicked (#bradd) I want the options selected in the first div (#bdiv))I managed to do this so that they always appear in the #bdiv, no matter what .addbutton was clicked, but I can't work out how to make each appear in the corresponding one.
JS to set the innerHTML of the 2 options
document.getElementById("bradd").onclick = function() {
document.getElementById("p1").innerHTML = "Cereal"
document.getElementById("p2").innerHTML = "Juice"
}
document.getElementById("mmadd").onclick = function() {
document.getElementById("p1").innerHTML = "2x small fruit"
document.getElementById("p2").innerHTML = "Big fruit"
}
JS to change the innerHTML of the first div (#bdiv)
document.getElementById("p1").onclick = function() {
var newItem = document.createElement("div")
newItem.innerHTML = document.getElementById("p1").innerHTML document.getElementById("bdiv").appendChild(newItem)
}
document.getElementById("p2").onclick = function() {
var newItem = document.createElement("div")
newItem.innerHTML = document.getElementById("p2").innerHTML
document.getElementById("bdiv").appendChild(newItem)
}
My HTML:
<h1>Meal Plan Customizer</h1>
<div id="list">
<input type="checkbox">
<p>Breakfast:</p>
<button class="addbutton" id="bradd">+</button>
<div id="bdiv"></div>
<br>
<input type="checkbox">
<p>Mid-Morning:</p>
<button class="addbutton" id="mmadd">+</button>
<div id="mdiv"></div>
<br>
<input type="checkbox">
<div id="dropdownList">
<p id="p1">Option1</p><br><br>
<p id="p2">Option2</p><br><br>
</div>
</div>
</div>
Your code should work.
Please check this:
https://jsfiddle.net/oliverdev/3wsfgov1/
If your code is not working, it is because Javascript code is loaded before loading the HTML.
You can modify the Javascript code like this:
window.onload = function(e){
document.getElementById("bradd").onclick = function() {
document.getElementById("p1").innerHTML = "Cereal"
document.getElementById("p2").innerHTML = "Juice"
}
document.getElementById("mmadd").onclick = function() {
document.getElementById("p1").innerHTML = "2x small fruit"
document.getElementById("p2").innerHTML = "Big fruit"
}
}
It will work for you
You are making this far more complicated and repetitive than necessary.
By storing your data in a structured object and using classes for the content elements you can make generic event listeners for all of this
Following is by no means complete but will give you a good idea how to approach something like this
var data = {
bradd: {
p1: "Cereal",
p2: "Juice"
},
mmadd: {
p1: "2x small fruit",
p2: "Big fruit"
}
}
var selectedButton = null;
var opts = document.querySelectorAll('#dropdownList p');
for (let p of opts) {
p.addEventListener('click', updateContent)
}
// generic event handler for all the options
function updateContent() {
const content = selectedButton.closest('.item').querySelector('.content')
content.innerHTML = this.innerHTML
togglePopup()
}
document.querySelector('#xbutton').addEventListener('click', togglePopup)
// generic event handler for all buttons
function addButtonClicked() {
selectedButton = this;// store selected for use when option selected
var wantedData = data[selectedButton.id];
for (let p of opts) {
p.innerHTML = wantedData[p.id]
}
togglePopup();
}
for (let btn of document.getElementsByClassName("addbutton")) {
btn.addEventListener("click", addButtonClicked)
}
function togglePopup() {
var popStyle = document.getElementById("addPopUp").style;
popStyle.display = popStyle.display === "block" ? 'none' : 'block'
}
#addPopUp {
display: none
}
<h1>Meal Plan Customizer</h1>
<div id="list">
<div class="item">
<p>Breakfast:</p>
<button class="addbutton" id="bradd">+</button>
<div class="content"></div>
</div>
<div class="item">
<p>Mid-Morning:</p>
<button class="addbutton" id="mmadd">+</button>
<div class="content"></div>
</div>
</div>
<div id="addPopUp">
<h3 id="h3">Select what you would like to add:</h3>
<span id="xbutton"><strong>×</strong></span>
<div class="dropdown">
<div id="dropdownList">
<p id="p1">Option1</p>
<p id="p2">Option2</p>
<!-- <p id="p3">Option3</p><br><br>
<p id="p4">Option4</p>-->
</div>
</div>
</div>

How to add and remove a class to a div element plain javascript

I am trying to add different classes to a div based on what is clicked, which I've managed to do, but need to remove the previously clicked/selected class and replace with the clicked one, Can't seem to get the remove part right. Most of the solutions I've come across are either toggles or adding and removing between two classes, but not 3 or more.
Thanks
This is what I have tried so far and the add part works as expected but when I click a different button it does not remove the previous clicked one
The HTML
<button id="btn-1" data-width="w-1/3">Mobile</button>
<button id="btn-2" data-width="w-2/3">Tablet</button>
<button id="btn-3" data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
The Javascript
let setMobile = document.querySelector('#btn-1');
let setTablet = document.querySelector('#btn-2');
let setDesktop = document.querySelector('#btn-3');
let btns = [setMobile, setTablet, setDesktop];
function getBtnId(btn) {
btn.addEventListener('click', function() {
let frame = document.querySelector('.frame')
frame.classList.add(this.dataset.width)
if(frame.classList.contains(btns)){
frame.classList.remove(this.dataset.width)
}
console.log(this.dataset.width);
});
}
btns.forEach(getBtnId);
Basically, what I am trying to do is a responsive frame which will adjust its width depending on what is clicked.
You can store the current class in a variable and use the remove() to remove the previous class on each click.
let setMobile = document.querySelector('#btn-1');
let setTablet = document.querySelector('#btn-2');
let setDesktop = document.querySelector('#btn-3');
let btns = [setMobile, setTablet, setDesktop];
var currentClass;
function getBtnId(btn) {
btn.addEventListener('click', function() {
let frame = document.querySelector('.frame')
if (currentClass) {
frame.classList.remove(currentClass);
}
currentClass = this.dataset.width;
frame.classList.add(currentClass);
console.log(this.dataset.width);
});
}
btns.forEach(getBtnId);
<button id="btn-1" data-width="w-1/3">Mobile</button>
<button id="btn-2" data-width="w-2/3">Tablet</button>
<button id="btn-3" data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
Here's a generalized version to work with multiple elements. I've wrapped each frame and buttons in a section element. Then I've bound the event listeners to the sections and used event bubbling / event delegation to perform the switch. I've also used a data attribute on the target frame to hold the current state.
function setWidthClass(event) {
var newWidth = event.target.dataset.width;
//This identifies a button click with our dataset
if (newWidth) {
//get the target div
var target = this.querySelector(".frame");
//if the target has a class set remove it
if (target.dataset.width) {
target.classList.remove(target.dataset.width);
}
//Add the new class
target.classList.add(newWidth);
//Update the data on the target element
target.dataset.width = newWidth;
}
}
//Add the event listener
var sections = document.querySelectorAll(".varyWidth");
for (var i = 0; i < sections.length; i++) {
sections[i].addEventListener("click", setWidthClass);
}
.w-third {
color: red;
}
.w-half {
color: blue;
}
.w-full {
color: green;
}
<section class="varyWidth">
<button data-width="w-third">Mobile</button>
<button data-width="w-half">Tablet</button>
<button data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
</section>
<section class="varyWidth">
<button data-width="w-third">Mobile</button>
<button data-width="w-half">Tablet</button>
<button data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
</section>
<section class="varyWidth">
<button data-width="w-third">Mobile</button>
<button data-width="w-half">Tablet</button>
<button data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>
</section>
Rather than track the current class, you can also just reset it:
let setMobile = document.querySelector('#btn-1');
let setTablet = document.querySelector('#btn-2');
let setDesktop = document.querySelector('#btn-3');
let btns = [setMobile, setTablet, setDesktop];
function getBtnId(btn) {
btn.addEventListener('click', function() {
let frame = document.querySelector('.frame')
// reset the classList
frame.classList = ["frame"];
frame.classList.add(this.dataset.width)
console.log(this.dataset.width);
});
}
btns.forEach(getBtnId);
<button id="btn-1" data-width="w-1/3">Mobile</button>
<button id="btn-2" data-width="w-2/3">Tablet</button>
<button id="btn-3" data-width="w-full">Desktop</button>
<div class="frame">
Some Content
</div>

Make text appear/disappear on button click [duplicate]

This question already has answers here:
How can I change CSS display none or block property using jQuery?
(15 answers)
Closed 3 years ago.
I'm trying to make the button alternate the text from hidden using 'none' to appear using 'block'. I tried the below but it did not work
<p id='demo' style = 'display: none'>Hello Javascript</p>
<button type='button' onclick="document.getElementById('demo').style.display='block'" >click me</ button>
I want to convert event listener to Javascript and run from there.
Try this, I hope it'll help you out. Thanks
function toggleText() {
var text = document.getElementById("demo");
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
<p id='demo' style='display: none'>Hello Javascript</p>
<button type='button' onclick="toggleText()">Click me</button>
css:
.demo {
display: none;
}
html:
<p id='demo' class='demo'>Hello Javascript</p>
<button type='button'> click me </button>
js:
var tag = document.getElementById('demo');
var button = document.querySelector('button');
button.addEventListener('click', function(){
tag.classList.toggle('demo');
});
Running Snippet:
var tag = document.getElementById('demo');
var button = document.querySelector('button');
button.addEventListener('click', function(){
tag.classList.toggle('demo');
});
.demo {
display: none;
}
<p id='demo' class='demo'>Hello Javascript</p>
<button type='button'> click me </button>
Is it helpful:
var showHide = document.getElementById("showHide");
var demo = document.getElementById("demo");
showHide.onclick = function() {
if (demo.style.display == "block") {
demo.style.display = "none";
} else {
demo.style.display = "block";
}
}
<p id='demo' style='display: none'>Hello Javascript</p>
<button id="showHide">Click Me</button>

error: updating values of elevator and user after clicking button

I am creating one program of the elevator which includes up, down buttons (external functions) and buttons (0 to 5:: internal functions) inside the elevator my external functions are working correctly but when inside elevator user press any button elevator should go to that place. and update the position of user and elevator. But when I press the button(0,1,2,3,4,5) it doesn't work. Can anyone help me to solve the issue. Thanks in advance.
code::
<!DOCTYPE html>
<html lang="en">
<head>
<title>elevator</title>
</head>
<body>
<h2>Internal Functions</h2>
<span>current user position :: </span>
<p id="userPosition"></p>
<span>current elevator position :: </span>
<p id="elevatorPostion"></p>
<button id="btn" onclick="inFunction(0)" value="0">0</button>
<button id="btn" onclick="inFunction(1)" value="1">1</button>
<button id="btn" onclick="inFunction(2)" value="2">2</button>
<button id="btn" onclick="inFunction(3)" value="3">3</button>
<button id="btn" onclick="inFunction(4)" value="4">4</button>
<button id="btn" onclick="inFunction(5)" value="5">5</button>
<h2>External Functions</h2>
user position:
<input type="text" id="userText" name="UserPosition" value="0">
<button onclick="exFunction('up')">UP</button>
<button onclick="exFunction('down')">DOWN</button>
<script>
var userPosition = 0,
elevatorPosition = 4
function exFunction(pressedValue) {
console.log(pressedValue);
var userPosition = document.getElementById("userText").value;
document.getElementById("userPosition").innerHTML = userPosition;
document.getElementById("elevatorPostion").innerHTML = elevatorPosition;
var intervalEle = setInterval(function () {
if (userPosition > elevatorPosition) {
console.log('Elevator position', elevatorPosition);
elevatorPosition++;
} else if (userPosition < elevatorPosition) {
elevatorPosition--;
} else {
elevatorPosition == userPosition;
clearInterval(intervalEle);
}
document.getElementById("userPosition").innerHTML = userPosition;
document.getElementById("elevatorPostion").innerHTML = elevatorPosition;
}, 1000);
}
function inFunction(clickedValue) {
var btnValue = document.querySelector('btn').value;
document.getElementById("userPosition").innerHTML = userPosition;
document.getElementById("elevatorPostion").innerHTML = elevatorPosition;
console.log(btnValue);
var intervalEle2 = setInterval(function () {
if (elevatorPosition > btnValue) {
elevatorPosition--
} else if (elevatorPosition < btnValue) {
elevatorPosition++
} else {
elevatorPosition == btnValue;
clearInterval(intervalEle2)
}
document.getElementById("userPosition").innerHTML = userPosition;
document.getElementById("elevatorPostion").innerHTML = elevatorPosition;
}, 1000)
}
</script>
</body>
</html>
output :
https://i.stack.imgur.com/tKeeL.png
var btnValue = document.querySelector('btn').value;
There are no <btn> elements on your page, so document.querySelector('btn') returns null. You've illegally reused "btn" as an id, so document.getElementById('btn') won't do what you expect either.
You've already got the number of the button that was clicked; you passed it in to inFunction as clickedValue. Just use that.

Hide text with the same button it opened it

how can I hide the text opened while clicking on a button by clicking on the same button ? In other words, the same button should show or hide a text when you click on it.
Here's my code that shows a text :
<h3>
<button class="button" onclick="myFunction()" ><img src="infoicon.png" height="30"></button>
<p id="infos"></p>
<script>
function myFunction() {
document.getElementById("infos").innerHTML = "blablabla";
}
</script>
</h3>
Define a variable to save the button state
var clicked = 0;
function myFunction() {
if(clicked == 0 ) {
document.getElementById("infos").innerHTML = "blablabla";
clicked = 1;
} else {
document.getElementById("infos").innerHTML = "";
clicked = 0;
}
}
<h3>
<button class="button" onclick="myFunction()" ><img src="infoicon.png" height="30"></button>
<p id="infos"></p>
</h3>
Try this out, it worked for me:
function showHide() {
var demo = document.getElementById('demo');
if (demo.innerHTML === "") {
demo.innerHTML = "bla";
} else {
demo.innerHTML = "";
}
}
<p id="demo"></p>
<button onclick="showHide()">Show Hide</button>
Quite simple, using jQuery—
$( "#button" ).click(function() {
$('#text-to-toggle').toggle(200);
});

Categories