JQuery: convert var's html contents to string - javascript

I have a var that gets the HTML of a div. I want to use that var in a hidden form field so I can save the HTML to a database.
I am just having difficulty converting the HTML or the var to a string. Currently, adding the var to my input as is disrupts the code.
I have tried using .wrap('<pre />'); in a few different ways but it doesnt help and I dont think it is right.
Can anyone point me in the right direction? Thanks!
var code = $('#container').html();
code = code.wrap('<pre />')
document.write('<input type="hidden" name="html" value="' + code + '">');

You're better off using the helper methods over a direct document.write as (because it's HTML) you'll need to escape it (ensure no quotation marks are witin the code). Long story short, maybe use something like:
$('<input>',{
'type':'hidden',
'name':'html'
}) // create element
.val(code) // use helper to insert HTML (auto-excapes)
.appendTo('body'); // insert it where ever you need it
Further explanation: Say, for example, code had the following:
<div class="foo">bar</div>
By using a document write (and not escaping it) you're writing:
<input type="hidden" name="html" value="<div class="foo">bar</div>">
The class="foo" (and its quotes) interfere with the original hidden element's value="" attribute. using .val() avoids this because it makes sure the value is safely inserted in to the element.

Using jQuery, this is probably the best way to do it...
jQuery(document).ready(
function (){
var code = jQuery.trim(jQuery('#container').html());
jQuery("form").append('<input type="hidden" name="html" value="' + code + '">');
});

Related

How to select element with id containing \ in jquery or javascript

we have some legacy code where Html element ID's are populated dynamically from database data (I cant change the data here)
ex. <input type="text" id="2314/test/film/code\branch"/>
when I get the ID from click event like below
var src = window.event.srcElement; I get src.id= "2314/test/film/code\\branch";
I want to use the src.id to find the same element in different function like $(_element).find("[id='" + src.id + "']").get();
which is failing to get any ID since I see "\" is replaced with "\\"
Please suggest me how to get around this ?
I don't think jQuery lets you use / in a selector. It is an illegal character in an id name, but still odd that jquery seems to flat out refuse it. Since JS has no problem with that selector You can select it with JS then pass it off to the jquery wrapper.
$(document.getElementById('2314/test/film/code\\branch'));
Maybe it´s works for you
http://codepen.io/luarmr/pen/vOgoLO
$("[id='" + str.replace(/\\/g,'\\\\') + "']").html(str)
The correct regex for backslash is '\\\\'.

why is ® not working when used with jquery

I am having a problem I want to attach the registered trademark symbol a button and I want it to be done with jquery because there are lots and lots of buttons that require the sign when I used it with html for example(below) it worked.
<input type="button" class="button_a" value="Value ®" />
But when I used jquery as below it returns as plain text:
$('.button_a').each(function(){
$(this).attr("value",$(this).attr("value")+" ®");
});
I don't want to waste my time and space by putting ® in all the button's values so I want it to be done in jquery but what am I doing incorrect.
I know it's a sluggish question but please someone help out me in this question
Javascript may be also used.
For more info please comment and ask
Thanks....
® is being rendered as a text string, but you can use unicode \u00AE
$('.button_a').each(function(){
this.value = this.value +" \u00AE";
});
http://jsfiddle.net/fbuohvm1/
or just ®:
$('.button_a').each(function(){
this.value = this.value +" ®";
});
http://jsfiddle.net/fbuohvm1/1/
Because, while the DOM you are manipulating was initialised from an HTML document, you are now dealing with DOM and not HTML. You are writing the value as text not as HTML.
You need to use either a literal character ("®") or a JavaScript escape sequence ("\u00AE").
You have to encode it first before setting the value of textbox.
$('.button_a').each(function () {
$(this).val("value " + $("<div/>").html('®').text());
});
$("<div/>").html('®').text() will return the encoded value.
Demo: https://jsfiddle.net/tusharj/t2gwptys/
you need to process content by html(), because html entities is manipulate by html() function, try this code.
$('.button_a').each(function(){
$(this).val($("<p/>").html($(this).val()+" ®").html());
});
Use a hidden div.
$('.button_a').each(function(){
var decoded = $('<div/>').html('®').text();
$(this).val($(this).val() + ' ' + decoded);
});
See Sample
In your case plain js is more straightforward:
$('.button_a').each(function(){
this.value += " ®";
});
-- EDIT --
Unfortunately this is still escaped, in fact you need
this.value += " \u00AE";

jquery escape square brackets to select element

Consider a input element
<input id="meta[152][value]" type="text" />
Here the input field is dynamically generated. I need to select that field. So I used,
alert($('#meta[152][value]').val());
But this seems to be invalid. After searching I found, that the "square brackets" need to be escaped like #meta\\[152\\]\\[value\\]
So how to do that ?
I currently use this code,
var id = "#meta[152][value]" // (I get this value by another method) I need the escaping to be done here. So that i can use as
/** I need the value of id to be escaped using regex,replace or any other method
to get #meta\[152\]\[value\]
and not manually **/
alert($(id).val());
Your suggestions will be helpful !
The following should work:
alert($('#meta\[152\]\[value\]').val());
or
var id = "#meta\[152\]\[value\]";
alert($(id).val());
Working Example
Conversion Function:
function ConvertValue(id)
{
var test = id.replace(/[[]/g,'\\\\[');
return "#" + test.replace(/]/g,'\\\\]');
}
Conversion Example
If you feel more comfortable without escaping you also use the attributes selector and search for the element with that id like this: $("[id='meta[152][value]']")
The simplest way is just to use the regular getElementById, which requires no escaping:
document.getElementById("meta[152][value]").value;
this shoudl work for you, you almost had it:
$(document).ready(function() {
var id = "#meta\\[152\\]\\[value\\]";
alert($(id).val());
});
Um, just put the escaped value right in your string.
var id = "#meta\\[152\\]\\[value\\]";
See it working here
You can use the _.escapeRegExp method from the Lodash library.
console.log($('#' + _.escapeRegExp('meta[152][value]')).val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<input id="meta[152][value]" type="text" value='Test' />

dynamically change html element

I have some checkboxes, once I check one of these the ID of the checkbox is sent to a function. I want this function to change the checkbox to a <img>element with the same ID.
I have tried
document.getElementById(ID).innerHTML = '<img src="image.png" id="' + ID + '"/>';
But this doesn't work, is it possible to change a element or would I need to create a new one using the same ID?
Thanks
I would advise that rather than replace one element with another you make one visible and one invisible eg...
document.getElementById(ID).style.display='none';
and
document.getElementById(ID).style.display='block';
And I would think of a way round the same ID constraint. Why do you need them to have exactly the same ID?
You'll need to create a new element and remove the old one. In case you need it, here's a quick article on adding and removing elements using javascript: http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
By way of explaining why you can't do what you were trying to do, your elements are represented in the DOM as different "types" (strictly speaking, this is not true, but it's a useful representation), and you can't just change the "type" of an object by changing its underlying markup.
in pure javascript you can do something like:
function changeToImage(el) {
var img = document.createElement('img');
img.setAttribute('src', 'http://www.google.com/images/nav_logo29.png');
img.setAttribute('ID', el.getAttribute('id'));
var parent = el.parentNode;
parent.appendChild(img);
parent.removeChild(el);
}
then from your html you would do
<input type="checkbox" onclick="changeToImage(this)" />
note that this may not be cross-browser proof.... you can also use jquery to simplify things
You can try to write like this one.
It worked for me.
Replace the innerHTML with HTML
document.getElementById(ID).HTML = '<img src="image.png" id="' + ID + '"/>';

jQuery: Using Selectors on HTML from an Attribute

I have some HTML that is stored as an attribute on a tag. I can access it in jQuery using
$("input[id$='_myField_hiddenSpanData']").attr("value")
This looks like this:
"<span id='spantest\user' tabindex='-1' contentEditable='false' class='ms-entity-resolved' title='test\user'><div style='display:none;' id='divEntityData' key='test\user' displaytext='Test User' isresolved='True' description='test\user'><div data=''></div></div><span id='content' tabindex='-1' contenteditable onMouseDown='onMouseDownRw();' onContextMenu='onContextMenuSpnRw();' >Test User</span></span>"
I would need the value of the key attribute (test\user). Can I somehow tell jQuery to parse a block of HTML and apply selectors to it? I found I can wrap it into a new jQuery object by wrapping it into another $(): $($("input[id$='_myField_hiddenSpanData']").attr("value")) but I still did not manage to apply a selector on it.
Any hints? And no, sadly I do not control the markup that generates the hidden field.
Wrap your crappy markup with a jQuery object, and then use the find function to apply a selector to it...
var crappyHtml = $("input[id$='_myField_hiddenSpanData']").attr("value");
var key = $(crappyHtml).find("div[key]").attr("key");
alert(key);
Try this:
var html = $("input[id$='_myField_hiddenSpanData']").attr("value");
var user = $(html).find("#divEntityData").attr("key");
alert("user=" + user);
You should be able to pass it as a context. Does this work?:
$('#divEntityData', $($("input[id$='_myField_hiddenSpanData']").attr("value"))).attr('key');

Categories

Resources