Javascript a new line in a string - javascript

I have a string like so:
var customerInfo = data[0].Customer_Name + " " + data[0].Customer_LName + "\r\n" + data[0].Phone + "\r\n" + data[0].Email;
and I am trying to add new lines with \r\n but its not working, everything is on the same line. Please Help.

To print the javascript variable in an HTML page, you should use the <br /> tag to create a new line, instead \r\n.
var customerInfo = data[0].Customer_Name + " " + data[0].Customer_LName + "<br />" + data[0].Phone + "<br />" + data[0].Email;

Related

Line break issue in javascript

if I use a paragraph element the line doesn't break, but if I use a textarea element the line breaks. why is this?
html:
<div id="requirement_7">
<h3> Requirement #7</h3>
<p>Press "Show Array" button to see an array created with JSON.<br>
It will show A state, the capital and quailty rating.</p>
<button type="button" id="array_button" onclick="JSONArray()">Show Array</button>
<p id="array_text"></p>
</div>
javascript:
function JSONArray(){
var text = '{"stateCapital":['+
'{"stateName":"Texas", "stateCapital":"Austin", "qualityRating":"10"},'+
'{"stateName":"Virginia", "stateCapital":"Richmond", "qualityRating":"7"},'+
'{"stateName":"California", "stateCapital":"Sacremento", "qualityRating":"7"},'+
'{"stateName":"Coloroado", "stateCapital":"Denver", "qualityRating":"10"} ]}';
var obj = JSON.parse(text);
document.getElementById("array_text").innerHTML =
obj.stateCapital[0].stateName + " " + obj.stateCapital[0].stateCapital + " "
+ obj.stateCapital[0].qualityRating + "\n" +
obj.stateCapital[1].stateName + " " + obj.stateCapital[1].stateCapital + " "
+ obj.stateCapital[1].qualityRating + "\n" +
obj.stateCapital[2].stateName + " " + obj.stateCapital[2].stateCapital + " "
+ obj.stateCapital[2].qualityRating + "\n" +
obj.stateCapital[3].stateName + " " + obj.stateCapital[3].stateCapital + " "
+ obj.stateCapital[3].qualityRating;
}
I have "\n" in my script to create the line break. I'm confused why it works in one element and not the other?
you need to replace "\n" with "<br>" since you are using .innerhtml it recognizes it as HTML and not JavaScript.
Codepen http://codepen.io/noobskie/pen/ojjeKZ?editors=101
You must use <br> to make a line break in paragraph.
If you do not want to change from '\n' to <br> you can use <pre> tag instead of <p> tag.
refer doc:
http://www.w3schools.com/html/html_paragraphs.asp
http://www.w3schools.com/tags/tag_pre.asp

Possible to add a loop while appending to the DOM?

I'm appending some information to the DOM, but realized that some of the information I need is nested within an object. When I do the below bit of code, the part within the loop returns as undefined. Is there a way to iterate over and pull out this information so that I can append it to my page:
function placeOnPage(allStopsWithRoutes){
allStopsWithRoutes.forEach(function(stop){
$('#stops').append("Stop: " + stop.crossStreets + "<br>" +
// LOOP HERE
stop.routes.forEach(function(route){
"Bus Name: " + busName + "<br>" +
"Stops Away: " + stopsAway + "<br>" +
"Destination: " + destination + "<p>"
});
// END LOOP
);
});
}
I don't think strings can be concatenated that way. Change your approach to concatenate before hand and store it in a variable. Then append the variable
function placeOnPage(allStopsWithRoutes) {
allStopsWithRoutes.forEach(function(stop) {
var concatenatedStr = '';
stop.routes.forEach(function(route) {
concatenatedStr += ("Bus Name: " + busName + "<br>" +
"Stops Away: " + stopsAway + "<br>" +
"Destination: " + destination + "<p>");
});
$('#stops').append("Stop: " + stop.crossStreets + "<br>" + concatenatedStr);
});
}

Change color of words in a string that's been returned from a search query

I'm trying to figure out how to change the color of specific words in a string thats been returned from a search query. I have passed down a collection and its search terms from the server via SignalR and ideally looking to replace the words with some HTML. Any Pointers will be greatly appreciated.
var searchReturnHTML = "";
//tickets is the collection returned
$.each(tickets, function ()
{
var tickets = this;
//Search terms used in the query
var data = tickets.SearchTerms;
//Split the search terms
var arr = data.toString().split(',');
//Property in the collection
var description = tickets.description;
//Loop through the search term collection
$.each(arr, function (k,v)
{
//Apply color change, if a search term is matched in the return property string
var re = new RegExp(v, "g");
description = description.replace(re, "<span style='color:red;'>" + v + "</span>");
});
//Return HTML
searchReturnHTML += "<div class='search-return-item'>" +
"<p>#" + tickets.ticketID + "</p>" +
"<p>" + description + "</p>" +
"<p>" + "From: " + tickets.name + "</p>" +
"<p><strong>" + tickets.SearchTerms + "</strong></p>" +
"</div>"
});
At the minute the description returns as NaN. I'm not entirely sure why. Any Ideas? This works ok without the string manipulation.
Regards,
Tez
Oh dear slightly embarrassed! I actually wrote the question by hand and then went back to my code in VS and realised I missed something fundamental to get it to work.
Basically I did not have reference to the "description" variable
searchReturnHTML += "<div class='search-return-item'>" +
"<p>#" + tickets.ticketID + "</p>" +
"<p>" + **description** + "</p>" +
"<p>" + "From: " + tickets.name + "</p>" +
"<p><strong>" + tickets.SearchTerms + "</strong></p>" +
"</div>"
Apologies for wasting your time! Complete rookie mistake.
Regards,

Javascript method argument escape

The below span tag containing an onclick event is not working
var test="<span onClick="gotoNode(\'' + result.name + '\',\'' + result.xaxis + '\',\'' + result.yaxis + '\',\'' + result.detail + '\',\'' + result.status + '\')" />"
the above escaped string has some problems with the method call.
How can I fix it?
If you're creating this in JavaScript to create an element, then the first single-quote needs to be escaped.
function gotoNode(name, xaxis, yaxis, detail, status) {
alert("name = " + name + "\r\nxaxis = " + xaxis + "\r\nyaxis = " + yaxis + "\r\ndetail = " + detail + "\r\nstatus = " + status);
}
var result = { name: "name", xaxis: "xaxis", yaxis: "yaxis", detail: "detail", status: "status" };
var htmlText = '<input value="Button" type="button" onclick="gotoNode(\'' + result.name + '\',\'' + result.xaxis + '\',\'' + result.yaxis + '\',\'' + result.detail + '\',\'' + result.status + '\')" />';
$("#lonely").append(htmlText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lonely"></div>
Generally speaking, whatever quote type you begin with (out of ' or "), you need to escape the same type that you want to use within the string and not escape the same type to terminate the string. You can leave the other type without escapes.
For your edited version, this should work if you want those result variables to be replaced with their values.
var test = "<span onclick=\"gotoNode('" + result.name + "','" + result.xaxis + "','" + result.yaxis + "','" + result.detail + "','" + result.status + "')\" />";
Do you use php to generate the output?
Then you should try
echo "<input type=\"button\" onClick=\"gotoNode(\" + result.name + \",\" +
result.xaxis + \",\" + result.yaxis + \",\" + result.detail + \",\" +
result.status + \")\" />";

onclick event and json data not meshing together

I've got a silly error which I cant seem to fix some how. I'm simply looking to do the following:
onclick="CreatePro('x','y','z')"
I basically want to pass text to the CreatePro function. Now my values of x,y and z are json data. As such here is what I am using for the javascript:
var Provision = "'" + data[i].ProvisionID + "'";
var Title = "'" + data[i].Title + "'";
var Author = "'" + data[i].Author + "'";
var Edition = "'" + data[i].Edition + "'";
var Publisher = "'" + data[i].Publisher+ "'";
var ISBN = "'" + data[i].ISBN + "'";
var UserID = "'" +data[i].UserID + "'";
var Price = "'" + data[i].Price+ "'";
var Condition = "'" +data[i].Condition +"'";
Row = Row + "<td><input type='button' onclick='CreatePro(" + Provision + "," + Title+ "," + Author + "," + Edition + "," + Publisher +"," + ISBN + ","+ UserID + ","+ Price + "," + Condition + ")' value='Create'></td></tr>";
console.log(Row);
Now when I use console.log I get the following:
<td><input type='button' onclick='CreatePro('19','dfjeryj','ertj','0','tj','0000000000000','4','0','0')' value='Create'></td>
But when I inspect the element I have :
<input type="button" onclick="CreatePro(" 19','dfjeryj','ertj','0','tj','0000000000000','4','0','0')'="" value="Create">
The problem is suspect is the " on the above line. But I dont know why this is happening? As from the console log. My quotes seem to match up. So I'm not sure why the browser is mixing them up? Perhaps I've gone wrong somewhere? (Frankly I can;t see the error). Every time I click the create button the event doesn't call my CreatePro function. I'm really not sure what I'm doing wrong or perhaps a better way of doing what I'm doing
You have got your quotes wrong. It should be:
Row = Row + "<td><input type='button' onclick=\"CreatePro('" + Provision + "','" + Title+ "','" + Author + "','" + Edition + "','" + Publisher +"','" + ISBN + "','"+ UserID + "','"+ Price + "','" + Condition + "')\" value='Create'></td></tr>";

Categories