Weird Behaviour in jQuery's html method - javascript

Any good reason why $("p").html(0) makes all paragraphs empty as opposed to contain the character '0'?
Instead of assuming I found a bug in jQuery, it's probably a misunderstanding on my part.

jQuery only accepts a string as an argument for the val parameter of the html() method. If you pass a number like you are it will call the html() method override that sets the contents of the element but the value of the argument will end up being null or an empty string.
Try this:
$("p").html((0).toString())
Relevant documentation

I guess that at some point, it checks if (newContent == false), and doesn't continue with adding any content? I tried looking at the source, but got a bit lost...
I also guess that this would not be counted as a bug, since the function calls for a string, and if "0" is passed (as a string), it works as expected.
A workaround would be to do this:
var myNum = 0;
$('p').html('' + myNum);

The code performing the html call was within someone else's plugin and rather than modify it, making upgrading it tedious, I just wrote the following tiny plugin that modifies the html method to do as spoon16 recommended.
(function($) {
var oldHtml = $.fn.html;
$.fn.html = function (content) {
oldHtml.apply(this, [content.toString()]);
}
})(jQuery);
It's a little bit of a hack, but it's working for me and doesn't require me to modify the Plugin I'm using.
I just thought someone else might like to see this.

Try using text() instead html().

I geuss you missed part of how jQuery works,
$('p')
returns all paragraphs and the html( val ) function:
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
http://docs.jquery.com/Attributes/html#val
So if you just want to set the contents for the first p use
$("P").eq(0).html( 'something' );
or to get the html:
$("P").eq(0).html();
http://docs.jquery.com/Core/eq#position
more on jQuery selectors here:
http://docs.jquery.com/Selectors

Related

Copy value from one text field to another when button clicked

I am trying to get one field to copy over to another field when a div is clicked on, and the code that I have currently is not working. It's showing '0' in field1, even though field2 is set to 1 by default.
$(document).on('click', '#button', function() {
$('#textfield1').val === "document.getElementById('#textfield2').value";
Try with:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val())
});
You're using an odd mix of JS and jQuery here.
Your main issue is that val() is a method, not a property. Therefore your code should look something like this:
$(document).on('click', '#button', function() {
$('#textfield1').val($('#textfield2').val());
});
I'd strongly suggest you familiarise yourself with the jQuery documentation, specifically val() in this case.
It's showing '0' in field1, even though field2 is set to 1 by default.
You were assigning a string to $('#textfield1').val method which is why your code was not having any effect on textfield1's value.
Make it
$(document).on('click', '#button', function() {
$('#textfield1').val( $('#textfield2').val()); //use jquery val method
}
Generally speaking, JQuery offers only functions, and not properties (as #Craicerjack stated), hence remove that === and pass the new value as an argument, as follows:
$('#textfield1').val("yourText");
Also, you're passing a CSS selector rather than just an element ID to the Document.prototype.getElementById() function. Remove that # qualifier!
Moreover, you shoudln't be using a stringified JavaScript expression as a value, otherwise you'll get that exact JS expression as the input value. Rather, don't put those quotes around the expression, so that the interpreter will be evaluating it. Below is some working code.
$('#textfield1').val(document.getElementById('textfield2').value);
However, as #Rory McCrossan pointed out, you're using an odd mix of plain DOM and JQuery, and that makes no sense. It would be more consistent to also read the value of the other text field using JQuery, as follows:
$('#textfield1').val($('#textfield2').val());
Alternatively, you may do not need JQuery and opt for the standard DOM interfaces like in the example below:
document.getElementById('textfield1').value = document.getElementById('textfield2').value;

Using variables with jQuery's replaceWith() method

Ok this one seems pretty simple (and it probably is). I am trying to use jQuery's replace with method but I don't feel like putting all of the html that will be replacing the html on the page into the method itself (its like 60 lines of HTML). So I want to put the html that will be the replacement in a variable named qOneSmall like so
var qOneSmall = qOneSmall.html('..........all the html');
but when I try this I get this error back
Uncaught SyntaxError: Unexpected token ILLEGAL
I don't see any reserved words in there..? Any help would be appreciated.
I think the solution is to only grab the element on the page you're interested in. You say you have like 60 lines. If you know exactly what you want to replace..place just that text in a div with an id='mySpecialText'. Then use jQuery to find and replace just that.
var replacementText = "....all the HTML";
$("#mySpecialText").text(replacementText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mySpecialText">Foo</div>
If you're only looking to replace text then jaj.laney's .text() approach can be used. However, that will not render the string as HTML.
The reason the way you're using .html() is likely illegal is that qSmallOne is not a JQuery object. The method cannot be performed on arbitrary variables. You can set the HTML string to a variable and pass that string to the .html() function like this:
var htmlstring = '<em>emphasis</em> and <strong>strong</strong>';
$('#target').html(htmlstring);
To see the difference between using .html() and .text() you can check out this short fiddle.
Edit after seeing the HTML
So there is a lot going on here. I'm just going to group these things into a list of issues
The HTML Strings
So I actually learned something here. Using the carriage return and tab keys in the HTML string is breaking the string. The illegal-ness is coming from the fact the string is never properly terminated since it thinks it ends at the first line. Strip out the white space in your strings and they're perfectly valid.
Variable Names
Minor thing, you've got a typo in qSmallOne. Be sure to check your spelling especially when working with these giant variables. A little diligence up front will save a bunch of headache later.
Selecting the Right Target
Your targets for the change in content are IDs that are in the strings in your variables and not in the actual DOM. While it looks like you're handling this, I found it rather confusing. I would use one containing element with a static ID and target that instead (that way you don't have to remember why you're handling multiple IDs for one container in the future).
Using replaceWith() and html()
.replaceWith() is used to replace an element with something else. This includes the element that is being targeted, so you need to be very aware of what you're wanting to replace. .html() may be a better way to go since it replaces the content within the target, not including the target itself.
I've made these updates and forked your fiddle here.

jQuery object html() doesn't work ... but innerHtml does

I have an object that should be a valid jQuery object. When I look at the variable in FireBug it contains all the jQuery functions I'd expect (clone, remove, removeat, etc.). However, I don't see html() as a valid function and when I do this:
stringValue = myjQueryObject.html();
It does fail, saying html() is not a function. However if I do something like this:
stringValue = myjQueryObject[0].innerHTML;
It will correctly pass back the object, minus the parent div and text (which I would expect, seeing as how it is just getting the innerHtml). What do am I missing here?
As noted below, it was an external library that was generating myjQueryObject that had previously returning a valid jQuery object and was updated ... incorrectly. For posterity's sake, I've updated my unit tests to verify that the external library returns a correct jQuery object, make sure this doesn't return null or undefined:
myjQueryObject.jquery
Thanks all! Had a bit of a freakout when my code suddenly broke this morning.
Either something is modifying the jQuery object prototype, or you have a different library loaded.
Take your object, and test for the jQuery version like this:
alert( myjQueryObject.jquery ); // should give the jQuery version number
EDIT:
Additionally, you state that there's a removeAt method. jQuery doesn't have one of those, unless you mean removeAttr().
Are you sure it's a jquery object? Wrap it in $() again and .html() should exist.
it's [0].innerHTML or .get(0).innerHTML, in that innerHTML is a property not a method.
You should make sure that jquery exists by doing alert( jQuery == $) and you can check for the .jquery property.
That's odd; try $(myjQueryObject).html();. If that works, the object isn't really a jQuery node.
If you still can't figure out why the object lost the html() method, post the code which creates it. Then, we might be able to help.
How are you setting myjQueryObject?
<div id='myElement'></div>
//Good Javascript, Incorrect jQuery
myjQueryObject = document.getElementById('myElement');
myjQueryObject.innerHTML = '<b>My HTML Here</b>';
//Correct jQuery
myjQueryObject = $('#myElement');
myjQueryObject.html('<b>My HTML Here</b>');
//Compact Version of Correct jQuery
$('#myElement').html('<b>My HTML Here</b>');

Is there a way to make jQuery output *actual markup*?

When using jQuery to dynamically build markup, it sometimes becomes useful to have it return the actual HTML that it's generating as a string, rather than as a bunch of jQuery objects. Is there a way to do this? For example, here:
$("<strong></strong>").text("Hi there!");
I want to be able to extract the plain-text string
"<strong>Hi there!</strong>"
so that I can cache it remotely. Is there a way to do this?
Yes, you can use the html() function
i.e.
$("").text("Hi There!").html();
Will return 'Hi There!'
Keep in mind this uses innerHTML, so
$("<div><b>Foo</b></div>").html();
will return
<b>Foo</b>
As a result you'll need to wrap your code in a surrounding div or span.
You can use a outerHTML plugin for that. Here is one:
jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}
Usage:
alert($("<strong></strong>").text("foo").outerHTML());
// alerts <strong>foo</strong>
Just call .html() to get HTML from any element, including generated ones. This is from a Chrome developer tool session:
> $("<div><span>blerg</span></div>")
Object
> $("<div><span>blerg</span></div>").html()
<span>blerg</span>
You can see, the first one returned an object, the second returns text.

Creating Javascript object from JQuery object

Currently I'm unit testing the following code:
if ($(selectedElement).innerText == 'blah')
{
// do something
}
with selectedElement being an anchor object selected from the UI.
In my test code, I have created a DOM structure which has that anchor in the proper position ready to be selected. The problem here is that since selectedElement is originally a javascript object, I need to convert the anchor I got from the DOM structure (which is a JQuery object) in order to get into the above condition.
I have tried the following, with no success:
// DOM structure using HtmlDoc
/*:DOC += <span id='testSpan' class='testSpanClass'><a href='#' id='selectedElem'>blah</a></span> */
selectedElement = $('#selectedElem')[0];
My goal is to be able to use a normal Javascript object to satisfy the condition, and also be able to switch it back to a jQuery object to satisfy conditions further down the function. But if there is a better approach I'll give it a go.
Does anyone have any ideas on how to go about this problem?
EDIT: Is there a solution that does not require changing of the code? selectedElement is actually a global variable.
Thanks.
I am not sure what browser you are testing in, but innerText is an IE only property. Since you are already using jQuery, I would suggest you just call the .text() method on the selected element like this:
selectedElement = $('#selectedElem')[0]; // Get DOM element
if ($(selectedElement).text() == 'blah')
{
// do something
}
You're method of getting the DOM object is fine: $('#selectedElem')[0] or $('#selectedElem').get(0) are equivalent, but the first one is faster in large loops.
jQuery's get method returns the original DOM elements for that jQuery object.
I think perhaps you need to use $('#selectedElem').get(0)
can you use jquery's .html() ?
if ($(selectedElement).html() == 'blah')
{
// do something
}
otherwise, without changing code:
var selectedElement = $('#selectedElem')[0];
if (selectedElement.innerHTML == 'blah')
{
// do something
}

Categories

Resources