Passing HTML string to JavaScript function - javascript

I have a value that I'm currently accessing and passing to a JavaScript function through an onclick.
Text
An example value that I'd receive from the getText method is shown below.
<h1>My Header</h1><br />My text
This value is then passed to my openTextWindow method.
function openTextWindow(inText) {
myWindow = window.open('','','width=500, height=300');
myWindow.document.write(inText);
myWindow.focus();
}
For some reason, the value stored in inText doesn't match the string with HTML tags that I showed above. It ends up looking like this.
"<lt/>h1<gt/>My Header<lt/>/h1<gt/><lt/>br /<gt/>My text
When inText is written to myWindow, I want that new window to render with the text My Header within a styled header and My text on a line below that. I've tried replacing and escaping characters with no luck. Any ideas on how to fix this or a better way to accomplish what I'm trying to do? Thanks!

You can stash your HTML in a hidden DIV or textarea, then grab that from your function instead of trying to pass it inline.
Text
<div id="DIV1" style="display:none"><%=myVar.varDefinition.getText()%></div>
JS:
function openTextWindow(divName) {
var inText = document.getElemenyById(divName).innerHTML;
myWindow = window.open('','','width=500, height=300');
myWindow.document.write(inText);
myWindow.focus();
}

Related

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

get the html of element itself using jquery .html()

How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/

How do get contents of a p element one at a time

Using jQuery, I need to parse the contents of each <p> tag individually and then replace the text with the new text.
The code at the moment looks like:
str = $('p').text();
str = str.replace('yadayada','yada');
$('p').text(str);
This is currently getting the contents of all the <p> tags, concatenating them then replacing the massive block of text into each <p> which is close but not quite what I'd like it to do.
Is there a way to get the contents of each <p> block one at a time and replacing it with only it's contents? I do not know what ids or classes are being applied to them hence the need to use the generic tag.
Any help is much appreciated! :)
Use the text(fn)
A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
$('p').text(function(_ text){
return text.replace('yadayada','yada');
});
Use the text() version that accepts a callback as the second argument and return the replaced content from the callback
$('p').text(function(i, str) {
return str.replace('yadayada', 'yada');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>yadayada-1</p>
<p>yadayada-2</p>
<p>yadayada-3</p>
<p>4</p>
You can use .each method on the colletion:
$('p').each(function (pEl) {
var text = pEl.textContent;
});

javascript alert value from a tag

I have on a page a tag links generated from a database with an id. What im trying to do is in an alert box display the text inside the a tag.
Ive tried to have a look to see if I can see a previous question, which I have come up with the following but all I get in the alert box is object HTMLCollection
I have the following code:
<a id="bet" onclick="addSlip();" class="btn btn-round" style="text-align: left;">'.$home->one.' <span>'.$home->two.'</span></a>
and...
function addSlip() {
document.getElementById('bet').innerHTML=bet;
alert(bet);
}
Thanks for any constructive answers
You should do the following
function addSlip() {
var bet = document.getElementById('bet').textContent;
alert(bet);
}
the rest as it is.
or using jquery
function addSlip() {
var bet = $("#bet").text()
alert(bet);
}
The main problem of your program was that the alerted variable had no value. (undefined)
The way you wrote it if the variable bet had a value would change the innerHTML of the of the a tag to that value.
Now to the using innerHTML or textContent part. As mentioned here in terms of performance the textContent is better
You need to reverse the variable assignment of bet:
function addSlip() {
var bet = $("#bet").text();// or $("#bet").html() if you want the HTML alerted
alert(bet);
}
In your case alert will give you the HTML Object Collection only.
When you have an element with id, then you can access them anywhere in javascript
e.g. for the following HTML
<div id="bet">This is a div </div>
in JS
alert(bet);
will give you the html object collection.
Solution for you is update your code
function addSlip() {
document.getElementById('bet').innerHTML=bet;
alert(bet);
}
to
function addSlip() {
alert( document.getElementById('bet').innerHTML);
}
If there is some html elements also in the div you can update the function with
function addSlip() {
alert(document.getElementById('bet').textContent);
}

Can jQuery or Javascript change elements within textareas?

My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/

Categories

Resources