How to get several buttons' text at once in Javascript? - javascript

I have the following code, it's part of a Java servlet, html, javascript/jQuery web app.
<Table border=1>
<Tr>
<Td><button id=Current_1 type=button></button></Td>
<Td><button id=Current_2 type=button></button></Td>
<Td><button id=Current_3 type=button></button></Td>
<Td><button id=Current_4 type=button></button></Td>
<Td><button id=Current_5 type=button></button></Td>
<Td><button id=Current_6 type=button></button></Td>
</Tr>
</Table>
What can I do on the Java servlet side to get all the text in each of the buttons, I'm thinking about having another submit button when it's clicked, some jQuery gets all those buttons and loop through them to get each button's text.
The text in those buttons originally have nothing, but during the app user can click and change values, so at the end I need to give user a way to save the content on those buttons and pass them to the servlet, what's the best way to achieve that, any sample code ? But what I need help the most is how to get hold of the buttons and loop through them to get their text ?
Edit : Maybe I didn't express it very clearly.
If Button_1 has text "B1"
Button_2 has text "B2"
...
Button_6 has text "B6"
The result I expect after user click another submit button is : B1B2B3B4B5B6

fairly simple to make array of objects using jQuery
var buttonData = $('button[id^="Current"]').map(function(){
return {id: this.id, text: $(this).text()};
}).get();
Produces:
[
{id:"Current_1", text: "Button #1 Text"},
{id:"Current_2", text: "Button #2 Text"},
....
{id:"Current_6", text: "Button #6 Text"}
]
A class selector would probably be cleaner or target them from selector on row
EDIT: If all you want is combined text with no delimiters you can actually get the whole collection of text without even looping the elements.
$('button[id^="Current"]').text();
for most value getters in jQuery this approach will only return the vlue of first element but with text() it returns all

As you mentioned you can use another button to get the text of each of the button. Just use a common class and loop through them
$(document).ready(function(){
$("#Current_7").click(function(){
$(".myButton").each(function(){
console.log($(this).text())
})
})
})
WORKING EXAMPLE

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('button[id^="Current"]').each(function(){
console.info($(this).attr('id') + '----' + $(this).text())
});
});
</script>
</head>
<body>
<Table border=1>
<Tr>
<Td><button id=Current_1 type=button>button_1</button></Td>
<Td><button id=Current_2 type=button>button_2</button></Td>
<Td><button id=Current_3 type=button>button_3</button></Td>
<Td><button id=Current_4 type=button>button_4</button></Td>
<Td><button id=Current_5 type=button>button_5</button></Td>
<Td><button id=Current_6 type=button>button_6</button></Td>
</Tr>
</Table>
</body>
</html>

Related

Update array data when clicking outside input

Cordial greetings I am developing a project in Laravel where I perform a data update in a table dynamically, this data is an array that is created by selecting an item and the function I perform is that when I click on the green button updates the data entered in the array.
But a requirement that they have asked me is that the green button is not there, that when entering the data in the input and clicking outside the input, it updates automatically. To update my data I do it this way, This is my table
<table class="table table-bordered">
<tr>
<th style="font-size: 11.7px;">Item</th>
<th style="font-size: 11.7px;">Eliminar</th>
</tr>
#foreach ($cart as $servicio)
<tr>
<td style="font-size: 11.7px;">
<input type="text"
class="form-con-lg"
value="{{$servicio->n_item}}"
id="servicio_{{$servicio->id}}">
<a class="btn-update-item btn btn-success"
data-href="{{ route('servicio_update',$servicio->id)}}"
data-id="{{$servicio->id}}">
<i class="fas fa-sync-alt"></i>
</a>
</td>
<td>
<i class="fas fa-trash-alt"></i>
</td>
</tr>
#endforeach
</table>
and this is my script where I pass the data to update my array
<script type="text/javascript">
$(document).ready(function(){
$(".btn-update-item").on('click', function(e){
e.preventDefault();
var id = $(this).data('id');
var href = $(this).data('href');
var n_item = $("#servicio_" + id).val();
swal("Good job!", "You clicked the button!", "success");
window.location.href = href + "/" + n_item;
});
});
</script>
and my controller where I update my array
//UPADTE
public function update(Servicios $servicios,$n_item){
$cart = Session::get('cart');
$cart[$servicios->id]->n_item = $n_item;
Session::put('cart', $cart);
return redirect()->route('coti_show');
}
and my route
Route::get('/servicios/update/{servicios}/{n_item?}', 'Admin\CotizacionController#update')->name('servicio_update');
I would like to know how I can do that when I enter the data in the input and click outside the input it is automatically updated, thank you for your help.
As Bravo said, a blur handler could be used, and would probably be the most straightforward. The other route would be to add a click handler to the window (or some encapsulating parent within which you want to check for clicks) and check that the Event.target.id (or some other property of your liking) does not match that of the input.
That being said, the blur handler is most likely the more straightforward solution, just presenting alternatives.

Swapping 2 html table elements

So I made this sliding puzzle using html, css and JavaScript:
this is a table and my question is how do I swap 2 table elements?
Let's say the one with the face (id = tile-2) and the white empy one (id = empty)
Hmm... try this:
https://jsfiddle.net/h7sp1ey8/
<button onclick='swap();'>
Swap
</button>
<table>
<tr>
<td id='f1'>
Contents of td 1
</td>
</tr>
<tr>
<td id='f2'>
Contents of t2
</td>
</tr>
</table>
<script>
function swap()
{
var f1 =document.getElementById('f1');
var f2=document.getElementById('f2');
var initialinner = f1.innerHTML;
f1.innerHTML=f2.innerHTML;
f2.innerHTML=initialinner;
}
</script>
Post your code if you want an exact solution. Here is how you program should work:
get id of box to swap
get id of box to swap to
swap them using method I gave in jsfiddle

Adding event handlers to each table row that will affect only that table row?

This isn't actually something I'm currently attempting to do; it just occurred to me while working with another table that I have no idea how I'd go about doing it, and the entire time on the train ride home I was puzzling over different solutions, none of which I could imagine working.
Imagine this situation: there is a table of 50 rows. On each row is a button. When clicked, this button should do something to the row it's on -- say, make all its text strikethrough, or make an AJAX call with the first cell's value, or something.
How would you go about binding those event handlers?
My initial thought was something like
buttons = document.getElementsByTagName("input");
rows = document.getElementsByTagName("tr");
for (i=0;i<buttons.length;i++) {
buttons[i].addEventListener('click',function() {
makeAjaxCall(rows[i]);
});
};
That is,
For each button in the document,
Add an event handler to that button,
Which will makeAjaxCall with the data of the row whose number corresponds to the button.
The problem, of course, being that makeAjaxCall will check the value of i when it's invoked, by which time, i is equal to buttons.length, and so the function will only ever work on the final row of the table.
So I suppose you'd need to find some way to actually hard-code the current value of i within the function handler... and that's something I don't even think is possible. Is it? How would you actually do something like this?
You can refer to the button object you are adding the event listener to using 'this'
Given the table in this format
<table>
<tr>
<td> <input type='button'> </td>
<td> 1st <td>
</tr>
<tr>
<td> <input type='button'> </td>
<td> 2nd <td>
</tr>
<tr>
<td> <input type='button'> </td>
<td> 3rd <td>
</tr>
</table>
The following code will allow you to access the data in the next cell, shown using console.log() rather than any ajax calls of course.
buttons = document.getElementsByTagName("input");
for (i=0;i<buttons.length;i++) {
buttons[i].addEventListener('click',function() {
makeAjaxCall(this);
});
};
function makeAjaxCall(btn) {
var sib=btn.parentNode.nextSibling;
while (sib.nodeName !='TD') {
sib=sib.nextSibling;
}
console.log(sib.innerHTML);
}
This can be extended to find any data in the row.
This section
while (sib.nodeName !='TD') {
sib=sib.nextSibling;
}
skips any extraneous characters (white space etc) between cells.
Fiddle Here
Interesting problem. I would go about doing it the way #kennebec suggests in the comment above.
Here is the fiddle: http://jsfiddle.net/u988D/
First, a slight change in markup to add data attributes
HTML
<table>
<tr>
<td data-to-json="id">1</td>
<td data-to-json="text">Lorem ipsum dolor.</td>
<td><button type="button">Click Me</button></td>
</tr>
<tr>
<td data-to-json="id">2</td>
<td data-to-json="text">Lorem ipsum dolor.</td>
<td><button type="button">Click Me</button></td>
</tr>
<tr>
<td data-to-json="id">3</td>
<td data-to-json="text">Lorem ipsum dolor.</td>
<td><button type="button">Click Me</button></td>
</tr>
</table>
Then the javascript. Probably can be optimized a bit more.
JS
var table = document.querySelector("table")
table.addEventListener("click", function(e) {
var element = e.target,
parent
//If the element is a button
if ( element && element.nodeName == "BUTTON" ) {
parent = element.parentNode
//Find the closest parent that is a TR
while ( parent.nodeName !== "TR" ) {
parent = parent.parentNode
}
//Convert Row to JSON
var json = {},
child
for ( var i = 0, _len = parent.children.length; i < _len; i++ ) {
child = parent.children[i]
if ( child.hasAttribute("data-to-json") ) json[child.getAttribute("data-to-json")] = child.innerText
}
// Do your AJAX stuff here
console.log(json)
}
})

Get parameter of template in Play Framework

I have a template with parameter like this :
#(people: List[models.Person])
<html>
<head>
</head>
<body>
<table class="centered" id="table_people">
<thead>
<tr class="table_header">
<th></th>
<th class="people_column">Name</th>
<th class="people_column">Active</th>
</tr>
</thead>
<tbody>
#for(p <- people) {
<tr>
<td><button id="timesheet_view_" >View</button</td>
<td><b>#p.getName()</b></td>
<td>#p.isActive()</td>
</tr>
}
</tbody>
</table>
That code shows a list of people. And now, i wanna when click on button view, it shows information of people. To do that, i have to write something like that:
<script>
$( "#timesheet_view_<%= people[i].id %>" )
.button()
.click(function() {
people = '<%= people[i].name %>';
showTimeSheet('current', '<%= people[i].name %>');
})
</script>
But i can't find how to get value people parameter of template in Javascript. I try to use # character, but it doesn't work.
First, you have to fix your HTML code:
<td><button id="timesheet_view_" >View</button</td>:
close the button element correctly: </button with a '>'.
Second, you have to give every button a unique ID:
Your code:
#for(p <- people) {
<tr>
<td><button id="timesheet_view_" >View</button</td>
<td><b>#p.getName()</b></td>
<td>#p.isActive()</td>
</tr>
}
Try it with:
#for(p <- people) {
<tr>
<td><button id="timesheet_view_#p.id">View</button></td>
<td><b>#p.getName()</b></td>
<td>#p.isActive()</td>
</tr>
}
<script>
$(document).ready(function() {
// There are better ways to do this, but it's just for your example
#for(p <- people) {
$("#timesheet_view_#p.id").click(function(e) {
... // your javascript code here
});
}
});
</script>
In my opinion it's better to use a link here (instead of a button), because for every button you need to code extra javascript for the onclick event. Try it with a link and Play! will do the work for you:
#for(p <- people) {
<tr>
<td><a class="btn" href="#routes.Application.view(p.id)">View</a></td>
<td><b>#p.getName()</b></td>
<td>#p.isActive()</td>
</tr>
}
Btw, if you use Twitter Bootstrap you can use class="btn" and your link looks like a button.
Start your Play! application and have a look in the HTML source code. You will see your code <button id="timesheet_view_#p.id">View</button> will looks like this:
<button id="timesheet_view_1">View</button>
<button id="timesheet_view_2">View</button>
...
<button id="timesheet_view_9">View</button>
Hope this helps.
Best regards,
gfjr
You can't do it that way. Javascript is running client-side whereas Play is running server-side.
At the time your Javascript is running, the page has already been rendered and Play has done it's part.
What you can do is to capture relevant data from people and put it in data attributes.
<tbody>
#for(p <- people) {
<tr data-people-id="#p.getId()" data-people-name="#p.getName()">
<td><button class="timesheet_view" >View</button</td>
<td><b>#p.getName()</b></td>
<td>#p.isActive()</td>
</tr>
}
</tbody>
And in your script you can get the data attributes.
<script>
$( ".timesheet_view" )
.button()
.click(function() {
var row = $(this).closest("tr");
var peopleId = row.data("peopleId");
var peopleName = row.data("peopleName");
// Do whatever you want with this data...
// Not sure how the showTimeSheet is working so leave it up to you
//showTimeSheet('current', '<%= people[i].name %>');
});
</script>

Change Table Cell Text Color when event form onchange is used

I looking for the right way (works in all most any Browser) to change cell table text color (which is a link) when the content in a form change using onchange event. I am using this:
JavaScript code
function changeColor(num){
if (num == "1"){
cont = num - 1;
answer[cont] = 1;
document.getElementById("cell_1").className="cellNumFilled";
}
HTML Code
<table border="1" cellspacing="0" cellpadding="2">
<tr>
<td><a class="cellNum" HREF="#preg1" title="1" id="cell_1">1</a></td>
<td><a class="cellNum" HREF="#preg2" title="2" id="cell_2">2</a></td>
<td><a class="cellNum" HREF="#preg3" title="3" id="cell_3">3</a></td>
</tr>
</table>
<div id="quesItem">
<p><b>1. [ 1 Pts.]</b> bla bla bla</p>
<p>Answer:
<input type="text" name="a6" maxlenght="200" size="20" onchange="changeColor(1)" />
<input type="button" value="Preview"/>
</p>
</div>
The complete "functional code" is in this jsfiddle.
When the content in the input box change, the color in the top of the table must change too. I am using two classes for tag , one by default and another one when content change through 'document.getElementById("idName").className="newClassName";' but doesn't work. Any idea why? or a better and simple way to do that?
Before setting class just remove that attribute like this
document.getElementById("cell_1").removeAttribute("class")
and then
document.getElementById("cell_1").setAttribute("class","cellNumFilled")
try the below :
document.getElementById("idName").setAttribute('class', 'className');
I hope it helps.

Categories

Resources