Button label equals to its id - javascript

Is it possible to make the label of the button the same as its ID?
This would save some work. The name Products and id is the same. So, is it possible to make the button using only id with something like {{this.id}}??
<button type="button" id="Products" class="btn btn-link">
Products
</button>

It does not seem like something that would really save you a lot of work, but you could do it using Javascript.
const buttons = document.getElementsByTagName('button');
for (let i = 0; i < buttons.length; i++) {
buttons[i].innerHTML = buttons[i].id;
}
<button id="hello-world"></button>
<button id="hello-other-world"></button>
<button id="hello-another-world"></button>
<button id="bye-world"></button>
Get all the buttons on the page, for each button, make the inner HTML take the value of the ID. You could edit it to remove the dash, capitalize or modify as you want.

Try this function using vanilla javascript:
function fillButtonLabel(buttonId) {
var button = document.getElementById(buttonId);
button.innerHTML = button.id;
}
https://jsfiddle.net/nbk3hzqp/1/

Related

How can I automatically file an input box and click a search button?

I tried to fill a search input field with some text and hit the search button with this code:
document.getElementsByName('search')[0].value = '1234978';
document.getElementsByClassName('js_search_button')[0].click();
I see my text in the box and the button gets hit. But the data from the input box, was not submited.
Maybe the website has a protection, so that only keytrokes are accepted.
To crosscheck this I tried this code:
var iButton = document.getElementsByClassName('js_search_button')[0];
iButton.addEventListener('click', simulateInput);
function simulateInput() {
var inp = document.getElementsByName("search")[0];
var ev = new Event('input');
inp.value =inp.value + '1234978';
inp.dispatchEvent(ev);
}
Here I get the right result if I manualy click the searchbutton with automaticly filled in the number.
I it possible to automate the click in this scenario, too ?
This is not an answer, because of code sample I posted it as answer.
Are you selecting the right element for clicking? As you can see I click the buttons programmatically.
function clicked(val) {
console.log('button clicked:', val)
}
document.querySelectorAll(".txt")[0].value = 5;
document.querySelectorAll('.btn')[1].click()
document.querySelectorAll('.btn')[2].click()
document.querySelectorAll('.btn')[0].click()
document.getElementsByClassName('btn')[3].click()
<input class='txt' type='text' />
<button class="btn" onclick="clicked(1)">a</button>
<button class="btn" onclick="clicked(2)">b</button>
<button class="btn" onclick="clicked(3)">c</button>
<button class="btn" onclick="clicked(4)">d</button>

HTML onclick function not working for a button

So I'm making a website, and I have some buttons that scroll to certain parts of a page. I have 5 buttons, and all of them have the exact same code except for their names. One of the buttons is broken and doesn't do anything, even though its code is the same as the working ones.
Here is my HTML:
About Us
<div class = "OurMethodsBar">
<button class = "OurMethodsButton" onclick = "ScrollTo(OurMethodsAnchor)">
Our Methods
</button>
</div>
<div class = "InvestBar">
<button class = "InvestButton" onclick = "ScrollTo(InvestAnchor)">
Invest
</button>
</div>
<div class = "ContactUsBar">
<button class = "ContactUsButton" onlclick = "ScrollTo(ContactUsAnchor)">
Contact Us
</button>
</div>
<div class = "MoreInformationBar">
<button class = "MoreInformationButton" onclick = "ScrollTo(MoreInfoAnchor)">
More Info
</button>
</div>
Here is my JS:
var AboutUsAnchor = document.getElementById("AboutUsAnchor");
var OurMethodsAnchor = document.getElementById("OurMethodsAnchor");
var InvestAnchor = document.getElementById("InvestAnchor");
var ContactUsAnchor = document.getElementById("ContactUsAnchor");
var MoreInfoAnchor = document.getElementById("MoreInfoAnchor");
function ScrollTo(Element) {
Element.scrollIntoView(true);
}
ScrollTo(AboutUsAnchor);
The broken button is the ContactUsButton which is supposed to scroll to the ContactUsAnchor.
If I manually use my ScrollTo function and input the ContactUsAnchor, it still works, but when I try to hit the button, it doesn't work.
I'd rather change approach and rewrite your function to get a string and get the element by ID later.
function ScrollTo(element) {
document.getElementById(element).scrollIntoView(true);
}
And then in your buttons just pass the string containing the ID in single quotes '
<button class = "ContactUsButton" onclick = "ScrollTo('ContactUsAnchor')">
Contact Us
</button>
And as others have pointed out, fix that onlclick :P

I want to know the value of the button I pressed in a table

I have an array of buttons arranged in each row of a table. When I click on a certain button, I want to know the row number the clicked button is positioned.
I add each time a row to existing table, where in each row there is a button. I tried to put each button in an array, so when I click on one of them, I will get the index number from the array. Didn't succeed
var btns[];
var btn=document.createElement("BUTTON");
btn.innerHTML="Edit";
btns.push(btn);
cell1.appendChild(btns[btn_num]);
btn_num=btn_num+1;
I expect to get the row number, so I can edit a specific row in a table.
You don't need to store button in memory var btns. I see a couple of practical ways to do this:
Create button with a class name
<button class="btn-edit" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" onclick="BtnEditClick(this)">Edit</button>
<script>
function BtnEditClick(clickedElement){
var btns = document.getElementsByClassName("btn-edit")
var result = -1
for(var i=0;i<btns.length; i++) {
if(clickedElement == btns[i]){
result = i
}
}
if(result != -1)
alert("found " + result)
else
alert("not found")
}
</script>
Reference to the value using data-attr in html5
<button class="btn-edit" data-index="0" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" data-index="1" onclick="BtnEditClick(this)">Edit</button>
<button class="btn-edit" data-index="2" onclick="BtnEditClick(this)">Edit</button>
<script>
function BtnEditClick(clickedElement){
var index = clickedElement.getAttribute("data-index")
alert("click index: " + index)
}
</script>
Pass index directly to the function
<button class="btn-edit" data-index="0" onclick="BtnEditClick(0)">Edit</button>
<button class="btn-edit" data-index="1" onclick="BtnEditClick(1)">Edit</button>
<button class="btn-edit" data-index="2" onclick="BtnEditClick(2)">Edit</button>
<script>
function BtnEditClick(index){
alert("clicked on item:" + index)
}
</script>
Yes there are still a few other ways. For myself most of the time I use the second approach that get the element ( the button object that get clicked ) and then read the data that I want from data-attr ( you can define any data-attr you want e.g data-index, data-id ). This is very convenient, you will find it useful because sometimes you might need more data than just an index of the element inside the list. I hope it helps
One possible approach is: for each added button you can add an the HTML attribute id equal table row. Besides that, you can add the HTML attribute onclick="onClickButton(this.id)" to the created button. So you can use the folowing script to get the id value when the button gets clicked:
<script>
function onClickButton(e) {
console.log(e);
}
</script>

Search for contents of element and click its parent

I am trying to create an extention which clicks on an item of the price given by the user. Here is the relevant popup.html:
<input style="display:none" /><input type="text" id="userInput" value='' />
<button id="clickme">Run</button>
When 'clickme' is clicked, it runs this popup.js:
document.getElementById('clickme').addEventListener('click', function() {
var price = '$'+ document.getElementById("userInput").value+".00";
alert(price);
$("p:contains("price")").parentNode.click();
});
If you type the desired price in in the form as 48, it returns an alert with the value $48.00.
It then shuold click on the item of that price, however this currently isn't working. Here is the code of the relevant part of the website which I am trying to run my extention on (not my website):
<div class="grid__item wide--one-fifth large--one-quarter medium-down--one-half">
<a href="/collections/1seventeenweek7/products/copy-of-supreme-dazzle-warm- up-top-red" class="grid-link text-center">
<p class="grid-link__title">Supreme Corner Cap Light Blue</p>
<p class="grid-link__meta">
<span class="visually-hidden">Regular price</span>
$48.00
</p>
</a>
</div>
I am trying to get it to search for the p element containing $48.00, and then click on the a element which is the parent element, but this is not currently working. What am I doing wrong? - thanks
Here you go. This will work!
document.getElementById('clickme').addEventListener('click', function() {
var price = '$'+document.getElementById('userInput').value+'.00'
var metas = document.getElementsByClassName('grid-link__meta')
alert(price)
for (let i = 0; i < metas.length; i++) {
if (metas[i].innerHTML.includes(price)) metas[i].parentNode.click()
break
}
})
Personally, I'd really like to use something like the following, yet I forgot that getElementsByClassName doesn't return an array, but rather a NodeList object.
var price = '$'+document.getElementById('userInput').value+'.00'
var metas = document.getElementsByClassName('grid-link__meta')
var match = metas.find((curr) => curr.innerHTML.includes(price))
match.parentNode.click()

Adding div elements to an array on button click

The page I am working on contains a div element with the id "exam", a button with the id of "copy" and a second button with the id "array". The div element contains the text "Exam 1" and when the "copy" button is clicked, this div is duplicated each time the button is clicked. The "array" button is supposed to add each of these "exam" divs to an array and use the alert function to display the length of the array. I can't figure out how to go about having these div elements added to an array when the button is clicked.
Here is the HTML I have so far (this also includes Javascript and CSS):
<html>
<head>
<title>Exam 1 Tanner Taylor</title>
<style type="text/css">
#exam {
border: 2px double black;
}
</style>
</head>
<body>
<div id="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()" >
<input type="button" id="array" value="Get Array" onclick="makeArray()">
</body>
<script type = "text/javascript">
var TTi = 0;
var TToriginal = document.getElementById("exam");
function copy() {
var TTclone = TToriginal.cloneNode(true);
TTclone.id = "exam";
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
var TTexam[];
for(var TTindex = 0; TTindex < TTexam.length; ++TTindex) {
}
}
</script>
</html>
There's more to it, but I removed the parts that didn't actually deal with this problem. As you can see, I've started the makeArray() function, but wasn't really sure where to go from there, I feel like this is the function I need the most help with. Any suggestions?
I would add a class name to the exam div and use getElementsByClassName() to get all the divs with that class.
HTML:
<body>
<div id="exam" class="exam">
Exam 1
</div>
<input type="button" id="copy" value="Make Copy" onclick="makeCopy()" />
<input type="button" id="array" value="Get Array" onclick="makeArray()" />
</body>
JS:
var TTi = 0;
var TToriginal = document.getElementById("exam");
function makeCopy() {
console.log('copy');
var TTclone = TToriginal.cloneNode(true);
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
var TTexam = document.getElementsByClassName("exam");
alert(TTexam.length);
for(var TTindex = 0; TTindex < TTexam.length; ++TTindex) {
console.log(TTexam[TTindex]);
}
}
You can replace the alert() and console.log() with whatever business logic you want.
Check out a working fiddle at http://jsfiddle.net/JohnnyEstilles/w6fdm5th/.
Some suggestions and something you maybe can proceed from: First, id-attributes should be unique, so it'd be better to use classnames:
<div class="exam">Exam 1</div>
<input type="button" id="copy" value="Make Copy" onclick="copy()">
<input type="button" id="array" value="Get Array" onclick="makeArray()">
For the script:
var TTexam = [];
function copy() {
var TToriginal = document.getElementsByClassName("exam")[0];
var TTclone = TToriginal.cloneNode(true);
TToriginal.parentNode.appendChild(TTclone);
}
function makeArray() {
alert(TTexam.length);
for (var TTindex = 0; TTindex < document.getElementsByClassName("exam").length; TTindex++)
{
TTexam.push(document.getElementsByClassName("exam")[TTindex]);
}
alert(TTexam.length);
}
That's just for starters. TTexam is an array defined global, just in case it should be accessible for both functions. But question is really what exactly you want to do - if you want to generate the array only once when you finished adding divs or if it should be possible to generate a new array containing all divs each time you click 'Get Array'. Then the array should be defined in the makeArray()-function.
To avoid having the same divs as doubles in the array in case of global definition, it would e.g. be possible to add a data-attribute with a counter to each newly created div and, when creating the array a second time, only add the new ones. Or it would be possible to add each new div to the array when it's added using TTexam.push(TTclone); in the copy()-function.

Categories

Resources