When button clicked JS is showing [object HTMLButtonElement] instead of original value.
I want that whenever a button is clicked the value of button is showed.
like when button having value 3 is pressed it will show 3 and not [object HTMLButtonElement]
this is my html file
<div class="col-3">
<button onclick="val(this)" id="n1" value="1" type="button" class="btn btn-outline-primary "
style="width:100%" value="1">1</button>
</div>
<div class="col-3">
<button onclick="val(this)" id="n1" value="2" type="button" class="btn btn-outline-primary "
style="width:100%" value="2">2</button>
</div>
This is my script.js
function val(num) {
let n = num;
document.getElementById("ta").innerHTML = n;
}
when using this inside the onclick html attribute, it will be valued with the html element firing the event so the object being passed to val() will be the whole element.
If you need to know the value of the button being clicked, you should retrieve its value property
function val(num) {
let n = num.value;
document.getElementById("output").innerHTML = n;
}
button{
cursor: pointer;
}
<button
type="button" class="btn btn-outline-primary "
id="n1" value="1" onclick="val(this)">1</button>
<button
type="button" class="btn btn-outline-primary "
id="n2" value="2" onclick="val(this)">2</button>
<div id="output"></div>
Using onClick directly on Elements is not really ideal, try using addEventListener.
Another advantage of addEventListener you can create a delegated event handler, so if you have lots of buttons doing the same thing you can attach one handler to a parent element and all the buttons can be handled.
Buttons don't store values like INPUT, but if you want to associate data with buttons try using the data- attribute. eg.. data-val="1", you can then access this using the dataset property.
Below is a simple example of using addEventListener as a delegated event handler, plus using data- attributes on buttons.
Update: Buttons do have the value attribute, so you could still do
e.target.value too, but I'll leave the data- attribute as it's
pretty handy anyway.. :)
const d = document.querySelector('div');
document.body.addEventListener('click', e => {
const val = e.target.dataset.val;
if (val) d.innerText = val;
});
div {
border: 1px solid black;
margin-top: 10px;
padding: 20px;
font-size: 30pt;
font-family: arial;
}
<button data-val="1">1</button>
<button data-val="2">2</button>
<button data-val="3">3</button>
<button data-val="4">4</button>
<div>
Click button above.
</div>
Related
I want to make a "numeric keyboard" that shows buttons with symbols from 0-9. When I press each button it is suppose to add up.
So lets say i press 3 , 4 then 1 it should say 341 on the text box or number box idk (srry im new).
I have only taken some examples from my teacher so i dont know if this is the right method.
I tried this on button 0:
<button onclick="showZero()">0</button>
<button onclick="">1</button>
<button onclick="">2</button>
<button onclick="">3</button>
<button onclick="">4</button>
<button onclick="">5</button>
<button onclick="">6</button>
<button onclick="">7</button>
<button onclick="">8</button>
<button onclick="">9</button>
<br>
<input type="text" id="txtZero">
window.onload = start;
function start() {}
function showZero()
{
var zero = document.getElementById("Number");
zero.Value="0";
document.querySelector("txtZero").appendChild(zero);
}
Am i using wrong method? I saw my teacher example, but he was using this to generate more buttons and not numbers like im trying to do.
EDIT: I edited my answer to provide a better answer that doesn't use inline event handling. I also wrapped the code into DOMContentLoaded event listener to make sure JS runs after the DOM is fully loaded.
function ready() {
// The textfield element
textField = document.getElementById("field")
// The reset button
resetButton = document.getElementById("resetbtn")
// Get all the buttons to an Array
buttons = document.getElementsByClassName("btn")
// Add click event listener to all button elements and insert their inner text as value to the text field
Array.prototype.forEach.call (buttons, (button) => {
button.addEventListener("click", () => {
textField.value += button.innerText
})
})
// Add click event listener to reset button
resetButton.addEventListener("click", () => {
textField.value = null
})
}
document.addEventListener("DOMContentLoaded", ready);
input, button {
padding: 3px 6px;
margin: 3px;
}
<button class="btn">0</button>
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
<button class="btn">6</button>
<button class="btn">7</button>
<button class="btn">8</button>
<button class="btn">9</button>
<br>
<input type="text" id="field"><button id="resetbtn">Reset</button>
Follow the code to it:
Add function setNumber to set number in field text.
Change function showZero to resetNumber if contains the value in field text insert zero.
function resetNumber()
{
document.getElementById("field").value = '0';
}
function setNumber(number) {
document.getElementById("field").value = document.getElementById("field").value === '0' ? '' : document.getElementById("field").value += number;
}
<html>
<body>
<button onclick="resetNumber()">Reset</button>
<button onclick="setNumber(0)">0</button>
<button onclick="setNumber(1)">1</button>
<button onclick="setNumber(2)">2</button>
<button onclick="setNumber(3)">3</button>
<button onclick="setNumber(4)">4</button>
<button onclick="setNumber(5)">5</button>
<button onclick="setNumber(6)">6</button>
<button onclick="setNumber(7)">7</button>
<button onclick="setNumber(8)">8</button>
<button onclick="setNumber(9)">9</button>
<br />
<input type="text" id="field" />
</body>
</html>
I'd like to insert an input in an adjacent div where the JS function has been fired.
JavaScript: to add an element (input in this case)
jQuery: to detect where the javascript function has been fired.
The issues I'm facing :
The input is created after the second click.
All the inputs move from one div to another on each click ...
I don't understand why this happens! Do you guys have an idea why everything messes up? Thanks a lot.
var ct = 0; // numeric identifier for training section
var lec = 0; // numeric identifier for lectures
function addLecture() {
lec++;
var div = document.createElement('div');
div.setAttribute('id', 'lecture'.concat(lec))
var input = document.createElement('input');
lecture.setAttribute('type', 'text')
div.appendChild(input)
var id;
jQuery('.info_container').click(function(id) {
var id = jQuery(this).attr("id");
document.getElementById(id).querySelector('[id ^= "lectures_container"]').insertAdjacentElement('beforeend', div);
});
}
[id^="row"] {
padding: 10px;
margin: 10px;
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="row-4" class="info_container">
<div id="lectures_container4">
</div>
<a class="btn btn-add" href="javascript:addLecture()"><span class="fa fa-plus"></span> Add an input</a>
</div>
<div id="row-5" class="info_container">
<div id="lectures_container5">
</div>
<a class="btn btn-add" href="javascript:addLecture()"><span class="fa fa-plus"></span> Add an input</a>
</div>
Full code and live example in the JS fiddle right here: https://jsfiddle.net/t7x350d9/
Your code is much more complicated than it needs to be.
Firstly when dealing with repeated HTML structures do not use id attributes. Use the same class on them all to group them. If you need to identify each one, listen for the event and use the target to determine which element was interacted with. In the example below this can be done through the target property of the event which is raised.
Secondly, to achieve your goal simply use an unobtrusive event handler in your JS (not an onclick attribute in the HTML) and append() the new HTML. Try this:
jQuery($ => {
$('.info_container .btn').on('click', e => {
e.preventDefault();
$(e.target).closest('.info_container').find('.lectures_container').append('<div class="lecture"><input type="text" /></div>');
});
});
.info_container {
padding: 10px;
margin: 10px;
background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="info_container">
<div class="lectures_container"></div>
<a href="#" class="btn btn-add">
<span class="fa fa-plus"></span> Add an input
</a>
</div>
<div class="info_container">
<div class="lectures_container"></div>
<a href="#" class="btn btn-add">
<span class="fa fa-plus"></span> Add an input
</a>
</div>
I want to turn buttons like the following to be clickable by the middle mouse button so it will be possible to open them in new tabs.
These buttons are on Aliexpress' orders page:
<button button_action="confirmOrderReceived" orderid="87428853391079" type="button" data-order-status="WAIT_BUYER_ACCEPT_GOODS" data-order-biztype="AE_COMMON" class="ui-button ui-button-normal button-confirmOrderReceived">
Confirm Goods Received
</button>
I tried to turn them into a but then they don't work.
These don't work either: Fiddle (note that the buttons on AE don't have a link).
Is there another way to inject a script that will turn all the buttons on a page to be tab clickable?
Try following code might help
Reference
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
var whichButton = function (e) {
// Handle different event models
var e = e || window.event;
var btnCode = e.button;
if (btnCode === 1) {
console.log('Middle button');
}
}
<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">Click With
Middle Button</button>
You can wrap your button in an anchor tag and add the target="_blank" to force the window to open in new tab.
<a href="link" target="_blank"><button button_action="confirmOrderReceived" orderid="87428853391079" type="button" data-order-status="WAIT_BUYER_ACCEPT_GOODS" data-order-biztype="AE_COMMON" class="ui-button ui-button-normal button-confirmOrderReceived">
Confirm Goods Received
</button></a>
You can simply write mousedown event instead of onclick like this
check updated fiddle : https://jsfiddle.net/1gd8m9y4/3/
<form action="http://google.com">
<input type="submit" value="Go to Google" href="google.com" onmousedown="window.open('http://www.gooogle.com/')" />
</form>
<input type="button" onmousedown="window.open('http://www.gooogle.com/')" value="Go to Google" />
Simple solution for detection of mouse middle click event
$('.test').mousedown(function(event) {
if(event.which == "2")
alert("middle click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="http://google.com">
<input type="submit" value="Go to Google" href="google.com" />
</form>
<input type="button" class="test" value="Go to Google" />
If you are using anchor tag use attribute target="_blank" to open a new tab and use href to add the link
I suppose that code snippet should solve your problem
.btn {
background-color: grey;
padding: 5px;
margin: 5px;
height: 15px;
width: 90px;
}
.btn-link {
text-decoration: none;
font-weight: normal;
display: inline-block;
color: #000000;
}
<a class="btn btn-link" rel="details" href="http://google.com" target="_blank">Go to Google</a>
How to detect which dynamic button is clicked?
Note: The #dCalc Element is added dynamically...
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<input id="firstNumber" type="text" maxlength="3" />
<input id="secondNumber" type="text" maxlength="3" />
<input id="btn1" type="button" value="Add" />
<input id="btn2" type="button" value="Subtract" />
<input id="btn3" type="button" value="Multiply" />
<input id="btn4" type="button" value="Divide" />
</div>
</div>
$("input").click(function(e){
var idClicked = e.target.id;
});
$(function() {
$('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
Since the block is added dynamically you could try:
jQuery( document).delegate( "#dCalc input[type='button']", "click",
function(e){
var inputId = this.id;
console.log( inputId );
}
);
demo http://jsfiddle.net/yDNWc/
jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...
$('#dCalc input[type="button"]').click(function(e) {
// 'this' Returns the button clicked:
// <input id="btn1" type="button" value="Add">
// You can bling this to get the jQuery object of the button clicked
// e.g.: $(this).attr('id'); to get the ID: #btn1
console.log(this);
// Returns the click event object of the button clicked.
console.log(e);
});
Detect event on dynamically created elements
Two examples, jQuery and vanilla JavaScript ahead:
jQuery
Use the .on() method with delegated events, which follows this syntax:
$("staticParentSelector").on("eventName", "dynamicChildSelector", handlerFn);
Example:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
$("#dBlock").on("click", '[type="button"]', (evt) => {
const staticParent = evt.delegateTarget; // This is #dBlock
const dynamicChild = evt.currentTarget; // This is the dynamic child
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
JavaScript
The same in vanilla JavaScript can be achieved like the following, with the difference in that JS has no notion of delegateTarget (which is a jQuery property on their proprietary Event object) therefore the slight modification:
// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future
document.querySelector("#dBlock").addEventListener("click", (evt) => {
const staticParent = evt.currentTarget; // This is #dBlock
const dynamicChild = evt.target.closest('[type="button"]'); // This is the dynamic child
if (!dynamicChild) return; // Do nothing (no designated dynamic child is clicked)
console.log(`Static Parent ID is: ${staticParent.id}`)
console.log(`Dynamic child ID is: ${dynamicChild.id}`)
});
<!-- STATIC -->
<div id="dBlock">
<!-- ADDED DYNAMICALLY -->
<div id="dCalc">
<button type="button" id="btn1">Add</button>
<button type="button" id="btn2">Subtract</button>
<button type="button" id="btn3">Multiply</button>
<button type="button" id="btn4">Divide</button>
</div>
</div>
as you can see neither of the above implementations stick solely on the Event.target Element per-se, for the reason that if we had i.e. an icon inside the buttons (like: <button id="add" type="button">Add <i class="icon-plus"></i></button>) and if a click landed on the icon directly, the Event.target would end up being the icon, not the Button Element - and we might miss to retrieve the needed data, like the specific button ID etc, resulting in a broken app logic.
I am using button tag <button value="1">1</button>
Basically I want when this button is pressed, the value of the button is set into editable div.
<div contentEditable='true'; >Value from button</div>
Is that possible with client side script?
Try the below code: (EDIT Modified as user has subsequently indicated that he will use this to create a calculator)
We are doing the following:
Assign an onclick function to the button. This will be called whenever the button is clicked.
An ID is added to both the button tag and the div tag to access them using the getElementById method in JavaScript.
this.value will pass the value of the button that is currently clicked to the function.
Inside the JavaScript, we get the value of the button and set it to the innerHTML of the required div. Note: Since += is used, it would take the current contents of the div and append the button's value to it (like, if 1 is pressed followed by 2, the div would have 12 as its content).
HTML
<button value="1" id='btn1' onclick='setBtnValue(this.value);'>1</button>
<button value="2" id='btn2' onclick='setBtnValue(this.value);'>2</button>
<div contentEditable='true' id='div1'></div>
Javascript
function setBtnValue(btnVal){
document.getElementById('div1').innerHTML += btnVal;
}
Demo
you can use getElementById method.
<button value="1" onclick="function1(this)">1</button>
<div contentEditable='true' id='edit'>value from button</div>
<script type='text/javascript'>
function function1(obj){
document.getElementById("edit").innerHTML=obj.value;
}
</script>
Yes this is possible but you have to assign the id.
<button onclick="put()" id="but" value="1">1</button>
<div id="pol" >Value from button</div>
Now with function use
function put()
{
document.getElementById("pol").innerHTML = document.getElementById("but").value;
}
DEMO
HTML:
<button value="1" class="button">1</button>
<button value="2" class="button">2</button>
<div contentEditable="true" id="element"></div>
JS:
var buttons = document.getElementsByClassName('button');
var div = document.getElementById('element');
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(event) {
div.innerHTML = event.target.value;
});
}
Working example.