Getting the value from HTML into javascript - 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>

Related

Creating a button based on user input

I have a website where you can enter information into an input box and then below it a button that says "add". When pushing this button I want it to create a new button with the text inputted above.
I'm not quite sure even where to start with the javascript but here's my html:
<input type="text" name="device" id="device">
<button class="add">Add</button>\
I'm just trying to make an add button make another button with the text in input box above.
Concepts
You need to change the DOM and append a new Element to your HTML.
To do this you need to capture the value when you click on the button and, after that, render the new element. I've created a Codepen to help you with that:
To explain:
HTML
<input id="my-input" placeholder="Place your text here" />
<button id="my-button">Submit</button>
<p id="my-content"></p>
Every element has an id that you'll use on your...
Javascript:
const myInput = document.getElementById('my-input')
const myButton = document.getElementById('my-button')
const content = document.getElementById('my-content')
myButton.addEventListener('click', function(event) {
const myInputValue = myInput.value;
content.innerHTML = myInputValue
})
By first we get all elements on DOM using document.getElementById function. After that we add an event to our button, the event of click. After that, we catch the value inputted by the user and change the HTML inner our p tag and put the text that have been inputted in our input.
So, after that, the text will be rendered on the screen and you can see what you have inputted.
Soluctions
By now, using this concept, we can now use this and change also, in our element, the style of showing or not. You can follow to this other Codepen that I'll use in our example:
HTML:
<input id="my-input" placeholder="Place your text here" />
<button id="my-button">Submit</button>
<button id="my-other-button"></button>
Javascript
const myInput = document.getElementById('my-input')
const myButton = document.getElementById('my-button')
const myOtherButton = document.getElementById('my-other-button')
myOtherButton.style.display = 'none'
myButton.addEventListener('click', function(event) {
const myInputValue = myInput.value;
myOtherButton.style.display = 'block'
myOtherButton.innerHTML = myInputValue
})
So, now we are capturing our elements as before, but that time we capture also an empty button and, with style.display property we change, when the first render occurs, to not showing our button. After we click in the first button we change it again to show it and, as before, change the innerHTML with the text that user have inputted.

How to add an HTML tag to the value of an array?

This is my HTML code. Here I render all the elements in the array (which is in the state) and add a class "dragImg" to each element (I need this class for another use). Under the rendered array, I have an input and button; the idea is that the user can type something and when he clicks on the button, the input text gets added to the array in the state.
<div>
{this.state.texts.map(text => (
<div class="dragImg">{text}</div>
))}
</div>
<input ref={(textInput) => {this.textInput = textInput}}
type="text"></input>
<button onClick={this.clickButton.bind(this)}>Add
Text</button>
Here is the clickButton() function where the input value gets added to the state:
clickButton(){
this.setState({
texts: this.state.texts.concat(this.textInput.value)
})
}
All the elements of the list get rendered correctly, the problem is that only the predefined elements in the list get the "dragImg" HTML class tag and the ones that get added later on by the user don't have it anymore. This is a problem for me, because I want all these texts to be draggable, and only the elements which have the "dragImg" class tag are draggable and the new inputs aren't.
What can I do?
use ClassName instead of class in react js
and best practice is to handle the typing value using state.
<input
value={ this.state.fieldInput }
onchange= { (e) => { this.setState({ fieldInput: event.target.value }); } }
>

Capturing the value of a button

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

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">

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