How to find out which button was clicked in handler function - javascript

In my code, I need to make it so when button 1 is pressed it sets a number to be "1" and if button 2 is pressed, it sets the number to be 2.
<!DOCTYPE html>
<html>
<body>
<table style="width:65%;height:100px">
<tr><td align="center" id="blockOne">
<p><button onclick="addGraph()" id="buttonOne">Create Graph/Chart</button></p>
<tr><td align="center" id="blockTwo">
<p><button onclick="addGraph()"id ="buttonTwo">Create Graph/Chart</button></p>
</table>
</body>
<script>
var button1 = document.getElementById('buttonOne');
var button2 = document.getElementById('buttonTwo');
var container = "0";
// When the user clicks the button, open the modal
function addGraph() {
{
if (button1.onclick === true) {
container = "1";
}
if (button2.onclick === true) {
container = "2";
}
}
console.log(container);
}
</script>
</html>

You can simply pass a parameter in your addGraph function which can be assigned to container as button1.onclick is not a valid way that gives you a boolean result.
var button1 = document.getElementById('buttonOne');
var button2 = document.getElementById('buttonTwo');
var container = "0";
function addGraph(value) {
container = value;
console.log(container);
}
<table border='1' style="width:65%;height:100px">
<tr><td align="center" id="blockOne">
<p><button onclick="addGraph(1)" id="buttonOne">Create Graph/Chart</button></p></tr>
<tr><td align="center" id="blockTwo">
<p><button onclick="addGraph(2)"id ="buttonTwo">Create Graph/Chart</button></p></tr>
</table>

You can check which button was pressed by passing this as your function parameter.
Then, simply check your element's id and edit container with :
container = elem.id == 'buttonOne' ? "1" : "2";
var container = "0";
// When the user clicks the button, open the modal
function addGraph(elem) {
container = elem.id == 'buttonOne' ? "1" : "2";
console.log(container);
}
<table style="width:65%;height:100px">
<tr>
<td align="center" id="blockOne">
<p><button onclick="addGraph(this)" id="buttonOne">Create Graph/Chart</button></p>
<tr>
<td align="center" id="blockTwo">
<p><button onclick="addGraph(this)" id="buttonTwo">Create Graph/Chart</button></p>
</table>

You can define the function to accept the number as input, and make the onclick function called filled with the dedicated number.
<button onclick="addGraph(1)">Some text</button>
In this case you don't even need to define the button id, if you don't need to manipulate the buttons.

Notice that in your Html you should open and close all the html elements.
In your JavaScript logic you can select multiple elements by their ids with document.querySelectorAll('#buttonOne, #buttonTwo')
Than just iterate over all them with Array.prototype.forEach() to dynamically attach the click event listener and handle the container value like this container = (index + 1).toString();
Code:
let container = '0';
document
.querySelectorAll('#buttonOne, #buttonTwo')
.forEach((el, index) => el.addEventListener('click', () => {
container = (index + 1).toString();
console.log(container);
}));
<table style="width:65%;height:100px">
<tr>
<td align="center">
<p>
<button id="buttonOne">Create Graph/Chart</button>
</p>
</td>
</tr>
<tr>
<td align="center">
<p>
<button id="buttonTwo">Create Graph/Chart</button>
</p>
</td>
</tr>
</table>

Related

Dynamically add rows and run the script

I have a table that's creating rows dynamically upon button click. This input box contains an auto suggest script. When , I am trying to perform an input on the the first box(the one that is default created) , the auto complete works fine. But, on performing the dynamic adding of the row, the script for that row doesn't work. How to invoke the auto complete script on the new ?
<html>
<body>
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr>
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
{!! Form::text('nameId', null,['class'=>'form-control auto', 'placeholder' => 'name']) !!}
</td>
</tr>
</body>
</table>
<script type="text/javascript">
$(document).ready(function ()
{
$("#add").click(function()
{
$('#tableAdd tr:last').after('<tr><td>{!! Form::text('project_manager_name', null,['class'=>'form-control pmID', 'placeholder' => 'Project Manager']) !!}</td></tr>')
});
});
$(".auto")
.on("keydown", keyDownEventForProjectAndCompetencyLead)
.autocomplete(
{
//function that autocompletes the input
});
</script>
</body>
</html>
Jquery sometimes has a little trouble identifying elements that have been programatically added to the DOM just by the original class / id. Try using a different selector method to check against the modified page:
$(document)
.on("keydown", ".auto", keyDownEventForProjectAndCompetencyLead)
.autocomplete( // etc )
Your selector isn't applying to DOM elements added after the page is loaded.
Modify as above to listen on all element in document that match, or attach listener on each new element created:
<html>
<body>
<button id="add">add</button>
<table id="cooltable">
<tr>
<td>cool table cell</td>
</tr>
</table>
<script type="text/javascript">
function autoPopulate(event){
// some code
event.currentTarget.value = "auto populated content";
}
let add_button = document.getElementById('add');
add_button.addEventListener('click',(event)=>{
let new_row = document.createElement('tr'); // create row
let new_cell = document.createElement('td'); // create cell
let new_input = document.createElement('input'); // create input
new_input.type = 'text';
new_input.value = "default content";
new_input.addEventListener('keydown', (event)=>{ // attach listener
autoPopulate(event);
});
new_cell.appendChild(new_input) // add input to cell
new_row.appendChild(new_cell) // add cell to row
document.getElementById('cooltable').appendChild(new_row); // add row to table
})
</script>
</body>
</html>
Problem here is you are adding callback on "keyDown" event which is not happening hence your script is not running
To fix this you should add eventlistener on jquery load()
Or you should using .bind('DOMNodeInserted DOMNodeRemoved') to call function when new node are added or deleted.
<div id='myParentDiv'> </div>
<button>Click </button>
$("button").click(function(){
$("#myParentDiv").append("<div class='test'></div>");
});
$("#myParentDiv").bind("DOMNodeInserted",function(){
alert("child is appended");
});
Here is working demo
https://jsfiddle.net/vickykumarui/28edcsmb/
Code for Table Example
<div id="addButtonDiv">
<button id="add" >Add New</button>
</div>
<table id="tableAdd">
<head>
<tr id = "test1">
<th >enter</th>
</tr>
</head>
<body>
<tr>
<td>
Test 1
</td>
</tr>
</body>
</table>
var numberOFRow = 1;
$("#add").click(function(){
numberOFRow++
$('#tableAdd tr:last').after('<tr id = test'+numberOFRow +'><td> Test' + numberOFRow + '</td></tr>')
});
$("#tableAdd").bind("DOMNodeInserted",function(){
alert("Row number"+ numberOFRow+ "created");
});
Working Demo for your table examplehttps://jsfiddle.net/vickykumarui/qpxL8k4c/

querySelector inside of Table

I have this simple chrome extension that allows the user to create a table however I can't bind the remove Button.
options.html
<body>
<!-- would be created as the user clicks on new Row -->
<table id="rows">
<tr id="row0">
<td>
<input id="textBox" type="text">
<button id="remove">Remove</button>
</td>
</tr>
</table>
<!-- used as template -->
<table hidden>
<tbody>
<tr id="rowTemplate">
<td>
<input id="textBox" type="text">
<button id="remove">Remove</button>
</td>
</tr>
</tbody>
</table>
<button id="newRow">new Row</button>
<script src="options.js"></script>
options.js
function Row() {
var rows = document.getElementById('rows');
this.node = document.getElementById('rowTemplate').cloneNode(true);
this.node.id = 'row' + (Row.next_id++);
this.node.row = this;
rows.appendChild(this.node);
this.node.hidden = false;
var row = this;
this.getElement('remove').onclick = function () {
row.node.parentNode.removeChild(row.node);
}
}
Row.next_id = 0;
Row.prototype.getElement = function (name) {
return document.querySelector('#' + this.node.id + ' .' + name);
}
window.onload = function() {
document.getElementById('newRow').onclick = function() {
new Row();
};
}
The problem lies in the querySelector because whenever I click on 'new Row', I get an error Uncaught TypeError: Cannot set property 'onclick' of null pointing to the getElement('remove').onclick which calls getElement() where the querySelector returns null.

Button give score to a variable

I'm learning html programming and I want to create a "website" (just to try my knowledge). It's very simple. There are two buttons. If you press win, add 1 score to win variable, if you press lose, add 1 score to lose variable. And it writes the scores under the buttons. But I can't make it.
</head>
<body>
<button id="win">Win!</button><button id="lose">Lose</button>
</br>
<script>
var win = 0;
var lose = 0;
function win(){
win = win + 1;
};
function lose (){
lose = lose + 1
};
</script>
</body>
</html>
Add an onclick event to your buttons:
<button id="win" onclick="return win();">Win!</button>
<button id="lose" onclick="return lose();">Lose</button>
You are going to need an element under each button, a div or span, with IDs so that you can change the innerHTML when the numbers are updated. Alter your functions to update the appropriate element.
You also probably want to wrap the buttons and elements in a table.
Something like this-
<html>
<table>
<tr>
<td><button id="win" onclick="win()">Win!</button></td>
<td><button id="lose" onclick="lose()">Lose!</button></td>
</tr>
<tr>
<td id="wins"></td>
<td id="losses"></td>
</tr>
</table>
<script>
var wins= 0;
var losses = 0;
function win() {
wins= wins+1;
document.getElementById('wins').innerHTML= wins;
};
function lose() {
losses= losses+1;
document.getElementById('losses').innerHTML= losses;
};
</script>
</html>

row open on onclick event which is initially hidden

I want to open a row on onclick event when the particular link is clicked. For that i having number of row where each row below having a hidden row, when i click a row just below row will display.
CODE:
<script>
function toggle(number) {
alert("toggle function called"+number);
var simNum = number;
if (document.getElementById(simNum).style.display = 'none') {
document.getElementById(${dList.simNumber}).style.display = '';
} else {
document.getElementById(${dList.simNumber}).style.display = 'none';
}
}
</script>
<tr>
<td></td>
<td>${dList.deviceAccount}</td>
<td>${dList.vehicleId}</td>
<td>${dList.simNumber}</td>
<td>${dList.imeiNumber}</td>
<td>${dList.lastTimestamp}</td>
<td>${dList.lastLoginTime}</td>
</tr>
<tr id="${dList.simNumber}" style="display: none;">
<td align="center" colspan="7">
Expiration Time:<input id="read" type="text" value="${dList.expirationTime}"/>
<input type="button" value="Edit"><input type="button" value="Save">
</td>
</tr>
change your javascript code
function toggle(number) {
alert("toggle function called"+number);
var simNum = number;
if (document.getElementById(simNum).style.display = 'none') {
document.getElementById(simNum).style.display = '';
} else {
document.getElementById(simNum).style.display = 'none';
}
}

How can I make a table in a cell a variable?

I have a table in a cell that displays the numbers a user enters with buttons (using onclick and a showthis function. I need to be able to store the value as a variable in order to perform operations on it. How can I do this?
PS: I am using JavaScript and HTML
<script language="JavaScript" type="text/javascript">
function showthis(first){
document.getElementById("displaycell").innerHTML+=first;
}
</script>
<body>
<h1 align="center"> RPN Calculator </h1>
<table summary align="center" border="1" cellpadding="1" cellspacing="3">
<tr>
<th id="displaycell" colspan="5" type="text"> </td>
</tr>
<tr>
<td>
<button type="button" onclick="showthis('1')">1</button>
</td>
<td>
<button type="button" onclick="showthis('2')">2</button>
</td>
<td>
<button type="button" onclick="showthis('3')">3</button>
</td>
<!-- ... -->
Firstly you should not be using += with innerHTML. It means that you will end up with the numbers appending to the cell's internal value rather than overwriting it.
function showthis ( number ) {
var cell = document.getElementById('displaycell');
cell.innerHTML = "";
cell.appendChild( document.createTextNode( number ));
}
Would be a much better way to handle that.
Next, within showthis you are best off storing the value in a variable so that you can access it directly from javascript in the future.
var displayStore = 0;
function showthis ( number ) {
var cell = document.getElementById('displaycell');
cell.innerHTML = "";
cell.appendChild( document.createTextNode( number ));
// you can either do this in a variable local to the <td> DOM Object like so
cell.currentDisplayNumber = number;
//or in a global variable like so
displayStore = number;
}
Finally, to access that variable again you can either read it out of the displaystore <td> or read it from your variable.
function DoStuff0 () {
var number = Number( document.getElementById( 'displaycell' )).innerHTML;
// rest
}
function DoStuff1 () {
var number = document.getElementById('displaycell').currentDisplayNumber;
// rest
}
function DoStuff2 () {
var number = displayStore;
// rest
}
Is this what you wanted? http://jsfiddle.net/CWQY2/
HTML:
<h1 align="center"> RPN Calculator </h1>
<table summary align="center" border="1" cellpadding="1" cellspacing="3">
<tr>
<th id="displaycell" colspan="5"> </th>
</tr>
<tr>
<td> <button type="button" onClick="showthis('1')">1</button> </td>
<td> <button type="button" onClick="showthis('2')">2</button> </td>
<td> <button type="button" onClick="showthis('3')">3</button> </td>
</tr>
</table>
JS:
function showthis(first){
document.getElementById("displaycell").innerHTML += first;
}
​
​

Categories

Resources