Creating a DOM element from a complicated HTML-string - javascript

Is it possible to create a DOM from an HTML string that includes link, style, script and comments?
In my app, the end user will be pasting some form code, for example:
<!-- Start comment -->
<link href="test.css" rel="stylesheet" type="text/css">
<style type="text/css">
#full_name{background:#fff; }
/* This is
another comment*/
</style>
<div>
<form action="process.php" method="post">
Full Name:<input type="text" name="full_name">
</form>
</div>
<script type='text/javascript' src='test.js'></script>
<!-- End comment -->
This is the jquery code:
$('#html-go').click(function (e) {
e.preventDefault();
var html_code = $('#html-code').val(),
obj = $('<div/>').html(html_code).contents();
alert(obj.attr("action"));
});
I want to load it into a DOM element for parsing but I get an undefined error. If the form code contains only that between the tags, then everything's OK.
Here's a JSFiddle that shows the error (paste the form code above).

You need to get your form inside your newly created div:
alert(obj.find('form').attr("action"))
See this JSFiddle.

$('#html-go').click(function (e)
{
e.preventDefault();
var html_code = $('#html-code').val();
console.log(html_code);
obj = $('<div/>').html(html_code).contents();
alert($(html_code).attr('action'));
});

Related

issue running a JS function on a webpage

I'm trying to use a javascript function to make a simple input text box dissapear, and I made it dissapear using css, but the javascript portion to make it fade in and out wont work. I got the fiddle from here.
a watered down version of my page looks like this:
<html lang="en">
<head>
<title>Volunteer Form</title>
<script type="text/javascript" src="script.js"></script>
<style type="text/css">
.fieldset-auto-width {
display: inline-block;
}
.todisplay {
display:none;
}
</style>
</head>
<body>
<input type="checkbox" name="typeofwork[]" value="other" class='checkdisplay' > Other <br><br>
<div class='todisplay'>
<b>Other Tasks</b><br>
if checked other, type below.<br>
<input type="text" name="othertasks"><br><br>
</div>
<div class='todisplay'>test</div>
and I made a javascript file in the same directory with this in it and named it script.js:
$(document).ready(function () {
$('.checkdisplay').change(function () {
if (this.checked) $('.todisplay').fadeIn('slow');
else $('.todisplay').fadeOut('slow');
});
});
I also tried putting the same script at the bottom of the page between the and tags like so:
</body>
<script type="text/javascript" src="script.js">
$(document).ready(function () {
$('.checkdisplay').change(function () {
if (this.checked) $('.todisplay').fadeIn('slow');
else $('.todisplay').fadeOut('slow');
});
});</script>
</html>
I'm sorry I'm terrible at javascript, I tried following the fiddle instructions from another stack overflow page and I have no idea why it wont execute. I tried everything I could possibly think of. Can someone please help?
Don't forget to import the JQuery library.
Also (and this is unrelated to your issue), place { and } around control blocks (the branches of your if statement, loops, etc.) to avoid confusion and prevent bugs in your code.
Additionally, it is usually a bad idea to use special characters in the name or id attribute of an element. You have name="typeofwork[]" as the name of your checkbox. You should consider changing that to an alphanumeric value.
// This code can be in an external script file, but you will have to reference that file
// similarly to the way JQuery is imported with the HTML <script> element. Or, you
// can place this code in a <script> element and place that element at the bottom of your
// HTML (just before the closing body tag) or inside the HTML <head> section.
$(document).ready(function () {
$('.checkdisplay').change(function () {
if (this.checked) {
$('.todisplay').fadeIn('slow');
}
else {
$('.todisplay').fadeOut('slow');
}
});
});
<html lang="en">
<head>
<title>Volunteer Form</title>
<style type="text/css">
.fieldset-auto-width {
display: inline-block;
}
.todisplay {
display:none;
}
</style>
<!-- This must preceed any code that uses JQuery. It links out to that library so you can use it -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="checkbox" name="typeofwork[]" value="other" class='checkdisplay' > Other <br><br>
<div class='todisplay'>
<b>Other Tasks</b><br>
if checked other, type below.<br>
<input type="text" name="othertasks"><br><br>
</div>
<div class='todisplay'>test</div>

Get Element Breaking Code

I'm trying to improve my Javascript by starting a simple web interface, but every time I try to add an event listener to an input field, it breaks my code.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="colors.css">
<script src="spot.js"></script>
</head>
<div id="ask">
Search for an artist to see their top songs:
</div>
<form>
<input type="text" name="artist" id="artist-search">
</form>
<div id="sub">
submit
</div>
</html>
And here's my Javascript:
window.onload = loaded;
var inField;
function loaded() {
document.getElementById("sub").addEventListener("click", search);
inField = document.getElementById("artist-search");
}
//https://api.spotify.com/v1/search?q=tania%20bowra&type=artist
function search() {
alert();
//var query = "//https://api.spotify.com/v1/search?q=";
}
When I add the getElementById to "artist-search", the alert in the search function stops working. Why is this? And is there a better way to get the text in an input field when someone clicks a submit button using vanilla Javascript?

Handlebarsjs : H1 tag won't display when submit button is clicked

I'm messing around with Handlebars.js and I'm doing a very simple example consisting of a tutorial from a website(the shoes section) and my own simple little template(the heading, where the problem is)
handlebardemo.html
<head>
<meta charset="ISO-8859-1" name="viewport" content="width=device-width, initial-scale=1">
<title>Handlebar demo</title>
<script src="lib/jquery-2.1.4.js" type="text/javascript"></script>
<script src="lib/jquery-ui.js" type="text/javascript"></script>
<script src="lib/handlebars-v4.0.4.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/w3.css">
<link rel="stylesheet" href="css/jquery-ui.css">
</head>
<body>
<div class="username-container">
<script id="heading-template" type="x-handlebars-template">
<h1 class="h1">Hello {{username}}</h1>
</script>
<input type="text" id="username">
<button type="submit" id="username-submit">Enter</button>
</div>
<h4 class="w3-row-padding">Shoe List:</h4>
<ul class="shoesNav w3-ul w3-text-indigo"></ul>
<script id="shoe-template" type="x-handlebars-template">
{{#each this}}
<li class="shoes">{{name}}--Price:{{price}} </li>
{{/each}}
</script>
</body>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
$(function (){
var shoesData=[{name:"Nike", price:199.00}, {name:"Loafers", price:59.00}, {name:"Wing Tip", price:259.00}];
//Get html from tempalte in script tag
var theTemplateScript = $("#shoe-template").html();
//Compile the template
var theTemplate = Handlebars.compile(theTemplateScript);
$(".shoesNav").append(theTemplate(shoesData));
//shoesData is passed to compiled handlebars function
//function inserts values from the objects in their respective places in the HTML
//and returned HTML: as a string. Then jQuery is used to append the resulting HTML string to the page
})
Im not sure if I'm using the handlbars syntax etc. correctly, but i based it mostly off of the second function in main.js, which came from a brief handlebars tutorial
When I click the Enter button, nothing happens. There are no console errors, it just does nothing. Am I going about this the wrong way, at least compared to the unordered list example?
EDIT: As per Elli Parks answer, I added an id to the submit button and changed the click handler assignment to the submit button rather than the textbox(a silly mistake on my part). The element still won't appear when the submit button is clicked
In main.js, you're attaching the click handler to #username, which is an input field. You need to give the Enter button an id (ex: #username-submit) and attach the click handler to the button.
So something like this:
handlebardemo.html
<button type="submit" value="Enter" id="username-submit" >Enter</button>
main.js
$("#username-submit").click(function(){
var uNameVal = $("#username").val();
var uName = {"username":uNameVal};
var theTemplateScript = $("#heading-template").html();
var theTemplate = Handlebars.compile(theTemplateScript);
$(".username-container").append(theTemplate(uName));
});
You need to change two things:
fix the selector to target the button, like #ElliPark has already said
put the whole thing into the document-ready handler (ie, into the $(function () {...} ); construct. You are trying to attach the event listener before the DOM is ready.
See the demo on JSBin.

how create document Object into HTML page?

I need to create a document Object into HTML page using javaScript
to execute a new HTML page into it;
like this :
<!DOCTYPE html>
<html>
<head>
... some head tags appened
<script>
// not problem of with jquery or not
function createDocument(){
var ta = document.getElementById('ta');
var targetElement = document.getElementById('targetElement')
// so i need to know how can use [ta.value]
// to execute it in new DOCUMENT Element appended it in [targetElement]
// without get or set global variables in origin document
}
</script>
</head>
<body>
<textarea id="ta"></textarea>
<div id="targetElement">
<!-- need to append new html document HERE! -->
</div>
<!--
when click the run Button the value of text area can be
running content to create new document object into targetElement
-->
<button onclick="createDocument()">RUN</button>
</body>
</html>
You probably mixed up .getElementById and .createElement
<!DOCTYPE html>
<html>
<head>
<script>
function createDocument(){
var ta = document.getElementById('ta').value;
var targetElement = document.getElementById('targetElement');
targetElement.innerHTML = eval(ta);
}
</script>
</head>
<body>
<textarea onchange="createDocument();" id="ta"></textarea>
<div id="targetElement">
<!-- Content goes here -->
</div>
</body>
</html>

Rich Text Editor (YUI Simple Text Editor used) not sending data to next page

I am using a simple text editor from YUI, but when I click submit the code in the textarea/editor is not sent to the next page. I want to be able to receive it on the subsequent page and then store it in a DB(MySql). I have wasted lot of time already. Please help.
HTML FILE:
<html>
<head>
<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.9.0/build/yahoo-dom-event/yahoo-dom-event.js&2.9.0/build/container/container_core-min.js&2.9.0/build/element/element-min.js&2.9.0/build/editor/simpleeditor-min.js"></script>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.9.0/build/editor/assets/skins/sam/simpleeditor.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.8.2r1/build/assets/skins/sam/skin.css">
<!-- Utility Dependencies -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js"></script>
<!-- Needed for Menus, Buttons and Overlays used in the Toolbar -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/container/container_core-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/menu/menu-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/button/button-min.js"></script>
<!-- Source file for Rich Text Editor-->
<script src="http://yui.yahooapis.com/2.8.2r1/build/editor/editor-min.js"></script>
<script>
YAHOO.util.Event.on('submit', 'click', function() {
myEditor.saveHTML();
var html = myEditor.get('element').value;
});
(function() {
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event;
var myConfig = {
height: '200px',
width: '900px',
dompath: true,
};
myEditor = new YAHOO.widget.SimpleEditor('msgpost', myConfig);
myEditor.render();
})();
</script>
</head>
<body class="yui-skin-sam">
<form action="submit.php" method="post">
<textarea name="msgpost" id="msgpost" cols="50" rows="10"></textarea>
<input type="submit" value="Submit" onsubmit="return myDoSubmit()"/>
</form>
</body>
</html>
The saveHTML() method you used does not seem to save the value to the textarea element. And because the browser doesn't care about YUI Editor and just submits what is there already in the textarea (which is null), it submits the input as null..
You should set the value of the textarea to the editor value so the browser will submit that value instead of null.. Which can be achieved using this little line:
document.getElementsById("msgpost").value = html;
See this working JsFiddle I made for you.
However you had HTML syntax errors too. The onSubmit attribute should be on the form element not the submit button.
And listening to the event is not practical when you can simply call a function when the form submits.. (See the JsFiddle)
I saw an example on this post.
Basically, add this to myConfig: handleSubmit: true
myConfig will then look like this:
var myConfig = {
height: '200px',
width: '900px',
dompath: true,
handleSubmit: true
};

Categories

Resources