A single js function to create 9 different alerts on buttons - javascript

I am creating a button in a div so when we click it show us detailed information of the person given in API. But now I am confused about how to do this like I have 9 divs and every div has its own button, I am using onClick() on button it works well for the single button but to show information of 9 people if I use 9 different onClick() function it will create redundancy in code so how a single function can handle all this?
HTML
<button type="button" class="button" onclick="show" name="button">Details</button>

You can leverage event bubbling and addEventListener API to do that with only one event listener and only one handler.
const root = document.getElementById('root');
const handler = (e) => {
// target IS THE CLICKED BUTTON.
const {target} = e;
if (target.tagName === 'BUTTON') {
alert(`${target.name} has been pressed.`);
}
};
root.addEventListener('click', handler);
<div id='root'>
<div>
<button type="button" class="button" name="Button 1">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 2">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 3">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 4">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 5">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 6">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 7">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 8">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 9">Details</button>
</div>
</div>

You could try something like this. Don't forget to defer execution when importing into your html file:
const alert = (e) => {
window.alert(e.target.innerHTML);
}
const buttons = document.getElementsByClassName("button");
for (const btn of buttons) {
btn.addEventListener("click", alert);
}

You can use querySelectorAll(). That means you select all of
the buttons. What you must pass in the braces is a CSS selector like
this: const button = document.querySelectorAll('button').
After that you must use forEach(). That is a callback function and that will apply the command/event on every single button. e.g. what you're gonna do if x button gets clicked.
Using querySelectorAll & forEach together is the most recommended for these use cases.
const button = document.querySelectorAll('.button');
button.forEach(e => {
// e here means every single button, doesn't matter which one
e.addEventListener('click', () => {
document.querySelector('h1').textContent += 1;
}
)}
)
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<h1>Result here: </h1>

if every div have its on button so you can find its id on button click
<button type="button" id="btn1" class="button" onclick="show(this)" name="button">Details</button>
here is javascript function
function show(btn){
const id = btn.getAttribute("id"); // here you will get "btn1"
if(id == "btn1"){
}
}

Related

How to forward input ref to a function by onClick button

I am trying to forward input ref text/string data to a function by clicking the button. but I cant forward or pass the data to my function by using button
--questionRef is my ref input data
--answerQuestion is my function
<input ref={questionRef} size="80"></input>
<button type="button" onClick={answerQuestion} >Enter</button>
I tried to use my button for forward the questionRef input to answerQuestion function but it failed. Also it works when I click enter on my keyboard
Pretty simply:
<input ref={questionRef} size="80"></input>
<button
type="button"
onClick={() => answerQuestion(questionRef)}
>Enter
</button>
Eventually, you can include also the onClick event to your function, depends on what you need to do with it:
<input ref={questionRef} size="80"></input>
<button
type="button"
onClick={(e) => answerQuestion(questionRef, e)}
>
Enter
</button>
Based on Junius L. comment:
const questionRef = useRef()
const answerQuestion = () => {
doSomethingWithRef(questionRef) // questionRef is accessible in whole component scope
}
<input ref={questionRef} size="80"></input>
<button
type="button"
onClick={answerQuestion}
>Enter
</button>

Is there a way to make every bouton using a single code

For a school project, I'm coding a porfolio.
I want to use jQuery hide() and show() to have popups that appear after clicking on buttons.
Is there a way, with a single code, to make every HTML element with the class="vignette" and an id="bouton1" show a div with the same number in id (id=popup1).
I don't know if I'm clear, I'm a student in graphic design, and I'm not having a good time.
As far as I can understand from your question, you want to show a modal whose ID is the same number as the button's ID?
You can use this same logic to work with your modal instead
// This regex just gets the number part from the ID
const re = /bouton(\d+)/
$('button.vignette').click(e => {
const res = re.exec(e.target.id)
if(res) {
// "popup" + res[1] gives the popup id
$('#content').html("popup" + res[1])
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class = "vignette" id = "bouton1">B1</button>
<button class = "vignette" id = "bouton2">B1</button>
<button class = "vignette" id = "bouton3">B1</button>
<button class = "vignette" id = "bouton4">B1</button>
<div id = "content"></div>
You can create a function that will be added via addEventListener. Alternatively you can add an onclick attribute to the HTML elements whose click you want to handle.
let activeDiv;
function myClick() {
if (activeDiv) activeDiv.classList.add("invisible");
(activeDiv = document.getElementById(this.id.replace("bouton", "popup"))).classList.remove("invisible");
}
let buttons = document.getElementsByClassName("vignette");
for (let button of buttons) {
button.addEventListener("click", myClick);
}
.invisible {
display: none;
}
<input type="button" id="bouton1" class="vignette" value="First">
<input type="button" id="bouton2" class="vignette" value="Second">
<input type="button" id="bouton3" class="vignette" value="Third">
<input type="button" id="bouton4" class="vignette" value="Fourth">
<input type="button" id="bouton5" class="vignette" value="Fifth">
<input type="button" id="bouton6" class="vignette" value="Sixth">
<input type="button" id="bouton7" class="vignette" value="Seventh">
<input type="button" id="bouton8" class="vignette" value="Eigth">
<input type="button" id="bouton9" class="vignette" value="Ninth">
<div id="popup1" class="invisible">1</div>
<div id="popup2" class="invisible">2</div>
<div id="popup3" class="invisible">3</div>
<div id="popup4" class="invisible">4</div>
<div id="popup5" class="invisible">5</div>
<div id="popup6" class="invisible">6</div>
<div id="popup7" class="invisible">7</div>
<div id="popup8" class="invisible">8</div>
<div id="popup9" class="invisible">9</div>
suppose you have 10 buttons with class vignette then you code would be:
$.each( "button.vignette", function( i, obj) {
$(obj).attr( "id", i ).on('click',function(){
$('#popup'+i).toggle();
});
});
You can replace toggle() function with your code as desired.

How to get value of clicked button in calculator

I have multiple buttons containing different values
<button data-action="digit" class="button" id="1">1</button>
<button data-action="digit" class="button" id="2">2</button>
<button data-action="digit" class="button" id="3">3</button>
And I want to get these buttons to display on my calculator using this in javascript:
function digit_pressed(digit) {
console.log("digit pressed: " + digit);
}
But I am unsure what to add to my function. Any help would be greatly appreciated :)
You can use querySelectorAll for select all button then use addEventListener for add click event and last step use textContent for number of digit and call function.
document.querySelectorAll('button').forEach(el =>{
el.addEventListener('click', () =>{
digit_pressed(el.textContent);
});
});
function digit_pressed(digit) {
console.log("digit pressed: " + digit);
}
<button data-action="digit" class="button" id="1">1</button>
<button data-action="digit" class="button" id="2">2</button>
<button data-action="digit" class="button" id="3">3</button>
Reference:
querySelectorAll
addEventListener
textContent

How could I avoid WYSIWYG buttons to follow the link

I am trying to build an editor. Once I click an any button ( bold, or italic,...) it follows the link. Here is what I have tried out.
function execCmd(command) {
document.execCommand(command, false, null);
}
function execCommandWithArg(command, arg) {
document.execCommand(command, false, arg);
}
<form>
<div id="text_section">
<button onclick="execCmd('bold');"><i class="fas fa-bold"></i></button>
<button onclick="execCmd('italic');"><i class="fas fa-italic"></i></button>
<button onclick="execCommandWithArg('createLink', prompt('Enter a RUL','http://'));"><i class="fas fa-link"></i></button>
<button onclick="execCmd('unlink');"><i class="fas fa-unlink"></i></button>
<div class="p-2" contenteditable="true" id="content_text" style="border:solid; width:200px; heigth:100px;"></div>
</div>
<div class="form-group">
<input type="button" name="submit" value="Post text" id="submit" class="btn py-3 px-4 btn-primary">
</div>
</form>
How could I use e.preventDefault(); function on it ?
This code lines seem to work as expected, but the problem is not solved in my programm.
I think e.preventDefault(); might solve the problem.
Thank you for taking the time to answer my question.
Your callback needs to return false.
Try
<button onclick="execCmd('bold'); return false;">
Or
<button onclick="return execCmd('bold');">
function execCmd(command)
{
document.execCommand(command, false, null);
return false;
}
When button element is inside a form element it acts as submit unless it's type attribute say different (etc: reset, button).
So a quick fix will be to set type="button to your editing buttons:
<button type="button" onclick="execCmd('bold');">
<i class="fas fa-bold"></i>
</button>
Enjoy code!

getElementById not returning current text from text area in javascript function

My function document.getelementbyid is not returning the current value of the textarea from HTML page
HTML:
<div class="modal-content">
<h4 class="modal-title">PersonName</h4>
<div id = 'person_name' class="modal-body">
<p><%=person['person_name']%></p>
</div>
<h4 class="modal-title">Person Description</h4>
<textarea id="person_descr" style="overflow: scroll; height:
100px;"></textarea>
<button name="button" type="button" class="save"
class="btn btn-info"
onClick="updateDescription('<%=person['person_name']%>')">
save description </button>
</div>
JavaScript:
function updateDescription(person_name) {
var person_name = person_name
var person_descr = document.getElementById("person_descr").value;
alert(person_name)
alert(person_descr)
}
In text-area I can edit the existing value and Save that modified value into DB.
When clicked on 'save description' button it is returning 1st element which is passing to text-area but need to get current value of text-area
Escape the ' inside your onClick function call.
onClick="updateDescription('<%=person[\'person_name\']%>')"
Your quotations inside your onclick aren't being escaped:
<button name="button" type="button" class="save" class="btn btn-info" onClick="updateDescription('<%=person[\'person_name\']%>')">save description</button>
When document load your textarea still is empty it show empty at alert. You need set value by person_descr.value = person_name;
function updateDescription(person_name){
var person_name= person_name
var person_descr= document.getElementById("person_descr");
alert(person_name)
alert(person_descr.value);
person_descr.value = person_name;
alert(person_descr.value)
}
<div class="modal-content">
<h4 class="modal-title">PersonName</h4>
<div id = 'person_name' class="modal-body">
<p>aaa</p>
</div>
<h4 class="modal-title">Person Description</h4>
<textarea id="person_descr" style="overflow: scroll; height:
100px;"></textarea>
<button name="button" type="button" class="save"
class="btn btn-info"
onClick="updateDescription('aaa')">
save description </button>
</div>
to get a html text area value, you can use the value property:
document.getElementById("id").value
also you have to escape your html quotes:
<button name="button" type="button" class="save"
class="btn btn-info"
onClick="updateDescription('<%=person[\'person_name\']%>')">
save description </button>
Avoid the limitations and awkward syntax of onevent attributes -- use onevent properties or event listeners instead. The following demo uses an onevent property.
BTW the button is invalid it has two class attributes:
<button name="button" type="button" class="save"
class="btn btn-info"
onClick="updateDescription('<%=person['person_name']%>')">
save description </button>
Demo
document.querySelector('.btn').onclick = updateDesc;
function updateDesc(e) {
var personName = document.getElementById("personName");
var personDesc = document.getElementById("personDesc");
console.log(personName.textContent);
console.log(personDesc.value);
}
* {
margin: 0;
padding: 0
}
<div class="modal-content">
<h4 class="modal-title">Person Name</h4>
<div id='personName' class="modal-body">
<p>
John Doe
</p>
</div>
<h4 class="modal-title">Person Description</h4>
<textarea id="personDesc" style="overflow: scroll; height: 100px;"></textarea><br>
<button name="button" type="button" class="btn btn-info save">Save Description</button>
</div>

Categories