Add new line using jQuery concat - javascript

Through ajax response I'm passing array data from controller to blade.
On Ajax success I'm looping through array with 2 elements and concatenating string to display later on in my bootstrap popover.
success: function (data) {
var content = "";
var num = 1;
for (var i = 0; i < data.length; i++) {
content = content.concat(num + "." + " " + data[i]);
num++;
}
$("#content").popover({content: content});
}
Result:
I would like to add new line, so that each item or "artikel" would be displayed in new line e.g. :
1.Artikel...
2.Artikel...
I tried to add "\n" (as below) or html break but nothing works, it only appends as string.
content = content.concat(num + "." + " " + data[i] + "\n");

Use this:
content.concat(num + "." + " " + data[i] + "<br/>");
And this:
$("#content").popover({ html:true, content: content });

Related

How to modify javascript to have html result instead of show out the html code in a comment system?

Currently,
when i input test,
the comment system directly show my typing, "test"
Modify to,
I would like the modify the javascript code that when i input test,
it convert to html result "test" (a hyperlink to "#").
How can i modify following code? Many thanks!
function fetchComments(leaveRequestId) {
$('#existingComments').html(lang_Loading);
params = 'leaveRequestId=' + leaveRequestId;
$.ajax({
type: 'GET',
url: getCommentsUrl,
data: params,
dataType: 'json',
success: function(data) {
var count = data.length;
var html = '';
var rows = 0;
$('#existingComments').html('');
if (count > 0) {
html = "<table class='table'><tr><th>" + lang_Date + "</th><th>" + lang_Time + "</th><th>" + lang_Author + "</th><th>" + lang_Comment + "</th></tr>";
for (var i = 0; i < count; i++) {
var css = "odd";
rows++;
if (rows % 2) {
css = "even";
}
var comment = $('<div/>').text(data[i]['comments']).html();
html = html + '<tr class="' + css + '"><td>' + data[i]['date'] + '</td><td>' + data[i]['time'] + '</td><td>' +
data[i]['author'] + '</td><td>' + comment + '</td></tr>';
}
html = html + '</table>';
} else {
}
$('#existingComments').append(html);
}
});
}
<div id="existingComments">
<span><?php echo __('Loading') . '...';?></span>
</div>
var comment = $('<div/>').text(data[i]['comments']).html();
You're explicitly escaping the data from the Ajax request so that it shows up as text and isn't treated as HTML source code.
If you don't want to do that, then just don't do it!
(Do be careful not to expose yourself to stored XSS attacks though)
$('#existingComments').html(html);

How to send a javascript array to php [duplicate]

This question already has answers here:
How to pass data from Javascript to PHP and vice versa? [duplicate]
(7 answers)
Closed 4 years ago.
I have an array named "seat" in my javascript file.It is used to store the seat numbers when a user clicks on a seat in a theater layout.In my function,I've used a window alert to show the user his selected seats,and when he clicks OK button,I want to send these booked seats(values in my array) to a php file named "confirm".
Here is the javascript function.
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved!');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
$_POST('confirm.php', {seat: seat})
})
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
And this is my php code.
$seat = "";
if(isset($_POST['seat']))
{
$seat = $_POST["seat"];
print_r($seat);
}
When this is executed I get the window alert,but the values stored in the array does not pass to the php file.Is there something wrong with this code?Please help!I'm stuck here!!!
$_POST isn't a built-in method, and jQuery doesn't provide a method like that either-- you can't just "set" the values into the $_POST array like this.
To post using jQuery, you would do something like the following, including a handler for data returning from the server (if you have any):
$.post("confirm.php", { seat: seat})
.done(function(data){
alert('Received data from server: ' + data);
});
You need to send the data to your PHP script, this does nothing in your JS code:
$_POST('confirm.php', {seat: seat})
use something like jQuery post method or vanilla JS XMLHttpRequest

Don't write comma after last element in for loop

I have function that gets data from a database and displays it in the view:
function GetUsers() {
let url = "/Home/GetUsers";
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) {
console.dir(data);
for (var i = 0; i < data.length; ++i) {
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName + "," + '</b>');
}
}
});
}
It displays it with comma, but after the last Username+RoleName it adds a
comma too. As I understood I need to get last iteration of for loop? How I can fix this problem?
I usually make a little trick for this cases:
var separator = "";
for (var i = 0; i < data.length; ++i) {
$('#taskresult3').append(separator + '<b>' + data[i].UserName + "-" + data[i].RoleName + '</b>');
separator = ",";
}
Simply check if the current element is the last element and if so, don't add the comma:
$('#taskresult3').append('<b>'+ data[i].UserName +"-"+ data[i].RoleName + (i === data.length - 1 ? "" : ",")+'</b>');
Dont add comma for the last element.
for (var i = 0; i < data.length; ++i) {
if (i === data.length - 1)
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName '</b>');
else
$('#taskresult3').append('<b>' + data[i].UserName + "-" + data[i].RoleName + "," + '</b>');
}
There is one more approach using .join() on arrays
var _html = [];
for (var i = 0; i < data.length; ++i) {
var _inhtml = '<b>' + data[i].UserName + "-" + data[i].RoleName+'</b>';
_html.push(_inhtml);
}
$('#taskresult3').append(_inhtml.join(","));
With this you can cut down the overhead of manipulating DOM multiple times.
You could use map and join to solve this, instead of using a loop.
$('#taskresult3').append('<b>' + data.map(item => item.UserName + "-" + item.RoleName).join(',</b><b>') + '</b>')
map would convert the array, to an array of item.UserName + "-" + item.RoleName, this array then would be joined together using ,</b><b> and the last part that is then missing is the first <b> and the last </b>
You can avoid the comma and improve your logic by building the HTML in an array, then using join() to display it, like this:
success: function(data) {
var html = data.map(function(item) {
return data[i].UserName + ' - ' + data[i].RoleName;
});
$('#taskresult3').append(html.join(',');
}
Also, keep in mind the semantic use of the <b> tag:
However, you should not use <b> for styling text; instead, you should use the CSS font-weight property to create boldface text.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b
I'd suggest placing the HTML you append within a container that has font-weight: bold applied to it through CSS.

Trying to get this string to appear in a paragraph

Trying to get this string I have in JavaScript to appear in a paragraph in my HTML page by mousing over another paragraph.
function showInfo()
{
for (i = 0; i < object2; i = i + 1)
{
var myParagraph = "Name of Business: " + info.insurance[i].name + "\nState: " + info.insurance[i].state + "\nDiscount: " + info.insurance[i].discount + "\n" + "(" + i + 1 + "of" + object2 + ")"
}
}
myDiscount.addEventListener("mouseover", showInfo, false);
myDiscount.addEventListener("mouseout", showInfo, false);
<p id="discount">Show me the discounts!</p>
<p id="myP"></p>
If you want to show the next element of the info.insurance array each time you mouse over the paragraph, you shouldn't be using a for loop. That will do it all at once, not once for each mouseover. You need to put the counter in a global variable, and just increment it each time you call the function.
Yuo show it by assigning it to the innerHTML of the paragraph. You also need to use <br> rather than \n to make newlines (unless the style of the paragraph is pre).
var insurance_counter = 0;
function showInfo() {
var myParagraph = "Name of Business: " + info.insurance[insurance_counter].name + "<br>State: " + info.insurance[insurance_counter].state + "<br>Discount: " + info.insurance[insurance_counter].discount + "<br>(" + (insurance_counter + 1) + "of" + object2 + ")";
document.getElementById("myP").innerHTML = myParagraph;
insurance_counter++;
if (insurance_counter >= object2) { // wrap around when limit reached
insurance_counter = 0;
}
}

remove array using jquery

I have created nestled arrays, which I then append to a div. When i click the button with id "name", a movie with title is stored in an array $titelBetyg, which is later stored in another array $films. Whenever i create a new $titelBetyg, i want to remove the previous $films from my div, before replacing it with the new one. How do I do this?
Javascript
$(document).ready(function(){
var $films = [];
$('#name').keyup(function(){
$('#name').css('background-color', 'white');
});
$('#options').change(function(){
$('#options').css('background-color', 'white');
});
$("#button").click(function(){
var $titelBetyg = [];
var $titel = $('#name').val();
var $betyg = $('#options').val();
if($titel == ""){
$('#name').css('background-color', 'red');
alert("Fail");
}
else if($betyg == "0"){
$('#options').css('background-color', 'red');
alert("Fail");
}
else{
$titelBetyg.push($titel);
$titelBetyg.push($betyg);
$films.push($titelBetyg);
// here is where i need to remove it before appending the new one
$('#rightbar').append("<ul>");
for(i=0; i<$films.length; i++){
$('#rightbar').append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>" + "<br>");
}
$('#rightbar').append("</ul>");
}
});
$('#stigande').click(function(a,b){
});
$('#fallande').click(function(){
});
});
Use .empty() like this (and append to the <ul> instead of something else):
var $ul = $("<ul>");
for (var i=0; i<$films.length; i++) {
$ul.append("<li>" + $films[i][0] + " " + $films[i][1] + "</li><br>");
}
$('#rightbar').empty().append($ul);
Btw, it might be easier to only append the new one instead of emptying and rebuilding the whole thing:
$('#rightbar ul').append("<li>" + $titel + " " + $betyg + "</li><br>");
To remove only the list contents (and nothing else) from the #rightbar, you could use this:
var $ul = $('#rightbar ul').empty();
if (!$ul.length) // if nonexistent…
$ul = $("<ul>").appendTo('#rightbar'); // create new one
for (var i=0; i<$films.length; i++)
$ul.append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>");
document.getElementById('rightbar').innerHTML = '';
That way rightbar is totally empty.
You only require to remove the content of the container. So, use the .empty() function
$('#rightbar').empty().append("<ul>"); //It will empty the content and then append
for(i=0; i<$films.length; i++){
$('#rightbar').append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>" + "<br>");
}
$('#rightbar').append("</ul>");

Categories

Resources