How to select the closest element with contains selector jquery - javascript

I want to replace the "{{my_name}}" and "{{my_email}}" with a string, but the program is not working, what should i do?
Thanks.
$(".notes *:contains('{{')").text(function() {
var rawkey = $(this).text().match(/{{(.*?)}}/i)[0]; // Output (console.log) : {{my_name}} or {{my_email}}
var key = $(this).text().match(/{{(.*?)}}/i)[1]; // Output (console.log) : my_name or my_email
if (key.indexOf('name') > -1) {
$(this).text($(this).text().replace(rawkey, "Tony"));
} else if (key.indexOf('email') > -1) {
$(this).text($(this).text().replace(rawkey, "tonyhawk#gmail.com"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_name}}, {{my_email}}</p>
</td>
</tr>
</table>
</div>

Set the result after replacing back to the element's textContent:
$(".notes *:contains('{{')").text(function() {
var rawkey = $(this).text().match(/{{(.*?)}}/i)[0];
var key = $(this).text().match(/{{(.*?)}}/i)[1];
if (key.indexOf('name') > -1) {
$(this).text($(this).text().replace(rawkey, "Tony"));
} else if (key.indexOf('email') > -1) {
$(this).text($(this).text().replace(rawkey, "tonyhawk#gmail.com"));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_email}}</p>
</td>
</tr>
</table>
</div>

You can do like this.
var $content=$('.notes').html();
var finalContent=$content.replaceAll("my_name","Tony").replaceAll("my_email","tonyhawk#gmail.com").replaceAll("{{","").replaceAll("}}","");
$(".notes").html(finalContent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="notes">
<h4>{{my_name}}</h4>
<table>
<tr>
<td>
<p>{{my_name}},{{my_email}}</p>
</td>
</tr>
</table>
</div>

Related

HTML table filter with unique values only

I have a 300x11(rowXcolumn) html table that I wanted to filter exactly like Excel or Google Sheets's filter. However, after searching a bit I found out the following code below in a website. This works as I wanted but it has one major problem. It shows same value multiple times. For example in the 2nd column, there are 2 values same "Apple" and 2 whitespaces . In the current code, it displays Apple twice and whitespace twice. However, I want it should show the same values only once. For example, it will show "Apple" only once, and if I select apple it will filter both rows containing apple.
Thank you very much for your help.
index.html
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.0.3" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<table class="grid">
<thead>
<tr>
<td index=0>Name
<div class="filter"></div>
</td>
<td index=1>Address
<div class="filter"></div>
</td>
<td index=2>City
<div class="filter"></div>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>first</td>
<td>first add</td>
<td>SDF dfd</td>
</tr>
<tr>
<td>second</td>
<td></td>
<td>SDF dfd</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF dfd</td>
</tr>
<tr>
<td>third</td>
<td></td>
<td>SDF hello</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF hello</td>
</tr>
</tbody>
</table>
</body>
</html>
script.js
$(document).ready(function(){
$(".grid thead td").click(function(){
showFilterOption(this);
});
});
var arrayMap = {};
function showFilterOption(tdObject){
var filterGrid = $(tdObject).find(".filter");
if (filterGrid.is(":visible")){
filterGrid.hide();
return;
}
$(".filter").hide();
var index = 0;
filterGrid.empty();
var allSelected = true;
filterGrid.append('<div><input id="all" type="checkbox" checked>Select All</div>');
var $rows = $(tdObject).parents("table").find("tbody tr");
$rows.each(function(ind, ele){
var currentTd = $(ele).children()[$(tdObject).attr("index")];
var div = document.createElement("div");
div.classList.add("grid-item")
var str = $(ele).is(":visible") ? 'checked' : '';
if ($(ele).is(":hidden")){
allSelected = false;
}
div.innerHTML = '<input type="checkbox" '+str+' >'+currentTd.innerHTML;
filterGrid.append(div);
arrayMap[index] = ele;
index++;
});
if (!allSelected){
filterGrid.find("#all").removeAttr("checked");
}
filterGrid.append('<div><input id="close" type="button" value="Close"/><input id="ok" type="button" value="Ok"/></div>');
filterGrid.show();
var $closeBtn = filterGrid.find("#close");
var $okBtn = filterGrid.find("#ok");
var $checkElems = filterGrid.find("input[type='checkbox']");
var $gridItems = filterGrid.find(".grid-item");
var $all = filterGrid.find("#all");
$closeBtn.click(function(){
filterGrid.hide();
return false;
});
$okBtn.click(function(){
filterGrid.find(".grid-item").each(function(ind,ele){
if ($(ele).find("input").is(":checked")){
$(arrayMap[ind]).show();
}else{
$(arrayMap[ind]).hide();
}
});
filterGrid.hide();
return false;
});
$checkElems.click(function(event){
event.stopPropagation();
});
$gridItems.click(function(event){
var chk = $(this).find("input[type='checkbox']");
$(chk).prop("checked",!$(chk).is(":checked"));
});
$all.change(function(){
var chked = $(this).is(":checked");
filterGrid.find(".grid-item [type='checkbox']").prop("checked",chked);
})
filterGrid.click(function(event){
event.stopPropagation();
});
return filterGrid;
}
style.css
table thead tr td{
background-color : gray;
min-width : 100px;
position: relative;
}
.filter{
position:absolute;
border: solid 1px;
top : 20px;
background-color : white;
width:100px;
right:0;
display:none;
}
Maybe someone else will fix that limited JS for you but otherwise use DataTables. It has all you want with extensive documentation, and it's a popular plugin so it's not hard to find any answers to questions you might have about it. Here's an example with everything you desired in your post:
/* Range Search - https://datatables.net/examples/plug-ins/range_filtering.html */
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
var min = parseInt($('#min').val(), 10);
var max = parseInt($('#max').val(), 10);
var age = parseFloat(data[3]) || 0;
if (
(isNaN(min) && isNaN(max)) ||
(isNaN(min) && age <= max) ||
(min <= age && isNaN(max)) ||
(min <= age && age <= max)
) {
return true;
}
return false;
});
$(document).ready(function() {
/* Init dataTable - Options[paging: off, ordering: off, search input: off] */
var table = $('#table').DataTable({
"paging": false,
"ordering": false,
dom: 'lrt'
});
/* Column Filters */
$(".filterhead").each(function(i) {
if (i != 4 && i != 5) {
var select = $('<select><option value="">Filter</option></select>')
.appendTo($(this).empty())
.on('change', function() {
var term = $(this).val();
table.column(i).search(term, false, false).draw();
});
table.column(i).data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
} else {
$(this).empty();
}
});
/* Range Search -> Input Listener */
$('#min, #max').keyup(function() {
table.draw();
});
});
.container {
max-width: 80%;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.13.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.13.1/datatables.min.js"></script>
<body>
<div class="container">
<input type="text" id="min" name="min" placeholder="Min Number">
<input type="text" id="max" name="max" placeholder="Max number">
<table id="table" class="display">
<thead>
<tr>
<th class="filterhead">Name</th>
<th class="filterhead">Address</th>
<th class="filterhead">City</th>
<th class="filterhead">Number</th>
</tr>
<tr>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>first</td>
<td>first add</td>
<td>SDF dfd</td>
<td>18</td>
</tr>
<tr>
<td>second</td>
<td>as</td>
<td>SDF dfd</td>
<td>50</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF dfd</td>
<td>2</td>
</tr>
<tr>
<td>third</td>
<td>as</td>
<td>SDF hello</td>
<td>25</td>
</tr>
<tr>
<td>third</td>
<td>Apple</td>
<td>SDF hello</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
</body>

How to bring only price value which with text and curreny symbol?

Now I have NT$ symbol in price, so i want to remove it so i can bring the only price(number) into script to future calculate.
what should I change?
var test = document.querySelector(".origprice");
var price = parseInt(fparent.textContent.replace(/NT/,/\U+00024/,/,/,''));
var testt = price - 150;
document.getElementById("demo").innerHTML = testt;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="test">
<table id="table">
<tr>
<td class="origprice">NT$ 1,500</td>
</tr>
</table>
<p id="demo"></p>
</div>
you can use this function to get the desired result.
var txt="NT$ 1,500";
let t= ""
var numb = txt.match(/\d/g).map(i => {
t += i ;
})
console.log(+t);
If you will have space between prices and $, then you can do like the below,
$(document).ready(function(){
let total = 0;
$('.origprice').each(function() {
total += Number($(this).text().split(' ')[1]);
});
console.log(total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="origprice">NS$ 10000</td>
<td class="origprice">NS$ 20000</td>
<td class="origprice">NS$ 30000</td>
</tr>
</table>

How do I get and pass the field of the row having class="name" in the following html?

<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata(parameter)">Fetch Details</button>
</td>
</tr>
</tbody>
In the above html, I want that the function fetchdata('parameter') to contain the text content of the td which has a class of name and is hidden, as the parameter.
OR
I need a way in which I can get the text content of the td having class of name in my javascript function.
i.e.
function fetchdata() {
const name = document.somethingThatGivesMeName()
}
NOTE: There are going to be multiple rows that I may require to get the name of so I can't directly do document.queryselector('.name')
Sorry, This might be pretty simple but I can't quite figure it out.
When clicking the button find the first row up in the tree relative to the button with the closest method. Then from the row select the element with the class name and read the textContent or innerText of that element.
const buttons = document.querySelectorAll('.js-fetch-details');
function fetchDetails(event) {
const row = event.target.closest('tr');
const name = row.querySelector('.name').textContent;
console.log(name);
}
buttons.forEach(button => button.addEventListener('click', fetchDetails));
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button class="js-fetch-details">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
You just need the quotes ':
function fetchdata(value){
console.log(value)
}
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata('parameter')">Fetch Details</button>
</td>
</tr>
</tbody>
or you can use event listener and data value:
document.querySelectorAll('button').forEach(el => {
el.addEventListener('click', e => {
e = e || window.event;
e = e.target || e.srcElement;
console.log(e.dataset.value)
})
})
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button data-value="parameter">Fetch Details</button>
</td>
</tr>
</tbody>
You can use document.getElementsByClassName('name')
This will get all the elements that have class of name.
I would put the listener on the <tbody> instead.
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.parentNode.parentNode.querySelector('.name').textContent;
console.log(name);
}
});
UPDATE
closest would also work
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.closest('tr').querySelector('.name').textContent;
console.log(name);
}
});
First you get all elements with class="name", then you pick just (the first) one with the attribute "hidden".
It's a way to do it anyway.
function fetchdata() {
const tds = document.getElementsByClassName("name")
for(let i = 0; i < tds.length; i++){
if(tds[i].getAttribute("hidden") != null) {
console.log(tds[i].innerHTML)
}
}
}
<table>
<tr>
<td class="name">gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td class="name">1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
With jQuery you can just do:
function fetchdata() {
console.log($('.name[hidden]').html());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
Note that you need to have a table around your structure for any of this to work properly. You can't have tbody, tr and td outside a table.
If you use document.getElementsByClassName you will get what you want.
However, if there will be a case where more than one instance of that class name will occur, then you need to iterate through the classes and get their values.
The following should solve your problem
<html>
<head>
<script>
function fetchdata(){
var data = document.getElementsByClassName("data");
var t = data.length;
for(i = 0; i< t; i++){
var content = data[i].innerHTML;
alert (content);
}
}
</script>
<body>
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="data" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>

Select all innerHTML of td in ul li hierarchy

I have an html structure as follows-
<ul id='abc'>
<li>
<table>
<tbody>
<tr>
<td>
A
</td>
</tr>
</tbody>
</table>
</li>
<li>
<table>
<tbody>
<tr>
<td>
B
</td>
</tr>
</tbody>
</table>
</li>
...
...
</ul>
I want to store A,B,C... values in an array using jquery.Please help...
You can use $.fn.map()
Translate all items in an array or object to new array of items.
var arr = $('#abc td').map(function(){
return $(this).text();
}).get();
you can do this by javascript by The
Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name
var values = []
var tableUl = document.getElementById("abc");
var cells = tableUl.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
values.push( cells[i].textContent.trim());
}
fiddle
Here is what you want:
var values = [];
$('ul li').find('td').each(function() {
values.push($(this).html());
});
Try utilizing .text() , String.prototype.match()
var res = $("#abc td").text().match(/\w+/gi)
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul id='abc'>
<li>
<table>
<tbody>
<tr>
<td>
A
</td>
</tr>
</tbody>
</table>
</li>
<li>
<table>
<tbody>
<tr>
<td>
B
</td>
</tr>
</tbody>
</table>
</li>
</ul>
This should work:
var values = $('ul#abc td').map(function() { return $(this).text(); });
Another way would be:
$("ul#abc li td:first-child").each(function () {
//alert($(this).text());
console.log($(this).text());
});

Trying to serialize a form with dynamically created input elements, but values of elements aren't posted

I am dynamically adding elements. However when I try and serialize the form, none of the dynamically generated elements are serialized.
This is the function I'm using to add elements to the page :
function addObjects(IDname,classname)
{
//to add more objects
var number;
switch(classname)
{
case "name":
number = no_Name++;
break;
case "part":
number = no_part++;
break;
}
var id = classname + number;
$("#"+IDname).append('<tr class="'+id+'"><td><input id="'+id+'" class="'+id+'" type="text"> <button class="'+id+'" onclick=removeAdditions("'+id+'")>x</button></td></tr>');
}
The page looks like this:
<html>
<head>
<script src="Controller.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//in order to prevent form reload when button click occurs
$(document).ready(function(){
document.getElementById("ReportForm").onsubmit = function (event) { event.preventDefault(); }
});
</script>
</head>
<body>
<div class="detailsPane" id="detailsPane1" >
<form id="ReportForm" name="ReportForm" >
<table style="width: 100%;">
<tbody>
<tr>
<td>
1. Describe the Status briefly-
</td>
<td>
<textarea id="StatDescp" name="StatDescp"></textarea>
</td>
</tr>
</tbody>
</table>
<br>
<table style="width: 100%;">
<thead>
<tr>
<th colspan="4" align="top">
Part Status
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="vertical-align:top;">
Part Name:
</td>
<td style="vertical-align:top;">
<table >
<tbody id="PartName">
<tr class="partname0">
<td><input class="part_name" type="text"> <button onclick='addObjects("PartName","part_name");'>+</button></td>
</tr>
</tbody>
</table>
</td>
<tbody>
</table>
</form>
</div>
<div id="buttonDiv" >
<a class="bottomLeftResultDiv" id="messageBox"></a>
<input type="button" id="saveButton" value="Save" style="width:85px" onclick="save();" />
</div>
</body>
</html>
And finally here is the save Button.
function save() {
var select = document.getElementById('newReportPane');
var contents = $('#ReportForm').serialize();
contents = contents.replace(/=on/g, "=checked");
contents = contents.replace(/\+/g, " ");
$("#messageBox").html("Saving report...");
console.log(contents);
$.post("/Report/Report1", { action: "save", content: contents }, function (data) {
if (data != "ACK")
$("#messageBox").html("Unable to save.");
else
$("#messageBox").html("Report saved successfully");
});
}
When I click on the save button, it only posts this StatDescp= without any of the dynamically generated elements.
I really can't figure out why.
Any help would be appreciated.
Give a name= attribute to each of your added inputs.
From http://api.jquery.com/serialize/
For a form element's value to be included in the serialized string,
the element must have a name attribute.

Categories

Resources