how to get text value from button? - javascript

I'm trying to get the text value inside a button. example:
if I click on papier I want the alert to say papier how can I call the HTML text of the button. right now I get undefined instead of "papier" when I click on papier.
<h1>Jeu de Roche,Papier,Ciseau</h1>
<div id="conteneur">
<div id="interface">
<table>
<tr>
<td><button class="button" type="text" onclick="clique(this)">Roche</button></td>
<td><button class="button" type="text" onclick="clique(this)">Roche</button></td>
</tr>
<tr>
<td><button class="button" type="text" onclick="clique(this)">Papier</button></td>
<td><button class="button" type="text" onclick="clique(this)">Papier</button></td>
</tr>
<tr>
<td><button class="button" type="text" onclick="clique(this)">Ciseau</button></td>
<td><button class="button" type="text" onclick="clique(this)">Ciseau</button></td>
</tr>
</table>
</div>
</div>
<script>
function clique(x) {
var element = document.querySelector("button").innerHTML;
alert(x.element);
}
</script>

It would better to use attribute selector and fire addEventlistener.
<h1>Jeu de Roche,Papier,Ciseau</h1>
<div id="conteneur">
<div id="interface">
<table>
<tr>
<td><button class="button" type="text" data-name="button">Roche</button></td>
<td><button class="button" type="text" data-name="button">Roche</button></td>
</tr>
<tr>
<td><button class="button" type="text" data-name="button">Papier</button></td>
<td><button class="button" type="text" data-name="button">Papier</button></td>
</tr>
<tr>
<td><button class="button" type="text" data-name="button">Ciseau</button></td>
<td><button data-name="button" class="button" type="text" >Ciseau</button></td>
</tr>
</table>
</div>
</div>
<script>
const buttons = document.querySelectorAll("[data-name='button']")
buttons.forEach(button => button.addEventListener('click', function() {
console.log(this.innerHTML)
}))
</script>

x in your clique function is already the element you clicked, you don't have to find it again, simply use x.innerHTML or better x.innerText:
function clique(x) {
alert(x.innerText);
}
<h1>Jeu de Roche,Papier,Ciseau</h1>
<div id="conteneur">
<div id="interface">
<table>
<tr>
<td><button class="button" type="text" onclick="clique(this)">Roche</button></td>
<td><button class="button" type="text" onclick="clique(this)">Roche</button></td>
</tr>
<tr>
<td><button class="button" type="text" onclick="clique(this)">Papier</button></td>
<td><button class="button" type="text" onclick="clique(this)">Papier</button></td>
</tr>
<tr>
<td><button class="button" type="text" onclick="clique(this)">Ciseau</button></td>
<td><button class="button" type="text" onclick="clique(this)">Ciseau</button></td>
</tr>
</table>
</div>
</div>

you don't need a selector you are passing the button as a reference to your handler.
you can use value inside the button as well, value could be more versatile in my opinion.
function clique(btn) {
alert(btn.value);
alert(btn.innerHTML);
alert(btn.innerText)
}
<h1>Jeu de Roche,Papier,Ciseau</h1>
<div id="conteneur">
<div id="interface">
<table>
<tr>
<td><button class="button" type="text" value="Roche" onclick="clique(this)">Roche</button></td>
<td><button class="button" type="text" value="Roche" onclick="clique(this)">Roche</button></td>
</tr>
<tr>
<td><button class="button" type="text" value="Papier" onclick="clique(this)">Papier</button></td>
<td><button class="button" type="text" value="Papier" onclick="clique(this)">Papier</button></td>
</tr>
<tr>
<td><button class="button" type="text" value="Ciseau" onclick="clique(this)">Ciseau</button></td>
<td><button class="button" type="text" value="Ciseau" onclick="clique(this)">Ciseau</button></td>
</tr>
</table>
</div>
</div>

Because querySelector will only pick up the first matching element.
Now you could use querySelectorAll but in JavaScript there's a process called event delegation. It allows you to add one listener to a parent element that captures the events from its child elements as they "bubble up" the DOM. It makes your code and markup cleaner, and has one single point of failure rather than many.
// Cache the container
const interface = document.querySelector('#interface');
// Add a listener to it
interface.addEventListener('click', handleClick);
// Check the clicked element is a button, and
// log its text content
function handleClick(e) {
if (e.target.matches('button')) {
console.log(e.target.textContent);
}
}
<h1>Jeu de Roche,Papier,Ciseau</h1>
<div id="conteneur">
<div id="interface">
<table>
<tr>
<td><button>Roche</button></td>
<td><button>Roche</button></td>
</tr>
<tr>
<td><button>Papier</button></td>
<td><button>Papier</button></td>
</tr>
<tr>
<td><button>Ciseau</button></td>
<td><button>Ciseau</button></td>
</tr>
</table>
</div>
</div>
Additional documentation
matches
addEventListener

You can change your function like this
function clique(x) {
alert(x.innerHTML);
}

Related

Passing the value from an input ID through a function

Within my PHP I have a while loop that is gong through the entries in the DB.
I would like to have a input where I can change a columns value.
<td><input type="text" id="cardId-<?php echo $cardId; ?>" /></td>
<td><button type="button" class="btn btn-primary mb-2" onclick="update(<!-- pass cardId-0.val() -->)">Submit</button></td>
My JS
function update(id) {
var inputVal = document.getElementById("cardId-<?php echo $cardId; ?>").value;
console.log(inputVal);
}
How can I make this work. No matter which one I click on, it only passes the first value in the first box.
Delegation is a good idea
Please change
"table tbody"
and "mb-2"
to better selectors matching your actual markup
window.addEventListener("load",function() {
document.querySelector("table tbody").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("mb-2")) { // if tgt has a class mb-2
const inp = tgt.closest("tr").querySelector("input[id^=card]"); // starting with "card"
console.log(inp.id,inp.value);
}
});
});
<table>
<tbody>
<tr>
<td><input type="text" id="cardId-1" /></td>
<td><button type="button" class="btn btn-primary mb-2">Submit</button></td>
</tr>
<tr>
<td><input type="text" id="cardId-2" /></td>
<td><button type="button" class="btn btn-primary mb-2">Submit</button></td>
</tr>
<tr>
<td><input type="text" id="cardId-3" /></td>
<td><button type="button" class="btn btn-primary mb-2">Submit</button></td>
</tr>
<tr>
<td><input type="text" id="cardId-4" /></td>
<td><button type="button" class="btn btn-primary mb-2">Submit</button></td>
</tr>
</tbody>
</table>

How to set input text value from table data on click of that row in javascript

I have a jsp page where i am displaying value from data base .
Now i need to edit the table value in click of that particular row and that selected row value should get set into respective input text .
My java script function is getting called but clicked value is not getting displayed into respective input type .
The java script function name is onRowClick
I am adding code for that .
Please suggest .
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
function onRowClick(){
var table = document.getElementById("hoteltable"),rIndex;
for(var i = 0; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
document.getElementByName("hId").value = this.cells[0].innerHTML;
document.getElementByName("hName").value = this.cells[1].innerHTML;
document.getElementByName("hArea").value = this.cells[2].innerHTML;
document.getElementByName("hNumOfRooms").value = this.cells[3].innerHTML;
document.getElementByName("hImgUrl").value = this.cells[4].innerHTML;
hideButton();
showDelete();
showEdit();
};
}
}
</script>
</head>
<body>
<h2>Welcome to Admin Page</h2>
<div id="sub-left">
<form:form action="hotelaction" method="post" modelAttribute="hotel">
<table>
<tr>
<td>hotelId</td>
<td><form:input name="hId" path="hotelId"></form:input></td>
<td><form:errors path="hotelId" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelName:</td>
<td><form:input name="hName" path="hotelName"></form:input></td>
<td><form:errors path="hotelName" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelArea:</td>
<td><form:select name="hArea" path="hotelArea">
<form:option value="Marthalli">Marathalli</form:option>
<form:option value="SilkBoard">SilkBoard</form:option>
</form:select></td>
<td><form:errors path="hotelArea" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelNumberOfRooms:</td>
<td><form:input name="hNumOfRooms" path="hotelNumOfRooms"></form:input></td>
<td><form:errors path="hotelNumOfRooms" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>hotelImgUrl:</td>
<td><form:input name="hImgUrl" path="hotelImgUrl"></form:input></td>
<td><form:errors path="hotelImgUrl" cssClass="error"></form:errors></td>
</tr>
</table>
<div id="sub-right">
<input type="submit" value="Add" name="action" id="btn1" class="glass2"></input> <br> <br>
<input type="submit"value="Edit" name="action" id="btn2" class="glass2" /><br> <br>
<input type="submit" value="Delete" name="action" id="btn3" class="glass2"></input><br> <br>
<input type="reset"value="Reset" name="reset" onClick=showButton(); class="glass2" />
</div>
</form:form>
</div>
<div class="myTable">
<table id="hoteltable" border="1" width=100%>
<tr>
<td><h4>hotelId</h4></td>
<td><h4>hotelName</h4></td>
<td><h4>hotelArea</h4></td>
<td><h4>hotelNumOfRooms</h4></td>
<td><h4>hotelImageUrl</h4></td>
</tr>
<c:forEach var="hotels" items="${hotelList}">
<tr onclick="onRowClick()">
<td >${hotels.hotelId}</td>
<td>${hotels.hotelName}</td>
<td>${hotels.hotelArea}</td>
<td>${hotels.hotelNumOfRooms}</td>
<td>${hotels.hotelImgUrl}</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
If you look in the web console, you'll find an error message. There is no document.getElementByName function in the DOM. There's getElementsByName (plural), but not a singular, and that one wouldn't really help you since it would give you a collection of all of the elements with that name, anywhere on the page. (Although if the only ones with those names are the ones you want, you could use it and then use [0] to get the only entry in the resulting collection.)
There's a different problem, though: Your click="onRowClick()" doesn't pass on any information about which row was clicked, and the function itself just hooks up event handlers on the rows rather than actually doing what you want done on click.
Instead, hook click on the table, and check to see if the click passed throug a row; if it did, fill in the information in the first table. See comments:
// Hook click on the table, rather than individual rows
document.getElementById("hoteltable").addEventListener("click", function(e) {
// Make sure the click passed through a row in this table
var row = e.target.closest("tr");
if (!row || !this.contains(row)) {
return;
}
// Get the form we're filling in
var form = document.querySelector("form[action=hotelaction]");
// Fill in the various inputs
// Note: I'd recommend giving each cell a data-name attribute or something
// and using those rather than using `row.cells[0]` and such. That way
// when (not if ;-) ) you change the source table, the cell references
// aren't messed up
form.querySelector("[name=hId]").value = row.cells[0].innerHTML;
form.querySelector("[name=hName]").value = row.cells[1].innerHTML;
form.querySelector("[name=hArea]").value = row.cells[2].innerHTML;
form.querySelector("[name=hNumOfRooms]").value = row.cells[3].innerHTML;
form.querySelector("[name=hImgUrl]").value = row.cells[4].innerHTML;
/*
hideButton();
showDelete();
showEdit();
*/
});
<h2>Welcome to Admin Page</h2>
<div id="sub-left">
<form action="hotelaction" method="post" modelAttribute="hotel">
<table>
<tr>
<td>hotelId</td>
<td>
<input name="hId" path="hotelId">
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelName:</td>
<td>
<input name="hName" path="hotelName">
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelArea:</td>
<td>
<select name="hArea" path="hotelArea">
<option value="Marthalli">Marathalli</option>
<option value="SilkBoard">SilkBoard</option>
</select>
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelNumberOfRooms:</td>
<td>
<input name="hNumOfRooms" path="hotelNumOfRooms">
</td>
<td>
<span class="error"></span>
</td>
</tr>
<tr>
<td>hotelImgUrl:</td>
<td>
<input name="hImgUrl" path="hotelImgUrl">
</td>
<td>
<span class="error"></span>
</td>
</tr>
</table>
<div id="sub-right">
<input type="submit" value="Add" name="action" id="btn1" class="glass2"><br> <br>
<input type="submit" value="Edit" name="action" id="btn2" class="glass2" /><br> <br>
<input type="submit" value="Delete" name="action" id="btn3" class="glass2"><br> <br>
<input type="reset" value="Reset" name="reset" onClick=showButton(); class="glass2" />
</div>
</form>
</div>
<div class="myTable">
<table id="hoteltable" border="1" width=100%>
<tr>
<td>
<h4>hotelId</h4>
</td>
<td>
<h4>hotelName</h4>
</td>
<td>
<h4>hotelArea</h4>
</td>
<td>
<h4>hotelNumOfRooms</h4>
</td>
<td>
<h4>hotelImageUrl</h4>
</td>
</tr>
<tr>
<td>1</td>
<td>Savoy</td>
<td>Marthalli</td>
<td>300</td>
<td>https://via.placeholder.com/150?text=Savoy</td>
</tr>
<tr>
<td>2</td>
<td>Marriott</td>
<td>SilkBoard</td>
<td>450</td>
<td>https://via.placeholder.com/150?text=Marriott</td>
</tr>
<tr>
<td>3</td>
<td>Premier Inn</td>
<td>Marthalli</td>
<td>150</td>
<td>https://via.placeholder.com/150?text=Premier+Inn</td>
</tr>
</table>
</div>
Note that I removed from JSP- or template-isms from the HTML in that, so it used standard form inputs. I assume what gets delivered to the browser uses standard form elements.

Click on button with data- attribute

I'm writing an script extension for a website for Greasemonkey (or Tempermonkey). The problem occurred when I wanted to autofocus (or even autoclick) the button that contains no id, but rather data- attribute.
<div id="wrapper_container">
<form id="form1" action="/?module=Action" method="post">
<table class="thinline" align="center">
<tbody>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="184">Go</button></td>
</tr>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="185">Go</button></td>
</tr>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="186">Go</button></td>
</tr>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="187">Go</button></td>
</tr>
</tbody>
</table>
</div>
</div>
Already tried numerous of times but got me nowhere and wondering why this is not working:
$("#wrapper_container button:eq(4)").focus();
tried to select 4th (or in future nth) button in div, but got unlucky.
I want, for example, button with data-value "186" to be either focused or clicked on pageload. Since I got more entries than displayed, I'd like to do so for every nth button that I'd choose.
Thanks in advance.
If your need just focus in static way button with data-value = 186, use this:
$("#wrapper_container button:eq(2)").focus();
Look this example with more control, just pass the value of you want:
$('#wrapper_container button').each(function() {
var dataValue = $(this).data("value");
if (dataValue == 186) {
$(this).focus();
}
});
button:focus {
background: limegreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div id="wrapper_container">
<form id="form1" action="/?module=Action" method="post">
<table class="thinline" align="center">
<tbody>
<tr>
<td>1</td>
<td>Name</td>
<td>Surname</td>
<td>E-mail</td>
<td>Phone Number</td>
<td>Contact</td>
<td>
<button class="btn btn-small" data-info="contact" data-value="184">
Go
</button>
</td>
</tr>
<tr>
<td>1</td>
<td>Name</td>
<td>Surname</td>
<td>E-mail</td>
<td>Phone Number</td>
<td>Contact</td>
<td>
<button class="btn btn-small" data-info="contact" data-value="185">
Go
</button>
</td>
</tr>
<tr>
<td>1</td>
<td>Name</td>
<td>Surname</td>
<td>E-mail</td>
<td>Phone Number</td>
<td>Contact</td>
<td>
<button class="btn btn-small" data-info="contact" data-value="186">
Go
</button>
</td>
</tr>
<tr>
<td>1</td>
<td>Name</td>
<td>Surname</td>
<td>E-mail</td>
<td>Phone Number</td>
<td>Contact</td>
<td>
<button class="btn btn-small" data-info="contact" data-value="187">
Go
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
To get the 4th one, you need eq(3) as it is a zero-indexed array.
Here are some examples that should get you on your way:
$(function(){
// extra bit of code to 'prove' each button is beaing clicked
$('#wrapper_container button').on('click', function(e) {
console.info('Button clicked, I am button with data value: ' + $(this).attr('data-value'));
});
// You know the IDs of the buttons, you could do:
let IDs = [186, 187];
IDs.forEach(ID => {
console.info('Clicking button with data-value = ' + ID);
$('[data-value=' + ID + ']').click();
});
// You just need a single ID:
let ID = 187;
console.info('Clicking single button with data-value = ' + ID);
$('[data-value=' + ID + ']').click();
// Select nth button in your container,
// as you are trying the 4th button, we use 3, because it is a zero-indexed array, starting at 0 of course:
let btn = $('#wrapper_container').find('button:eq(3)');
console.info('Clicking 4th button in #wrapper_container');
btn.click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper_container">
<form id="form1" action="/?module=Action" method="post" onsubmit="return false">
<table class="thinline" align="center">
<tbody>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="184">Go</button></td>
</tr>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="185">Go</button></td>
</tr>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="186">Go</button></td>
</tr>
<tr>
<td>1</td><td>Name</td><td>Surname</td><td>E-mail</td><td>Phone Number</td><td>Contact</td>
<td><button class="btn btn-small" data-info="contact" data-value="187">Go</button></td>
</tr>
</tbody>
</table>
</form>
</div>

remove readonly attribute from multiple fields on clicking button in jquery

I have a table with the details of the student. These fields are readonly field and can be edited on clicking the edit button. But I am having problem to select all the input fields of that row at once on clicking the edit button.
Here is my html code
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Checklist</th>
<th>Id</th>
<th>Student Name</th>
<th>Address</th>
<th>Phone</th>
<th>Class</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" id="editCheck" class="btn1" />
<input type="checkbox" id="deleteCheck" />
</td>
<td>1</td>
<td><input type="text" class="form-control item" readonly="readonly" /></td>
<td><input type="text" class="form-control item" readonly="readonly" /></td>
<td><input type="text" class="form-control item" readonly="readonly" /></td>
<td>12</td>
<td><button type="button" class="btn btn-info btn-xs" id="btn1">Edit</button></td>
<td><button type="button" class="btn btn-danger btn-xs" id="dbtn1">Delete</button></td>
</tr>
<tr>
<td>
<input type="checkbox" id="editCheck" class="btn2" />
<input type="checkbox" id="deleteCheck" />
</td>
<td>1</td>
<td><input type="text" class="form-control item" readonly="readonly" /></td>
<td><input type="text" class="form-control item" readonly="readonly" /></td>
<td><input type="text" class="form-control item" readonly="readonly" /></td>
<td>12</td>
<td><button type="button" class="btn btn-info btn-xs" id="btn2">Edit</button></td>
<td><button type="button" class="btn btn-danger btn-xs" id="dbtn2">Delete</button></td>
</tr>
</tbody>
</table>
And here is the jquery. I have made the checkbox selected on pressing the edit button.
$(document).ready(function(){
$('.btn.btn-info.btn-xs').click(function(){
var newClass = $(this).attr('id');
$('.'+newClass).prop('checked','true');
});
});
</script>
You can simply add this into your click handler
$(this).closest('tr').find('input').removeAttr('readonly');
Which finds the tr containing the clicked button, locates all of its input elements, and removes their readonly attribute.
Live example: http://jsfiddle.net/zxsq0m5n/
Incidentally, you could use the same trick to locate your checkbox, negating the need to tie it together with the edit button using id/class
$('.btn.btn-info.btn-xs').click(function(){
var $tr = $(this).closest('tr')
$tr.find('input:checkbox').first().prop('checked','true');
$tr.find('input').removeAttr('readonly');
});
Live example: http://jsfiddle.net/zxsq0m5n/1/
$('.btn.btn-info.btn-xs').on('click', function (e) {
var $btn = $(e.currentTarget),
newClass = '.' + $btn.attr('id');
$btn
.parents('tr')
.find(newClass).prop('checked', true)
.end()
.find('input').removeAttr('readonly');
});
You can update your code to following
Logic - Get the tr row i.e. parent of parent of input -> tr -> td -> button. Then for that row find all the input and remove the attribute. Please note you can add conditions if required
$('.btn.btn-info.btn-xs').click(function(){
var newClass = $(this).attr('id');
$('.'+newClass).prop('checked','true');
$(this).parent().parent().find("input").each(function(){
$(this).removeAttr("readonly");
});
});

jQuery Show/Hide non-children elements?

I tried to make this span button toggle hide / show an element it is not a parent of. Is it possible or does it have to be a parent of the element it is trying to toggle .show()/.hide() ?
HTML:
<div id="log_reg">
<span class="btn" id="Log">Log In</span>
<span class="btn" id="Reg">Register</span>
</div>
<div id="log_box">
<table>
<form name="login" action="logsys.php" method="post">
<tr>
<td>Username:</td>
<td><input type="text" name="user" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pass" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Log In" /></td>
</tr>
</form>
</table>
</div>
jQuery:
$(document).ready(function(){
$("#log_box").hide();
$("log").click(function(){
$("#log_box").show();
});
});
Your selector is incorrect. Its Log and You missed #
Use
$("#Log").click(function () {
$("#log_box").show();
});

Categories

Resources