replace with a string that depends on what found - html

If I want to replace
1. First title
with
1. First title
which means I want to replace the garbage text with the numbering in the content, how can I do that with command find and replace engine like the ones in VScode or sublime text?
I have tried:
find: #.*">[0-9]+\.
replace: #$$0">$$0.
This doesn't work at all and further, when the list goes long, numberings may have more digits, like "17. Some title". Better use only plain find and replace engines rather than other programmes or JS.

You could do it in jQuery:
$('a').each((i, a) => {
$(a).attr('href', '#' + parseInt($(a).text()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1. First title
2. Second title
3. Third title
or in pure JavaScript:
document.querySelectorAll('a').forEach(a => {
a.href = '#' + parseInt(a.innerHTML);
});
1. First title
2. Second title
3. Third title

You can do it with Vanilla Javascript using a regex matching the first digit of the string :
^[\d]*
You can test it here : https://regex101.com/r/Vq0Vm0/1
Something like that will work :
const $aList = document.querySelectorAll('a');
const pattern = /^[\d]*/g;
$aList.forEach($a => {
const digit = $a.textContent.match(pattern)[0];
$a.setAttribute('href', `#${digit}`);
});
1. First title
17. First title
1456456. First title
1456546654. First title
1546456. First title

I would personally use jQuery alongside a RegEx match to extract the number in the string.
HTML:
<div class="row d-flex justify-content-center">
<div class="col-md-4 d-flex justify-content-center">
<button class="btn-primary btn-change-content">Change content</button>
</div>
<div class="col-md-4 d-flex justify-content-center">
1. First title.
</div>
<div class="col-md-4 d-flex justify-content-center">
2. Second title.
</div>
</div>
jQuery:
$('.btn-change-content').on("click", function() {
$('a').each(function () {
var anchorText = $(this).text();
var num = anchorText.match(/\d+/)[0];
$(this).attr("href", "#"+num);
});
});
$('a').on("click", function(e) {
e.preventDefault();
var hrefAttr = $(this).attr("href");
alert(hrefAttr);
});
Snippet: (try to first click the anchor tags, then change content and click them again)
$('.btn-change-content').on("click", function() {
$('a').each(function () {
var anchorText = $(this).text();
var num = anchorText.match(/\d+/)[0];
$(this).attr("href", "#"+num);
});
});
$('a').on("click", function(e) {
e.preventDefault();
var hrefAttr = $(this).attr("href");
alert(hrefAttr);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row d-flex justify-content-center">
<div class="col-4 d-flex justify-content-center">
<button class="btn-primary btn-change-content">Change content</button>
</div>
<div class="col-4 d-flex justify-content-center">
1. First title.
</div>
<div class="col-4 d-flex justify-content-center">
2. Second title.
</div>
</div>
Codepen Example here.

Related

How can I get the ID of div inside a div wrapper. Jquery

I have a div that looks like this:
<div id="data" class="grid grid-cols-2">
</div>
and I have a function that can append in data div:
function loadStaticBar(data) {
let pl_name= `bar-${data.title.replace(/\s+/g, '-').toLowerCase()}`
$('#data').append(`
<div class="flex flex-col" id="${pl_name}-wrapper">
<div class="static barchart" id="${pl_name}-plot">
</div>
</div>
`)
}
The content of loadStaticBar(data) is a key and value it's a details for charts:
{id: 453, title: 'Bar Chart Example', select: 'bar-form', xtitle: 'Values', ytitle: 'Date', …}
Now, I'm trying to get all the IDs with the class static. I have tried:
$('#data').find('.static')
And I get S.fn.init [prevObject: S.fn.init(1)] inside of this are bunch of information. How can I get the IDs of the div that containing static class like this.
ids = [line-plot, bar-plot]
The answer to the updated question could be:
function loadStaticBar(data) {
let pl_name= `bar-${data.title.replace(/\s+/g, '-').toLowerCase()}`
$('#data').append(`
<div class="flex flex-col" id="${pl_name}-wrapper">
<div class="static barchart" id="${pl_name}-plot">
</div>
</div>
`)
}
const data={id: 453, title: 'Bar Chart Example', select: 'bar-form', xtitle: 'Values', ytitle: 'Date'};
$(function(){
loadStaticBar(data); // create the divs first !!!
const ids=$("#data .static").get().map(el=>el.id);
console.log(ids);
});
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<div id="data" class="grid grid-cols-2">
</div>
As you want to receive a "proper" array instead of a jQuery object it makes sense to .get() the selected DOM elements first and then .map() them using the standard Array-method.
Incidentally, you can solve the originally posted question also without jQuery:
document.addEventListener("DOMContentLoaded", function () {
const ids=[...document.querySelectorAll("#data .static")].map(el=>el.id);
console.log(ids);
});
<div id="data" class="grid grid-cols-2">
<div class="flex flex-col" id="line-wrapper">
<div class="static linechart" id="line-plot">
</div>
</div>
<div class="flex flex-col" id="bar-wrapper">
<div class="static barchart" id="bar-plot">
</div>
</div>
</div>

SQL Query won't run after pressing button

I am trying to run the searchSQL query with the input from the searchbar after pressing the button. The 'sql' query runs on start.
When pressing the button it won't update the images according to the input from the search?
#using WebMatrix.Data
#{
var db = Database.Open("MTGDecks");
var sql = "SELECT * FROM Cards WHERE isPopular <> 0";
var searchSQL = "SELECT * FROM Cards WHERE cardName LIKE CONCAT ('%', #0, '%')";
var searchValue = Request.Form["searchBox"];
if (IsPost)
{
var searching = db.Query(searchSQL, searchValue);
}
var output = db.Query(sql);
}
<link href="~/Content/Site.css" rel="stylesheet" />
<h2>All Cards</h2>
<form method="post" action="/Home/Index">
<input type="text" name="searchBox" />
<button type="submit" class="btn">Search</button>
Make New Deck
<div class="row">
<div class="row justify-content-center">
#foreach (var row in output)
{
<div class="col-4">
<div class="card">
<img src="#row.imageURL" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#row.cardName</h5>
<p class="card-text">#row.oracleText</p>
Details
</div>
</div>
</div>
}
</div>
</div>
</form>
I'm unsure of what to do.
ok, going out on a limb here... your "button" is the href that redirects you to the details of the #row.cardID
In your code block you have it set up to do some stuff, but you never actually call it... If I were doing this in Blazor (razor syntax) the solution would be something like
#page "/myPage/{int: cardID}
HTML HERE
//Pseudocode, don't copy/paste
#code
{
public override void OnParametersSet ()
{
if (cardID != null)
Run The COde!!
}
}
So, basically, you're missing wiring up some kind of page event. There's a TON wrong with everything you're doing, but... hopefully this will get you to the next logical question.

Change HTML code after page load (w/ jQuery ?)

I'm trying to find out a way to modify the HTML code to replace every Bootstrap col class name (col, col-xs-x, col-x etc.) by col-12 after the page is loaded.
I could do that with .removeClass('name') and then .addClass('name') but I need to use some RegEx because I want to modify Bootstrap col class names.
From something like this :
<body>
<div class="col-xs-6 col-sm-4 col-2"> Content 1 </div>
<div class="col"> Content 2 </div>
</body>
I want to modify to something like this :
<body>
<div class="col-12"> Content 1 </div> <!--can even be class="col-12 col-12 col-12"-->
<div class="col-12"> Content 2 </div>
</body>
I found here someone who did that with html().replace in jQuery so I tried to do the same but it doesn't work.
Way like this:
$(document).ready(function () { // my RegEx works well, verified it on regex101
let col_let_num = $('body').html().replace(/\bcol\b(\-[a-z]{0,2})?(\-)?([0-9]{0,2})?/i, 'col-12')
$('body').html(col_let_num)
})
So my question is, do you have any solution to change HTML content after the page is loaded ?
You forgot to add ')' to your Javascript.
but i really cant realize what you are trying to do here.
any way
$(document).ready(function () { // my RegEx works well, verified it on regex101
let col_let_num = $('body').html().replace(/\bcol\b(\-[a-z]{0,2})?(\-)?([0-9]{0,2})?/i, 'col-12')
$('body').html(col_let_num)
})
Edited
here you go
$('[class*="col"]').each((i, e) => {
let classes = $(e).attr('class').split(/\s+/);
classes.forEach(v => {
let col_let_num = v.replace(/\bcol\b(\-[a-z]{0,2})?(\-)?([0-9]{0,2})?/i, 'col-12')
$(e).attr('class', col_let_num)
})
})
this should work.

jquery multiple selectors in single query

I have various lists and inside those lists I've list of checkboxes and I've show more/less functionality.
Now, everything works fine but I want to convert some logic to one liner, tried various ways but didn't work so posting here.
Here is HTML part, and assume I have multiple lists like this.
<div id="list-special-needs">
<h4 class="filter-header">Special Needs</h4>
#foreach (var item in specialNeeds)
{
<div class="am-checkbox" style="padding: 3px 0;">
<input id="chk-special-needs-#item.ToLower()" name="special-needs" value="#item" type="checkbox" class="schedulerepeat-checkbox" onclick="return prepareSearchParams()" />
<label for="chk-special-needs-#item.ToLower()" class="margin-h-10 mobile-padding">#item</label>
</div>
}
<p onclick="return loadMore(this, 'list-special-needs', '#specialNeeds.Length')" class="show-more">Show more...</p>
</div>
<div class="clearfix"></div>
Js:
<script type="text/javascript">
PageEvent.add(PageEvent.AFTER_INIT, function () {
$("#list-services .am-checkbox").slice(5).hide();
$("#list-timing .am-checkbox").slice(5).hide();
$("#list-special-needs .am-checkbox").slice(5).hide();
$("#list-neighborhoods .am-checkbox").slice(5).hide();
});
function loadMore(element, listId, length) {
var listSelector = $(`#${listId} .am-checkbox`);
var isShowMore = $(element).text() == 'Show more...';
if (isShowMore) {
//..show more
$(element).text('Hide...');
listSelector.slice(0, length).slideDown();
} else {
//..hide
$(element).text('Show more...');
listSelector.slice(5).slideUp();
}
}
</script>
and I just want to convert this into one liner.
$("#list-services .am-checkbox").slice(5).hide();
$("#list-timing .am-checkbox").slice(5).hide();
$("#list-special-needs .am-checkbox").slice(5).hide();
$("#list-neighborhoods .am-checkbox").slice(5).hide();
Although I tried this, but it didn't work.
$("#list-services .am-checkbox, #list-timing .am-checkbox ..").slice(5).hide();
Any help would be really appreciated.
You should work with each one of them separately. So from your code:
$("#list-services .am-checkbox, #list-timing .am-checkbox ..").slice(5).hide();
We can take that and loop through and attack each one with
Array.from($("#list-services .am-checkbox, #list-timing .am-checkbox ..")).forEach(elem => {elem.slice(5).hide());
Although I'd suggest adding a class to each one of the blocks with te list-... IDs, so the code is nicer and go with:
Array.from($(".list-block .am-checkbox")).forEach(elem => {elem.slice(5).hide());
Create array of your elements with id's, then for each search for that same class and do stuff...
[...$("#list-services"), ...$("#list-timing"), ...$("#list-special-needs"), ...$("#list-neighborhoods")].forEach(el => {
$(el).find(".am-checkbox").slice(5).hide()
})
"need something more elegant"
Beauty is in eye of the beholder, is this one pretty enough?
[...document.querySelectorAll("#list-services, #list-timing, #list-special-needs, #list-neighborhoods")].forEach(el => $(el).find(".am-checkbox").slice(5).hide())
[...document.querySelectorAll("#list-services, #list-timing, #list-special-needs, #list-neighborhoods")].forEach(el => $(el).find(".am-checkbox").css("color", "red"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list-services">
<div class="am-checkbox">1</div>
</div>
<div id="list-timing">
<div class="am-checkbox">2</div>
</div>
<div id="list-special-needs">
<div class="am-checkbox">3</div>
</div>
<div id="list-neighborhoods">
<div class="am-checkbox">4</div>
</div>

Delete item in the database using a simple button on angular 7

im trying to create a delete button on one side of a word that i get from the data base and i cant figure out how to do it
I already delete the word but i have to use a input form on the html and i have to write by hand the word i that i want to delete, but this is no god for user experience, so thats why im seeking that X button
this is my html
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Hashtags</h4>
<h6 class="card-subtitle">Hashtags <code> uno</code> agregar.</h6>
<div class="row button-group">
<div class="col-lg-2 col-md-4" *ngFor="let hash of getHashtag">
<form [formGroup]="form" (ngSubmit)="onDelet(form.value)">
<button class="ti-close" type="submit"></button >
<input type="text" formControlName="hashtag" > {{hash}} <br>
<p id="competitors" > {{hash}}</p>
</form>
</div>
</div>
</div>
</div>
<div class="card">
this is my componet file:
public onDelet(){
this._getHashtag.deleteHashtag(this.form.value.hashtag).subscribe(
result =>{
// console.log(result)
this._getHashtag.getHashtag().subscribe(
resultado =>{
this.getHashtag = resultado
this.getHashtag = this.getHashtag.result
// console.log("Resultado", this.getHashtag)
},
error => {
var mensajeError = <any>error;
}
);
}
)
}
this is my service component:
deleteHashtag(hastagdel:string){
let header = new Headers({"Content-Type":"application/json"})
return this._http.post(this.url + "/removeHashtags" ,{hashtags:[hastagdel]}, {withCredentials:true})
}
I'm pretty sure you want to use http.delete, not http.post in your service.
http.post adds something to the db,
http.delete removes something,
http.put modifies something, and
http.get retrieves something from the db.
There are other http options, but those are the main ones.