How to change the node when blur event occur? - javascript

Source HTML structure.
<table>
<tr>
<td>class</td>
<td><input type="text" id="data1"></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" id="data2"></td>
</tr>
</table>
Event: The Source HTML struture turns into the Target HTML struture after typing test1 in input whose id is data1 and mouse focus go out of the input.
Target HTML structure.
<table>
<tr>
<td>class</td>
<td>test1</td>
</tr>
<tr>
<td>name</td>
<td><input type="text" id="data2"></td>
</tr>
</table>
Here is my JS.
function changeNode(event){
ob =document.activeElement;
_str = ob.value;
ob.parentNode.removeChild(ob);
ob.parentNode.innerText = _str;
}
document.addEventListener("blur",changeNode,true);
Why my JS can't achieve my expected target?
How to fix it?

You are selecting the active element while the event is that an object's focus is lost.
You should select event.target as ob and your code should work:
Also: you don't need to delete the object, your overriding all inner text so the object is automatically deleted.
function changeNode(event){
ob = event.target;
_str = ob.value;
ob.parentNode.innerText = _str;
}
document.addEventListener("blur",changeNode,true);
<table>
<tr>
<td>class</td>
<td><input type="text" id="data1"></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" id="data2"></td>
</tr>
</table>

Several problems in your code:
You need to add the event listener to the input itself, not the document object. You can then simply use event.target instead of activeElement (input is no longer active after the blur event…)
You're trying to access ob.parentNode after removing ob. Try storing it in a variable first:
function changeNode(event) {
var ob = event.target;
var cell = ob.parentNode;
var _str = ob.value;
cell.removeChild(ob);
cell.innerText = _str;
}
document.querySelectorAll("input").forEach(function(input) {
input.addEventListener("blur", changeNode);
});
<table>
<tr>
<td>class</td>
<td><input type="text" id="data1"></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" id="data2"></td>
</tr>
</table>
Note: querySelectorAll(…).forEach
might not be reliable in some old browsers, if you need to support them, see css-tricks.com: Loop Over querySelectorAll Matches

function changeNode(event){
var ob=event.target;
ob.parentNode.append(ob.value);
ob.parentNode.removeChild(ob);
}
document.getElementById("data1").addEventListener("blur",changeNode,true);
<table>
<tr>
<td>class</td>
<td><input type="text" id="data1"></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" id="data2"></td>
</tr>
</table>

function changeNode(event) {
var ob = event.target;
var cell = ob.parentNode;
var _str = ob.value;
cell.removeChild(ob);
cell.innerText = _str;
}
document.addEventListener("blur",changeNode,true);

Related

Create Javascript object from HMTL table

I have a table like
<table id="misc_inputs">
<thead>
<tr><th>Property</th><th>Input</th></tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td><input type="number" value="1"></td>
</tr>
<tr>
<td>b</td>
<td><input type="number" value="2"></td>
</tr>
...
I would like to convert that table to a Javascript object like
misc_inputs = {"a": 1, "b": 2, ...
How can the result be generated?
You can use below re-usable javascript method to convert any HTML table into Javascript object.
<table id="MyTable">
<thead>
<tr><th>Property</th><th>Input</th></tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td><input type="number" value="1"></td>
</tr>
<tr>
<td>b</td>
<td><input type="number" value="2"></td>
</tr>
</tbody>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
function ConvertHTMLToJSObject(htmlTableId)
{
var objArr = {};
var trList = $('#' + htmlTableId).find('tr');
$('#' + htmlTableId).find('tbody tr').each(function ()
{
var row = $(this);
var key = $(row).first().text().trim();
var value = $(row).find('input').attr("value");
objArr[key] = value;
});
return objArr;
}
var obj = ConvertHTMLToJSObject("MyTable");
console.log(obj);
});
You can loop through each inputs and create the object:
var misc_inputs = {};
$("#misc_inputs input[type=number]").each(function(i, el){
var k = $(this).closest('td').prev().text();
return misc_inputs[k] = +el.value;
});
console.log(misc_inputs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="misc_inputs">
<thead>
<tr><th>Property</th><th>Input</th></tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td><input type="number" value="1"></td>
</tr>
<tr>
<td>b</td>
<td><input type="number" value="2"></td>
</tr>
</tbody>
</table>
Probably you can do it without any library but with jQuery it's easier. Something like that should work (not tested):
// Here we will store the results
var result = {};
// Ask jQuery to find each row (TR tag) and call a function for each
$('tr').each(function(){
// Inside a jQuery each() "this" is the current element, the TR tag in this example
var row = $(this);
// We ask jQuery to find every TD inside the current row (the second parameter of a jQuery selector is the parent node for your search). We take the first one and then we take the content of the tag
var label = $("td", row).first().text();
// We ask for an "input" tag inside the current row and we read its "value" attribute
var value = $("input", row).attr("value");
// Store everything in result
result[label] = value;
});

Value not displaying in correct input

I have a 2 row table with input fields that does a calculation when I focusout on the first input. The problem I am experiencing is when I focusout on the second row, my new value is displayed in the first row corresponding input. I'm not sure why this is happening. I would greatly appreciate your help.
My expectation is when I enter a value in a row input (Cost) and focusout the new value should be set in the same row but in the input (New Cost).
function Calculate(element) {
var dollar = 216.98;
var id = element.id;
var oldcost = $(element).val();
var newcost = oldcost * dollar;
$("#" + id).closest("tr").find("td #new").val(newcost);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" id="old" onfocusout="Caluculate(this)" /></td>
<td><input type="number" new="new" /></td>
</tr>
<tr>
<td><input type="number" id="old" onfocusout="Caluculate(this)" /></td>
<td><input type="number" new="new" /></td>
</tr>
</table>
There's several issues here. Firstly you're repeating the same id attribute which is invalid; they must be unique. I'd suggest using a class instead. Secondly, there's is no new attribute. I presume that's a typo and should be an id, but again see my first point.
Next, the function you defined is named Calculate() yet the call is to Caluculate().
Then you should also be using unobtrusive event handlers as on* event attributes are very outdated and should be avoided where possible. As you've already included jQuery in the page you can use the on() method. The input event would seem to be more applicable to your usage as well, especially given it also catches the up/down arrow usage on the number control, although you can change this to blur if preferred.
Finally, it's a simply a matter of amending your DOM traversal logic to work with the new classes, like this:
var dollar = 216.98;
$('.old').on('input', function() {
var oldcost = $(this).val();
var newcost = oldcost * dollar;
$(this).closest("tr").find(".new").val(newcost);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" class="old" /></td>
<td><input type="number" class="new" /></td>
</tr>
<tr>
<td><input type="number" class="old" /></td>
<td><input type="number" class="new" /></td>
</tr>
</table>
Your use of id's is kind of messed up. First of all be sure to use an id once in the entire HTML file.
For your usecase better use classes.
Also be sure to type your function names correct ;)
function Calculate(element) {
var dollar = 216.98;
var parent = $(element).closest('tr');
var oldcost = $(element).val();
var newcost = oldcost * dollar;
parent.find(".new").val(newcost.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>Cost</th>
<th>New Cost</th>
</tr>
<tr>
<td><input type="number" class="old" onfocusout="Calculate(this)" /></td>
<td><input type="number" class="new" /></td>
</tr>
<tr>
<td><input type="number" class="old" onfocusout="Calculate(this)" /></td>
<td><input type="number" class="new" /></td>
</tr>
</table>
They have the same ID. You need to make the ID different
Firstly, there is a a typo.Change caluculate to calculate
There must not be the same id two elemnts have the same id.You could change the id of the first to old-1 or something different

How to get multiple selected cell array values with checkbox in jquery, then send with ajax post

How should I get an array value from a table cell when clicking checkbox with jQuery? If I've selected cell 1, I want to get array like ["BlackBerry Bold", "2/5", "UK"], but if I've selected all of them, I want to get all the data in the form of an array of arrays.
<table border="1">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
Please help.
Onclick get 3 children of the parent and add content to data. Used jquery nextAll for siblings and splice the 3 required.
Attached event to the table, onclick will check if element is INPUT.
If it's input, will get parent of that input which will be <td>.
For this parent element, will get three siblings using jquery.
Will add in selected if not present else delete, using indexOf.
CodePen for you to playaround: [ https://codepen.io/vivekamin/pen/oQMeXV ]
let selectedData = []
let para = document.getElementById("selectedData");
let tableElem = document.getElementById("table");
tableElem.addEventListener("click", function(e) {
if(e.target.tagName === 'INPUT' ){
let parent = e.target.parentNode;
let data = [];
$(parent).nextAll().map(function(index, node){
data.push(node.textContent);
})
let index = selectedData.indexOf(JSON.stringify(data))
if(index == -1){
selectedData.push(JSON.stringify(data));
}
else{
selectedData.splice(index,1);
}
para.textContent = "";
para.innerHTML = selectedData ;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="table">
<tr>
<th><input type="checkbox" /></th>
<th>Cell phone</th>
<th>Rating</th>
<th>Location</th>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
<td>UK</td>
</tr>
<tr>
<td align="center"><input type="checkbox" /></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
<td>US</td>
</tr>
<tr>
<td align="center"><input type="checkbox"/></td>
<td>Droid X</td>
<td>4.5/5</td>
<td>REB</td>
</tr>
</table>
<h3> Selected Data: </h3>
<p id="selectedData"></p>
Updated to meet your needs.
create a function to build the array values based on looking for any checked inputs then going to their parents and grabbing the sibling text values
attach your change event to the checkbox click even.
I provided a fiddle below that will output the array in the console.
function buildTheArray(){
var thearray = [];
$("input:checked").parent().siblings().each(function(){
thearray.push($(this).text());
});
return thearray;
}
$("input[type='checkbox']").change(function(){
console.log(buildTheArray());
});
Fiddle:
http://jsfiddle.net/gcu4L5p6/

Get clicked column index from row click

I have a row click event. Recently had to add a checkbox to each row. How can I identify the clicked cell on row click event?
Or prevent row click when clicked on the checkbox.
Attempts: this.parentNode.cellIndex is undefined on the row click event.
function pop(row){
alert(row.cells[1].innerText);
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Do you want something like this? You can just check the type attribute of the source element of the event and validate whether to allow it or not, you can stop the event using e.stopPropagation();return;.
function pop(e, row) {
console.log(e.srcElement.type);
if(e.srcElement.type === 'checkbox'){
e.stopPropagation();
return;
}else{
console.log(row);
alert(row.cells[1].innerText);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event, this);">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
You should pass in the event details to your function and check the target property:
function pop(e){
// If the target is not a checkbox...
if(!e.target.matches("input[type='checkbox']")) {
alert(e.target.cellIndex);
}
}
<table style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr onclick="pop(event)">
<td><input type="checkbox" id="123456" /></td>
<td>Lonodn</td>
</tr>
</table>
Note: If you have nested elements inside the <td>, you might want to check e.target.closest("td") instead.
Note 2: You might need a polyfill for the matches method depending on which browsers you're supporting.
Here is an example if you don't want to attach a listener on every row :
document.getElementById("majorCities").addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var tr = e.target.parentElement.parentElement;
var city = tr.cells[1].innerHTML;
console.log(city+":checked="+checked);
}
});
<table id="majorCities" style="width:100%">
<tr>
<th>Select</th>
<th>Site</th>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>London</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>Paris</td>
</tr>
<tr>
<td><input type="checkbox"/></td>
<td>New-York</td>
</tr>
</table>
window.pop = function(row){
console.log('here');
var parent = row.parentNode;
Array.from(row.parentNode.querySelectorAll('tr')).forEach(function(tr, index){
if (tr === row) {
alert(index)
}
})
}
https://jsfiddle.net/sz42oyvm/
Here is for the pleasure, another example with an object containing the cities' names and a method to draw the table with ids corresponding to the name of the clicked city, so getting the clicked name is easier.
(function () {
var mySpace = window || {};
mySpace.cities = {};
mySpace.cities.pointer = document.getElementById("majorCities");
mySpace.cities.names = ["Select","City"];
mySpace.cities.data = [{"name":"Paris"},{"name":"New Delhi"},{"name":"Washington"},{"name":"Bangkok"},{"name":"Sydney"}];
mySpace.cities.draw = function(){
this.pointer.innerHTML="";
var html = "";
html+="<tr>"
for(var i=0;i < this.names.length;i++){
html+="<th>"+this.names[i];
html+="</th>"
}
html+="</tr>"
for(var i=0;i < this.data.length;i++){
html+="<tr>"
html+="<td><input id='"+this.data[i].name+"' type='checkbox'/></td>"
html+="<td>"+this.data[i].name+"</td>"
html+="</tr>"
}
this.pointer.innerHTML=html;
}
mySpace.cities.draw();
mySpace.cities.pointer.addEventListener("click", function(e){
if(e.target.type === 'checkbox'){
var checked = e.target.checked;
var city = e.target.id;
console.log(city+":checked="+checked);
}
});
})();
table {width:25%;background:#ccc;border:1px solid black;text-align:left;}
td,tr {background:white;}
th:first-of-type{width:20%;}
<table id="majorCities">
</table>

how to get text of td that belongs to checked radio button

I 'm trying to get the text of the td that belong to checked radio buttons, but I can't and my code doesn't work correctly:
<tr>
<td><input name="radio_org_id" type="radio"></td>
<td>male</td>
</tr>
$("body").on("change", "input[name='radio_org_id']:radio:checked", function () {
$('input[name="radio_org_id"]:radio:checked').each(function () {
var vIns_title = $(this).next().find('td').text()
alert(vIns_title)
});
Use $(this).parent().next("td").text()
$("body").on("change", "input[name='radio_org_id']:radio:checked", function() {
$('input[name="radio_org_id"]:radio:checked').each(function() {
var vIns_title = $(this).parent().next("td").text()
alert(vIns_title)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input name="radio_org_id" type="radio"></td>
<td>male</td>
</tr>
<tr>
<td><input name="radio_org_id" type="radio"></td>
<td>female</td>
</tr>
</table>
Try this $(this).closest('td').next('td').text() document for closest(). And your click function selector was wrong.so change as like this "input[name='radio_org_id']"
$("body").on("change", "input[name='radio_org_id']", function() {
$('input[name="radio_org_id"]:checked').each(function() {
var vIns_title = $(this).closest('td').next('td').text()
console.log(vIns_title)
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input name="radio_org_id" type="radio"></td>
<td>male</td>
</tr>
<table>
Your initial selector is flawed as you only select already checked elements. The :radio is also redundant.
To fix your issue, use closest().next() to get the sibling td element. Try this:
$('table').on("change", "input[name='radio_org_id']", function() {
if ($(this).is(':checked')) {
var vIns_title = $(this).closest('td').next('td').text()
console.log(vIns_title)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input name="radio_org_id" type="radio"></td>
<td>male</td>
</tr>
<tr>
<td><input name="radio_org_id" type="radio"></td>
<td>female</td>
</tr>
</table>
You should also note that you could potentially make this much simpler by placing a value on the radio input and reading that out in the JS code.

Categories

Resources