Setting the Input Value attribute to a variable with space. - javascript

I am trying to set the value of a input button to a string variable.i.e"A Guide to the School Bus"; But when the HTML loads up only the first word comes up in the button. My code is given below. Thanks for the help.
var title="A Guide to the School Bus";
var htmlString= "<div class="+title+ ">"+"<input type="+"button "+"value="+title+" onclick=loadBook()>"+"</div>";
$(htmlString).appendTo(attachPoint);
And the attachpoint is a reference in the HTML that i got using the following.
var attachpoint=document.querySelector('.buttonAttachPoint');

The problem is because you're not putting quotes around the attribute values. Try this:
var htmlString= '<div class="'+title+'"><input type="button" value="'+title+'" onclick="loadBook()"></div>';
You can either escape all the " in your string or, like I have done, just switch between ' and ". " will show up as a normal character and ' is used to mark the start and finish of strings.
As a side point you probably wouldn't want to put the variable title as the class on the div as it would add each separate word as a class, so in your example the div would have 6 classes added to it.

Related

concatenate a variable to a html string in javaScript

Please be gentle with me, it is my first time uploading a question to stack overflow, and since I am rather new in programming I might be a bit vague in the terms.
My problem is that I have a function that places some markers on a map, this happens automatically when I load the site, these markers are different and contain different "trophies", that I have placed in a pop-up locked to the marker. However I want the program to be able to collect the trophies, therefore I would like to call a function with the specific trophy as my parameter in my javaScript file when I click a button in my pop up. HTML.
So far it looks like this:
function createMarker(coords, trophy) {
var id
// check if array is empty and set id to 0 if it is
if (markers.length < 1) id = 0
// else make id based on array length
else id = markers[markers.length - 1]._id + 1
// custom popup content with HTML that can be styled
var popupContent =
'<div id= "divTrophy">'+
'<img src=' + trophy +'></img>' +
'<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+
'<button onclick="closePopUp()">Close pop up</button>'+
'</div>'
'<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+
The problem is in this line where I am for some reason not allowed to concat this way, which confuses me because it works fine in the line above in the <img>.
I really hope someone can help me, create my little treasure hunt around DK.
Try using string interpolation. Something like this.
`your_html_string ${your_dynamic_value} your_html_string`
You can find more info on interpolation here.
How to interpolate variables in strings in JavaScript, without concatenation?
Try escaping them it should work, example
'<button onClick="trophyCollection(\''+trophy+'\')">Collect trophy</button>'+
You can insert your entire HTML inside of a backtick string and interpolate values like this:
let popupContent =
`<div id= "divTrophy">
<img src=${trophy}></img>
<button onClick="trophyCollection(${trophy})">Collect trophy</button>
<button onclick="closePopUp()">Close pop up</button>
</div>`
As suggested you can try template literals:
var popupContent = `<div id="divTrophy">
<img src="${trophy}"/>
<button onClick="trophyCollection('${trophy}')">Collect trophy</button>
<button onclick="closePopUp()">Close pop up</button>
</div>`
Do note that as trophy is a string you still need to wrap it in quotes.

Appending the javascript onclick event to anchor tag

Im trying to append the onclick event to my Phonegap Application. Where it will link to external browser.
My Code:
pair +='<div class="card_background" style="background-image: url("http://placehold.it/600x200");" valign="bottom" class="card-header color-white no-border"><div class="card_overlay"></div><div class="animated_background"></div><h3 class="card-title">'+ results.rows.item(i).title +'</h3></div><div class="card-content"><div class="card-content-inner"><p class="color-gray event_details">Event Location: <strong>'+ results.rows.item(i).eventlocation +'</strong></p><p class="color-gray event_details">Event Date: <strong>'+ date + " " + month + " " + year +'</strong></p>Google<br/></div></div>';
inside loop,
Later I append it to div
Im trying to add :
Google
It gives me error
Thanx in advance
I've simplified your code somewhat. Consider the following:
var pair = '';
var eventOrganiserLink = '[EVENT ORGANISER LINK]';
pair += 'Google';
This would generate the following:
Google
The onclick attribute opens with double quote ("), which means it will look for the first double quote after that to close it. That's right after window.open( meaning that part is the only thing that will be set as the onclick attribute. See how the colors in the onclick attribute in the code box here at StackOverflow don't really match up?
It is a little tricky because we're mixing quotes (setting the pair variable) and double quotes (as text inside that variable, which will be used as html later on - so it needs to be valid).
You can use single quotes for the first window.open parameter and escape them in the assignment to your pair variable, like so:
var pair = '';
var eventOrganiserLink = '[EVENT ORGANISER LINK]';
pair += 'Google';
This would yield:
Google
Note the single quotes around [EVENT ORGANISER LINK]. Also note the colors now match up.

Removing spaces between lines in JavaScript

I'm just learning JavaScript, and I've come up with the following page that "draws" a guitar fretboard by creating a 6X16 grid of images (the first column is the set of "open notes" on the very left hand side of the image grid). The page is here.
Each of the six rows represents a string on the guitar so, six strings, six rows. But what I can't figure out is how to make the rows butt up right next to each other, with no whitespace between the top of one row and the bottom of the next. So, what I get is this:
But what I want is this:
The way that the JavaScript works is to run through a loop that is 16 items long - one "open string" image, and 15 "fretted note" images, and at the end of the loop it generates a <br/>tag. These strings are inserted into an InnerHTML value of a <p> element, and the grid of images gets drawn. Here is the line of code that generates, as an example, the fretted note image:
for(frets=0; frets < 17; frets++){
GuitarNeckImg.innerHTML = GuitarNeckImg.innerHTML + "<img title=" + allNotes[frets + 1] + " src=images\\" + allFretImages[frets + 1] + ">";
continue;
}
What I don't understand is:
What CSS attribute/value pairs do I need to enter to get the images
to not have any space between them above and below,and
How do I write the JavaScript code to add those CSS attribute/value pairs to the tag in my code?
Add'l information:
I have tried, as an example, to write the following code in my JS file:
GuitarNeckImg.innerHTML = GuitarNeckImg.innerHTML + "<img title=" + allNotes[frets + 1] + " style=padding:0px; margin:0px;" + " src=images\\" + allFretImages[frets + 1] + ">";
But this produces the following HTML output:
<img title="F.Esharp.Gbb" style="padding: 0px;" src="images\F.jpg" margin:0px;="">
So the first problem is specifically around JS syntax and how I need to craft the code statement to generate multiple attribute/value pairs for the style tag, and the second is which CSS tags I should use to get my desired results.
Thanks in advance, and please feel free to let me know what additional information I can provide.
An appropriate line-height value, such as 0.70, should do exactly what you want.
Try this...
//We define the text variable that needs to be cleansed of line breaks.
Var someText = "Here's some text.\n It has some line breaks that will be removed \r using Javascript.\r\n";
//This javascript code removes all 3 types of line breaks
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
Best of luck...

JavaScript is taking only the first word in a sentence

am stuck over a small issue here.
I want to set the value of a input using JavaScript but jQuery is not displaying the full sentence.
var name = "Richard Keep";
But when I use try to do this
$('input#nameid').val(name)
to this input
<input type="text" id="nameid">
the value is set to Richard alone instead of Richard Keep.
How do I make the jQuery echo the entire string and not just the first word in a string? Thanks
EDIT:
<td id="To_be_collected_port" onclick="requestPopup()" class="tr-selected">
<div class="pop-td To_be_collected_port">
</div>
this is the content am fetching
</td>
This will display this only.
var str = $('#To_be_collected_port').text();
then
$('.xyz').html("<input type=\"text\" name=\"text\" id=\"selected-service-text\" value="+str+">");
You're missing escaped double quotes around the value attribute:
value="+str+"
should be:
value=\""+str+"\"
Fiddle - works now
Explanation of why it was displaying "this"
This means your input tag is effectively composing to this:
<input type="text" ... value=this is the content am fetching>
value = "this"
is, the, content, am, fetching = attributes without any value
That is odd behaviour. Here are a few things you can try
1) add a console log just before putting the value in the field. if it does not properly show the entire name then you probably have some code manipulating the variable.
console.log(name);
$('input#nameid').val(name);
2) stupid suggestion but is your input field visually not to small? Maybe it added the entire name but you just don't see it.
3) use an onchange event on the field to check if something was changed after you updated the input field.

How do I get the proper quotations around the return and end of on click statement?

I've been having some troubles with this javascript code and I am looking for a suggestion. I am programtically adding a row to a table with javascript but I need to add an onclick event for each row. Problem is when the row adds to the page the quotations and upper / lower case has been all converted to lower case causing issues on the web page.
here is the current code
var row = $("<tr id=" + id + " onclick=return SelectRow('Racks','" + id + "') >");
if someone could explain how to get it so that the ending result looked like this
<tr id="r1" onclick="return SelectRow('Racks','r1')">
</tr>
I'm guessing it has to do with escape characters and the order they are being placed but I can't seem to figure it out.
Don't try to generate JavaScript inside HTML inside JavaScript. It is a right pain.
Don't write 90s style code. Stop using onclick attributes. Use event handlers bound with JavaScript.
function row_click_handler(event) {
return SelectRow("Racks", this.id);
}
var row = $("<tr />").attr("id", id).on("click", row_click_handler);

Categories

Resources