Adding an integer to string - javascript

I am trying to add an integer to the card id so that I can delete it when pressing the delete button. Any help?
var variable = '' +
'<div id="card+$num.toString(cnt);" class="card col-3" style="width: 18rem;" style="margin-right=3%; margin-right=3%">' +
' <img src="..." class="card-img-top" alt="..." id="image"+String(cnt)>' +
' <div class="card-body">' +
' <h5 class="card-title" id="title"+String(cnt) contentEditable="true"; >Card title</h5>' +
' <p class="card-text" id="desc"+String(cnt) contentEditable="true">Some quick example text to build on the card title and make up the' +
' bulk of the' +
' card\'s content.</p>' +
' <a href="#" class="btn btn-primary" id="button"+ String(cnt) >Go somewhere</a>' +
' <a href="#" id="btn"+String(cnt) class="close"+String(cnt)>Delete</a>' +
' </div>' +
' </div>' +
'';
$(".create").click(function(){
document.getElementById("lastRow").innerHTML+=variable;
});
$(".close"+String(cnt)).click(function(){
console.log("Doulevw!");
document.getElementById("card"+String(cnt)).hidden=true;
});

There are a few concepts that you have to know when rendering dynamic elements with js.
you have a click listener for your .close button. This listener will never fire because this listener is relevant only for your initial DOM. But your closing button is rendered dynamically, which means that listener not relevant for your button.
Easily solving that by attaching onclick to the button, and creating a function. (example follows)
I inspected your code, you DON'T have to use id mechanism to delete/hide your card element (unless you need to fire POST request), you can use parentNode (example follows)
I made some simple changes to your code:
$(".create").click(function(){
let element = `
<div id="card" class="card col- 3" style="width:18rem;style="margin-right=3%; margin-right=3%"><img src="..." class="card-img-top" alt="..." id="image"+String(cnt)><div class="card-body"><h5 class="card-title" id="title" contentEditable="true">Card title</h5><p class="card-text" id="desc" contentEditable="true">Some quick example text to build on the card title and make up the bulk of the' card\'s content.</p><a href="#" class="btn btn-primary" id="button"+ String(cnt) >Go somewhere</a><a href="#" class="close" onclick='deleteCard(this)'>Delete</a></div></div>`;
document.getElementById("lastRow").innerHTML+=element;
});
function deleteCard(delBtn){
delBtn.parentNode.parentNode.hidden = true
}
Notice for the function I added and the onclick that enables the hiding action.
Here is a codeped link for you to test by your self what I did.
Hope this was helpful, any other questions will be great :)

Related

When delete something in page , refresh all values

I have a list of items. I can create some items. The problem is that when I push the delete button I want all values to refresh and change. How can I do that?
For example when I delete the third number, then the fourth tag will be third.
$(document).on("click", ".addnew", function() {
id = this.id;
var idsh = parseInt(id.substr(3));
var ids = parseInt(id.substr(3)) + 1;
document.getElementById("ad_" + idsh).style.display = "none";
kanban = document.getElementById("kanban");
var btn = document.createElement("p");
btn.id = "main_" + ids;
btn.innerHTML =
'<span type="text" id="co_' + ids + '" class="counter text-center bg-success text-white" >' + ids + ' </span>' +
'<span id="mo_' + ids + '" class="formulbitti text-center bg-success text-white" > inner </span>' +
'<button id="de_' + ids + '" class="delete text-center bg-success text-white" >delete</button> ' +
'<button type="text" id="ad_' + ids + '" class="addnew text-center bg-success text-white" >add</button>';
kanban.appendChild(btn);
});
$("body").on("click", ".delete", function() {
id = this.id;
var ids = id.substr(3);
$('#main_' + ids).remove();
});
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<div id="kanban">
<span type="text" id="co_1" class="counter text-center bg-success text-white">1</span>
<span type="text" id="mo_1" class="formulbitti text-center bg-success text-white">inner</span>
<button type="text" id="de_1" class="delete text-center bg-success text-white">delete</button>
<button type="text" id="ad_1" class="addnew text-center bg-success text-white">add</button>
</div>
Do not use incremental id attributes. As you can see in your code they add needless complication and have absolutely no benefit.
The best method to do what you require is to use DOM traversal to relate elements to each other. The only tweak you need to make to your HTML is to add a new div to group the span and button elements. From there when a button is clicked you can use closest() to retrieve the nearest .row container and clone/remove it.
The benefit of this is that the HTML becomes standardised and the JS to work with it is the same, regardless of the content or position.
To solve the issue of the counters being updated when an action is performed, create a function which iterates through all the .counter elements and updates their text based on their index in the DOM.
Finally note that button elements have a type of button or submit, never text.
With all that said, try this:
let $kanban = $('#kanban');
let updateCounters = () => $kanban.find('.counter').text(i => i + 1);
$(document).on("click", ".addnew", e => {
$(e.target).closest('.row').clone().appendTo($kanban);
updateCounters();
});
$(document).on("click", ".delete", e => {
$(e.target).closest('.row').remove();
updateCounters();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<div id="kanban">
<div class="row">
<span type="text" class="counter text-center bg-success text-white">1</span>
<span type="text" class="formulbitti text-center bg-success text-white">inner</span>
<button type="button" class="delete text-center bg-success text-white">delete</button>
<button type="button" class="addnew text-center bg-success text-white">add</button>
</div>
</div>
One last thing to note is that it's a litte odd to have a table-level 'add' button on each row. It would make more sense to have a single add button at the top or bottom of the content.

Add dynamic li element and remove the respective one in VUEJS

I am new in VUE JS.
I have a form where I want to add multiple media.
So on click of "Add media" button i want to add "li" tag with respective html content in which i have on remove button too.
On click on remove button i want to delete the respective li.
What will be the best way to do this?
Here is what i have done so far
HTML:
<div class="col-md-10">
<button #click="addMediaRow()" class="btn btn-primary" :disabled="mediaRowCount >= 3" type="button">Add Media</button>
<br>
<br>
<ul style="list-style-type: none; padding: 0;" id="project_media_ul">
<li v-for="(row, index) in mediaRowArr">
<span v-html="row.template"></span>
</li>
</ul>
</div>
JS
In data i have declared variable
mediaRowLI: '<a v-on:click="openMediaFileInput"><i class="fa fa-camera fa-2x"></i> \n' +
' <span class="photospan">Add Photo </span></a>\n' +
' or Input Video URL here : <input type="text" class="form-control"\n' +
' placeholder="use embed URL, e.g. www.youtube.com/embed/EXa9ZeqRKl8"\n' +
' name="media_video_url" style=" width: 50%">\n' +
' \n' +
' <i class="fa fa-close"></i>\n' +
'\n' +
' <input multiple type="file" accept=\'image/x-png,image/jpeg\' name="media_images"\n' +
' style="visibility: hidden;">\n' +
''
Methods :
addMediaRow () {
this.mediaRowArr.push({
template: this.mediaRowLI
})
},
removeMediaRow (key) {
this.mediaRowArr.splice(key, 1)
},
Thanks in advance
Note that:
you cannot use v-html to compose template partials, because Vue is
not a string-based templating engine. Instead, components are
preferred as the fundamental unit for UI reuse and composition.
(source)
meaning html raw with v-on:click="removeMediaRow" doesn't work.
As the documentation says, you should create a component instead.
(jsfiddle example here)

How to link to another webpage using html/JS without keeping the filepath of the orginial page?

I want to go to stackoverflow.com for example when an ahref is clicked. The user types in the URLs so it could either have https:// at the start or not. Whenever the URL does have the https:// at the start, it works perfectly and links to the page, but whenever it doesn't. It keeps the file path, eg: file:///C:/Users/..../stackoverflow.com
How can I fix this?
https://codepen.io/anon/pen/rKZGdG
let results = document.getElementById('results');
// let url = "https://www.facebook.com"; WORKS
let name = "result";
let url = "facebook.com";
// this one leaves on the webite when Visit is clicked eg. file:///C:/User/../facebook.com
//I want the user to be able use to fb.com or http://www.fb.com, how can I do this?
results.innerHTML += '<div class="card bg-light p-3">'+
'<h3>'+name+
' <a class="btn btn-secondary" target="_blank" href="'+url+'">Visit</a> ' +
' <a onclick="delete(\''+url+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</h3>'
+ '</div>';
<div id="results">
</div>
Just add // before your url. So in your case, this should work:
results.innerHTML += '<div class="card bg-light p-3">'+
'<h3>'+name+
' <a class="btn btn-secondary" target="_blank" href="//'+url+'">Visit</a> ' +
' <a onclick="delete(\''+url+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</h3>'
+ '</div>';
This is because when you add a link without a protocol or a slash, it gets interpreted as a relative path.

Remove owl carousel item

I know that there are some associated questions about it, I tried all solutions and read all documentation, but w/o result.
I am initializing a Owl carousel :
HTML
In HTML, I have 2 items :
<div class="owl-carousel owl-theme all_diplomas">
<div class="item diploma-0">
<div class="content_diplomas">
<a data-fancybox="gallery" href="images/6.jpg"><i
class="material-icons">search</i></a>
<figure><img src="images/6.jpg" alt=""></figure>
</div>
<button class="waves-effect delete-diploma waves-blue diploma-0" type="button"><span>x</span> </button>
</div>
<div class="item">
<div class="add_diplomas">
<div class="item_add_diplomas">
<span class="plus_add">+</span>
<span class="txt_btn">Add diploma<br></span>
<input id="generateInputsForDiplomas">
</div>
</div>
</div>
</div>
JS :
$(".all_diplomas").owlCarousel({
loop: true,
margin: 15,
responsive: {
1000: {
items: 4
},
1200: {
items: 2
}
},
});
Next, after my script initialization :
$('input#generateInputsForDiplomas').on('click',function() {
var template = '<div class="item diploma-' + index + '"> <div class="content_diplomas"> <a class="diploma-' + index + '" data-fancybox="gallery" href="images/3.jpg"><i class="material-icons">search</i></a>' +
'<figure><img src="images/3.jpg" class="addedDiplomaInput diploma-' + index + '"alt=""></figure> </div> </div>'
+ '<button class="waves-effect delete-diploma waves-blue ' + classes + '" type="button"><span>x</span> </button>';
var newEl= $('.all_diplomas').trigger('add.owl.carousel', [template, 33]).trigger('refresh.owl.carousel');
});
Code above just adds a block of owl-item with one image and some id-s
and classes.
Then, it appends this template to position 33 and refreshes the
carousel
Them, each element has a delete button associated to owl-item class
$(document).on('click', 'button.delete-diploma',function() {
$(".all_diplomas").trigger('remove.owl.carousel', 33).trigger('refresh.owl.carousel');
});
That's the thing. When adding an element, from documentation, I am setting the position for this element explicitly - like 33. But when I am calling the button that is responsable to remove item with position 33, it deletes entire slider, or sometimes unexpected behavior.
The reason why I'm calling position explicitly, because I need to know each item's index, because when calling delete button, to know item with which position to delete. Documentation offers callbacks that has this information, but not for "add" event.
How can I lifehack that problem? I want to add n-items to carousel, and each this block with image to has it's own delete button. So, when calling this button, it will delete that element and refresh the Owl. I tried with pure jQuery to delete parents and so on... but Owl generates some other classes, and because of it, item is deleted, but empty spaces in slider remains.

Updating p in div with jQuery

I'm trying to update the text of a p element which has a .bus_latitude class.
So first, I locate the parent div which has a data-* attribute.
After retrieving the div, I try to locate his closest p element which has the class .bus_latitude, and set his text to some static content.
I have tried enoumerous ways, specially because jQuery has various methods to do so, but none of them worked.
So here I inject a div with has a data-id attr
this:
var div = $('<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 bus_card" data-id="'+bus.getKey()+'"><br/><br/>'+
'<div class="thumbnail">'+
' <div class="caption">'+
' <div class="col-lg-12">'+
' <div class="header">'+
' <h4 class = "line_name" style="text-align:center;color:'+line.child("colorNormal").val()+';"><strong>Linha '+line.getKey()+'</strong></h4>'+
' </div>'+
' </div>'+
' <div class="col-lg-12 well well-add-card">'+
' <h4 class="pull-left">Cartão:</h4>'+
' <h4 class="pull-right">'+bus.child('cardid').val()+'</h4>'+
' </div>'+
' <div class="col-lg-12 bus_information">'+
' <div style="padding-left:10px!important;" class="row">'+
' <p class="pull-left"><kbd>Latitude</kbd></p>'+
' <p class="pull-right bus_latitude">'+bus.child('lat').val()+'</p>'+
' </div>'+
' <div style="padding-left:10px!important;" class="row">'+
' <p class="pull-left"><kbd>Longitude</kbd></p>'+
' <p class="pull-right bus_longitude">'+bus.child('long').val()+'</p>'+
' </div>'+
' <div style="padding-left:10px!important;" class="row">'+
' <p class="pull-left"><kbd>Velocidade:</kbd></p>'+
' <p class="pull-right bus_velocity">35km/h</p>'+
' </div>'+
' <div style="padding-left:10px!important;white-space: nowrap; overflow:hidden;" class="row">'+
' <p class="pull-left"><kbd>Geo-localização:</kbd></p>'+
' <class = "bus_georeference">&nbsp&nbsp'+streetNameOfPosition+'</>'+
' </div>'+
' </div>'+
' <button type="button" class="btn '+(bus.child('state').val() === 1 ? 'btn-danger' : 'btn-default')+' btn-xs btn-update btn-add-card">Em Terminal</button>'+
' <button type="button" class="btn '+(bus.child('state').val() === 2 ? 'btn-danger' : 'btn-default')+' btn-xs btn-update btn-add-card">Em Andamento</button>'+
' <button type="button" class="btn '+(bus.child('state').val() === 3 ? 'btn-danger' : 'btn-default')+' btn-xs btn-update btn-add-card">Em Paragem</button>'+
' </div>'+
'</div>'+
'</div>').appendTo("#bus-cards-container");
So I have an event listener for a button to update the p element with some static content.
Here is where it isn't working:
function updateBusOnHTML(bus) {
alert(bus.getKey());
$("div[data-id='" + bus.getKey() +"'] .bus_information .bus_latitude").val("39.284035"); //this doesn't work, bus.getKey()
}
Both data-id are correct, even when the HTML is rendered, the div has the exact same id with the one that enters updateBusOnHTML().
So why doesn't it update the p text?
.val() is used to update the value of a form element like input. Use a method like .text() or .html() instead.
Another recommendation: use console.log() instead of alert().

Categories

Resources