Capturing the value of a button - javascript

Get the value of a button and print it to the console.
I currently have a number of buttons (html) all have the same ID but different values.
when a button is clicked I want to print its value to the console.
document.getElementById("calcButtonID").addEventListener("click", btnPress);
function btnPress() {
var x = document.getElementById("calcButtonID").value
console.log(x);
}
It always displays the value of the first button ("1") regardless of the button I click,
What am i doing wrong? I think i need to pass the event listener to the function so it knows what button was clicked and not just the first ID it comes across
Thanks for the help (im getting there :) )

As pointed in the comments to the question, you may use e.target.value, or add data-attributes to your buttons, but since you asked about what you're doing wrong, I'll answer that particular question for you to avoid such problems in future.
Basically, an ID must be unique on page, proof here. So your main error is that several buttons have the same ID. What they can share though, is the name attribute, if for some reason you need them to be processed as a single element.
However, in this latest case, I would recommend using <input type="radio">, i.e., a group of radio buttons with the same name, but again, with different unique IDs.

You cannot have more than one element with id="calcButtonID" (or any other given id value). id must be unique at all times.
Instead of id, use the class attribute. Here's an example:
// get a NodeList of the buttons
const buttons = document.querySelectorAll('.report-value');
// turn the NodeList into an Array so we can use array methods on the list
const buttonsArray = Array.from(buttons);
// now iterate over the button list...
buttonsArray.forEach(function(button) {
// ... so we can give each button a click listener
button.addEventListener('click', function(event) {
// inside the event listener function, `this` points to the button that was clicked
console.log(this.value);
// alternatively, you can get the clicked button from the event object that is implicitly passed as event.target
console.log(event.target.value);
});
})
<input type=button value=foo class="report-value" />
<input type=button value=bar class="report-value" />
<input type=button value=baz class="report-value" />

An id is a unique identifier for only one html element. If you wnat to find several element, use class. Here is an example.
var buttons = document.getElementsByClassName("calcButton")
for(var i = 0; i<buttons.length; i++){
buttons[i].addEventListener("click", btnPress)
}
function btnPress(ev) {
console.log(ev.target.value);
}
<!-- begin snippet: js hide: false console: true babel: false -->
<button class="calcButton" value="1">1</button>
<button class="calcButton" value="2">2</button>
<button class="calcButton" value="3">3</button>
<button class="calcButton" value="4">4</button>
But as specified, it's better to use the onclick attribute rather than find the element by its classname

Related

Getting the value from HTML into javascript

I'm not entirely certain if what I'm trying to do may be possible.
However,
<button class = "numbers" value=1>1</button>
all the way to
<button class = "numbers" value=9>9</button>
For example, I have 1 all the way to 9, when one of these buttons were to be clicked, I want the values to be console logged. So, if I clicked the number 1 for example, it would just console log 1 as an int using the value of that specific button, without having to specify each button individually.
Thank you for helping in advance!
Use event delegation. Add one event listener to the container of the buttons, and on click, if the target (the innermost clicked element) was a button that matches .numbers, log the value.
document.querySelector('.container').addEventListener('click', ({ target }) => {
if (!target.matches('.numbers')) return;
console.log(target.value);
});
<div class="container">
<button class = "numbers" value=1>1</button>
<button class = "numbers" value=9>9</button>
</div>

Uncaught TypeError: document.querySelector(...).click is not a function on automated process

Expected Behaviour: I am adding the value from a select element to a 3rd party API input element using the select element's onchange event. Once the text value has been added to the input element, the search button must be clicked to fully automate the process.
Returned Behaviour: Although the text value can be seen in the input, once it gets focus, it clears the text. When the text is visible and the search button is clicked, nothing happens. When I add the text value manually to the input and then click search it works fine. Not too sure what to do to make sure the text remains in the input.
Code for my select and the input as follow -
function vehicle_vin() {
var use_vehicle_vin = document.getElementById('get_vehicle_make');
use_vehicle_vin = use_vehicle_vin.options[use_vehicle_vin.selectedIndex].value;
var add_vehicle_vin = document.getElementById('id-vin-frame-search');
add_vehicle_vin.value = use_vehicle_vin;
alert(add_vehicle_vin.value);
//This works fine, but please see my notes above, when I put focus on the input, my value dissapears...
//I have tried, as per various search results the following QuerySelector, no luck in the search button being clicked.
//document.querySelector('.CLOYw6ixbVCoWy9pu904a ._2DcnCzqTJKrTWusHYHyHEf').click();
//I then changed to the svg element, the same error was returned...
var x_vin = document.querySelector('._15YY4Hl-2b6wr1smId9ZlA').click();
//I also tried to do a setTimeout, also did not work, then added the below, this returns nothing -.
if (x_vin && x_vin.length) {
alert("All true, click...");
setTimeout(() => { x_vin[0].click(); }, 750);
alert("clicked");
} else {
alert("not clicked");
}
}
<select id="get_vehicle_make" name="get_vehicle_make" title="Select a vehicle from your current car park. This V.I.N. will be added to the Search Input and will automatically load your search." onchange="vehicle_vin();">
<option value="" selected >Select Saved Vehicle</option>
<option value = "123456asdfgh09876" >Kia, Sportage, 2. CRDi</option>
</select>
<!--3rd party Api input and search button-->
<input type="text" id="id-vin-frame-search" name="vin-frame-search" placeholder="VIN or FRAME" class="_2UbmnxPVuhV1aqBHdE1oDO">
<button type="button" class="CLOYw6ixbVCoWy9pu904a _2DcnCzqTJKrTWusHYHyHEf">
<span class="_24-MeE_aY0KDledQMmmJAn">
<svg width="16" class="_15YY4Hl-2b6wr1smId9ZlA">
<use xlink:href="#search"></use>
</svg>
</span>
</button>
As above, I have tried many things with no success and will really appreciate any help available, javascript is not my strong point...
querySelector returns single element, to get multiple elements use
querySelectorAll
As you are trying to access single and first element, then you can use querySelector.
So the x_vin will contain element directly (not nodelist)
So you are trying to click element programmatically (From Javascript), Then you have .click() function
Just wrapped the click function in timeout (e.g., below)
setTimeout(() => {
console.log(document.querySelector('._15YY4Hl-2b6wr1smId9ZlA'));
document.querySelector('._15YY4Hl-2b6wr1smId9ZlA').click();
}, 1000) //1 second delay
Update
Hey I just found that svg does not have click function (I thought
every element does). Solution is to click parent element
programmatically, In your case either click span or button

How to get boolean value, If element id clicked - Angular

I am trying to get boolean value, if element id has been clicked in angular. I have tried to get boolean value through document.getElementById to find element clicked or not, but that is not working as expected.
This is how my sample html code:
<button id="my-btn-id" class="bx--number__control-btn up-icon">
If my button id will be clicked, I need to get true or need to return false. Here through click event I can able to get it, but I need to be identified through id. If any one have any idea please help me.
Just a add a variable in your class, say: public myBtnIdClicked: boolean = false
<button id="my-btn-id" (click)="myBtnIdClicked = true" class="bx--number__control-btn up-icon">
Add a click listener on your button, set the variable myBtnIdClicked to true once a click happens over the button.
This is probably not exactly what you want but why not keep it simple. I like simple.
controller
public clickedBtn1: boolean = false; // keep a number which is the same as button id.
Then you can always check by simply.
if (this.clickedBtn1)
{
//do something
// will only be reached if button has been clicked
}
template
<button id="1" class="bx--number__control-btn up-icon" (click)="clickedBtn1 = true">

How to grab ID of element which ID has been dynamically given?

I’m trying to make a simple show when checkbox is checked kind of section but am unable to get a hold of the element because the IDs of the element are assigned dynamically by PHP.
The element will be inside a foreach loop so there will be multiple instances of it with dynamically given IDs.
example:
//Laravel blade template
<element id="attrb{{ $elem->id }}> "></element>
//Javascript
if ($("#attrb*ID").is(":checked")) {
$("#attrbs-container").show();
} else {
$("#attrbs-container").hide();
}
With Jquery
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="attrb1" value="1" />
Run, and check the box. You can replace console.log with your .show or whatever.
The selector input[id^="attrb"] means an input with an id that ^= starts with attrb. You could also use input[type="checkbox"] if these are the only checkboxes you have, but it's less specific.
Change vs Click
change fires when the data (state) of the element changes. click will trigger anytime you click. In this case it probably doesn't matter too much which you use. A better example of change vs click is using radio buttons, and clicking an already checked radio. Checkboxes un-click when checked, radio buttons not so much. I'm just in a habit of using change over click for state changes.
$('input[id^="attrb"]').click(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Run and click the radio 2x. It fires 2 times.
$('input[id^="attrb"]').change(function(e){
if($(this).is(':checked')) console.log($(this).prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="attrb1" value="1" />
Do the same thing here, but with change. That's the difference.
DYNAMIC vs Dynamic
What I mean here is DYNAMIC is something that changes at run time on the client, Dynamic is static HTML where the ID changes on the server side only. For DYNAMIC you want to use on like this
$(someparent).on('change', 'input[id^="attrb"]', function(e){ ... });
Where someparent is a static element that doesn't change at runtime. This will use event delegation and "bubbling" to find the content that was changed on the client side.
I don't think you meant DYNAMIC but I included it just in case.
Cheers!
you could create a function with a callback if you're assigning the id with javascript (after an ajax request)
function addID(add, callback)
Then use the funciton:
addId(function(){
//dynamically add ID
}, function(){
// callback function
if ($(“#attrb*ID”).is(":checked")) {
$(“#attrbs-container").show();
} else {
$(“#attrbs-container").hide();
}
})

OnClick event is only getting the first dynamically created row/id

I have a table where if X has a value, display X, otherwise, add a link which when clicked will display a textbox where user can input the value. I dynamically assign IDs/classes to the link and textboxes but when I run the application, each click on any link only seems to trigger the first row. I put in alerts to show what row is being clicked and I always get the first row. Looking at the browser DOM explorer, I can see that each row has its own unique ID. How do I get each OnClick event to grab the correct corresponding ID?
C#/Razor code:
<td>
Unmapped
<input type ="submit" class="editAction hidden" value="#string.Format("tr{0}",i)" name="action:ChangeToEditSubAction" />
<input type="hidden" name="#Html.Raw("EntityMapping.EMREntityID")" value="#Html.Raw(Model.DisplayResults[i].EMREntityID)" />
<span class="#string.Format("tr{0}accountTxtBox",i) hidden">#Html.TextBoxFor(m => m.EntityMapping.AssignedHOAccountID)</span> </td>
Javascript Function
function UnmappedClick() {
//$(".accountTxtBox").removeClass("hidden");
//$(".unmapped").addClass("hidden");
//$("#btnSave").removeAttr('disabled');
//$(".editAction").click();
//$(".editAction").val(null);
alert($(".unmapped").attr('id'));
var txtBox = $(".editAction").val();
var actTextBox = "." + txtBox + "accountTxtBox";
$(actTextBox).removeClass("hidden");
alert(txtBox);
}
DOM Explorer Image
You can pass a parameter from your onclick event using the "this" keyword.
onclick="UnmappedClick(this.id)"
function UnmappedClick(id){
//now you have the specific ID
}
or if necessary pass the whole control over
onclick="UnmappedClick(this)"
you can try this
$(this).attr('id') // use this
instead of
$(".unmapped").attr('id')
This will give you the current elements id when you click
As you can see here, using $('.class') will return a list all the elements with that class. When you use $(".unmapped").attr('id') you'll always get the value of the first element in the list, that's why you always get the first row.
The same will happen with var txtBox = $(".editAction").val();. With $(actTextBox).removeClass("hidden"); you'll remove the class hidden from all the elements matched.
To get the id of an element you can use onclick="unmapped(this) or onclick="unmapped(this.id)" using the following code depending on the onclick attribute
function unmapped(element) {
var id = $(element).attr('id')
alert(id)
}
function unmapped(id) {
alert(id)
}
You can check this fiddle to see them in action.

Categories

Resources