Alternative to x.innerHTML for long texts - javascript

I'm trying to write a form in HTML and JS that shows at the end the completed form uneditable for confirmation.
I have to replace the contents of the page without refresh and/or redirection.
My code is:
function F() {
if(...){
//Empty fields [...]
}else{
var el = document.getElementById("formID"); //Form da sostituire
el.innerHTML = "NEW CONTENT";
}
}
The problem is that the "new content" is really long and is very uncomfortable to write it as a string. Are there any alternatives to innerHTML for this situation?

Use the <template> tag. Put the content you want inside a <template> tag, give it an ID, and then in JavaScript simply copy the content of the template inside the form.
HTML:
<template id="form-template">
NEW CONTENT
</template>
JavaScript:
function F() {
if(...){
//Empty fields [...]
}else{
var el = document.getElementById("formID"); //Form da sostituire
el.innerHTML = document.getElementById("form-template").innerHTML;
}
}
See live example in the following snippet:
document.querySelector("button").addEventListener("click", event => {
document.getElementById("content").innerHTML = document.getElementById("my-template").innerHTML
})
<template id="my-template">
<h1>Hello template!</h1>
</template>
<button type="button">Try it!</button>
<div id="content"></div>

For problem of <template> browser support you could use any element as placeholder, like this :
document.querySelector("button").addEventListener("click", event => {
document.getElementById("content").innerHTML = document.getElementById("my-template").innerHTML
})
.template{
display:none;
}
<div id="my-template" class="template">
<h1>Hello template!</h1>
</div>
<button type="button">Try it!</button>
<div id="content"></div>
Or just give display:none to template element :)

Related

how to Append defined functions to script tag of html

Hi: I want to append a js function something like function amb(){console.log("hello")} inside the script tag. But There is a problem in this. Because as the function is append to script tag it says function is not defined when i try to call. if you understand the problem or have any solution to it please help me. Thanks a lot...
<script id="append_here">
// the appended function goes in this script
</script>
<script>
a = `function amb() { console.log('hello')}`
document.getElementById('append_here').append(a)
</script>
<div id="a">
<button onclick="amb()"> amb</button>
</div>
You can't append content to a script and have the browser "re-parse" the script
You can create a new script tag, add the content, and append that to the body
<script>
const a = `function amb() { console.log('hello')}`;
const scr = document.createElement('script');
scr.textContent = a;
document.body.append(scr);
</script>
<div id="a">
<button onclick="amb()"> amb </button>
</div>
You can use eval aswell
<script id="append_here">
// the appended function goes in this script
</script>
<script>
a = `function amb() { console.log('hello')}`;
document.getElementById("append_here").append(eval(a));
</script>
<div id="a">
<button onclick="amb()">amb</button>
</div>

How to hide a parts of text after a special symbol, using html and Javascript?

I'm trying to hide a part of every user email, registered in a website.
So lets say I have get zero#example.com and I want to hide everything after the "#". And only show it if someone clicks on whats left of the email.
Any help would be appreciated.
This just hides everything.
<p>
<button onclick=".hide('#email')">Hide</button>
<button onclick=".show('#email')">Show</button>
</p>
<div id="email">
<h2>zero#example.com<h2>
</div>
Try following:
<script type="text/javascript">
function show(){
document.getElementById('trail').style.display = 'inline';
}
function hide(){
document.getElementById('trail').style.display = 'none';
}
</script>
<p>
<button onclick="hide()">Hide</button>
<button onclick="show()">Show</button>
</p>
<div id="email">
<h2>zero<span id="trail">#something.com</span></h2>
</div>
You can use split ( => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split ) if you know what character to expect. In this case:
var full; // let's say, it already has a value (f.e. zero#something.com)
var visiblePart = full.split("#")[0];
and eventually you can do something like this on click:
function show(){
document.getElementById("emailH2").innerHTML = full;
}
function hide(){
document.getElementById("emailH2").innerHTML = visiblePart;
}
and
<h2 id = "emailH2">zero#something.com<h2>

Search text in html by javascript

I have some html like this:
<html>
<body>
<div>
<p>Something</p>
</div>
<div class="hide" id="show">Protected</div>
</body>
</html>
I need to display or hide/show an element via JavaScipt if html has "Something" in its text. How can I do that? I need this for my Wordpress page.
Without using jQuery:
var content = document.body.textContent || document.body.innerText;
var hasText = content.indexOf("Something")!==-1;
if (hasText) {
document.getElementById("show").style.display = 'block';
} else {
document.getElementById("show").style.display = 'none';
}

How to select elements from <template> with jQuery

I have two similar selections. The first uses a <div> tag, which works fine, the second uses a newly <template> tag, which doesn't work anymore.
Can anyone tell me how to get this to work with jQuery using the <template> tag?
HTML
<div id="div">
<div>content</div>
</div>
<template id="template">
<div>content</div>
</template>
JavaScript
var $div = $('#div');
var $content = $div.find('div');
console.log($content); //works ($content.length == 1)
var $template = $('#template');
var $content = $template.find('div');
console.log($content); //doesn't work ($content.length == 0)
http://jsfiddle.net/s8b5w0Le/1/
HTMLTemplateElement saves the DOM into a seperate attribute:
JQuery
<script src="jquery-3.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var $div = $('#div');
var $content = $div.find('div');
console.log($content.text()); // output "content", inner div
var $template = $('#template');
var node = $template.prop('content');
var $content = $(node).find('div');
console.log($content.text()); // output "content", inner template
});
JavaScript
document.createElement('template').content
I'm fairly certain this has to do with Chrome's use of shadow dom (thank Polymer... )
You can either try your luck using the /deep/ combinator (probably won't work on other browsers), but I think the most robust solution would be $template[0].outerHTML as in your comment if you just need the text.
If you need jQuery functionality, using $.parseXML (to avoid Chrome's native dom construction) would probably do the trick across all browsers (can confirm Chrome + FF).
Example here: http://jsfiddle.net/3fe9jjfj
var tc = $('#template')[0].outerHTML;
$template = $($.parseXML(tc)).contents();
console.log($template);
console.log($template.find('div'));
Both logs return as we'd expect, and $template can now be treated as an ordinary jQuery object.
As others have noted, Chrome puts <template> child elements into a shadow DOM. To access them:
// Access the JavaScript object for the template content
$('template')[0]
// Make a jQuery selection out of it
$($('template')[0])
// Now you can search it
$($('template')[0]).find('div.someclass').css('color','#000');
A way, too late for the party but I ended up doing this:
function resolveTemplate(id) {
return $(id).contents();
}
...
var $searchIcon = resolveTemplate('#search-icon-template');
$('#div').append($searchIcon);
You can use all the JQuery methods as usual if the element inside the template element are wrapped with a container.
const temp = $("#template").contents().clone();
$(temp).find("h1").text("A dynamic title");
temp.appendTo($("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="app"></div>
<template id="template">
<div class="container">
<h1>lorem ipsum</h1>
<p>lorem ipsum </p>
<img src="" alt="">
</div>
</template>
The container can also be appended dynamically with JQuery. Or if you don't want a container, you can append its content.
const temp = $('<div></div>').html($("#template").contents().clone());
$(temp).find("h1").text('dynamic title');
$(temp).find("p").text('But no container this time');
temp.contents().appendTo($("#app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="app"></div>
<template id="template">
<h1>lorem ipsum</h1>
<p>lorem ipsum </p>
<img src="" alt="">
</template>
<template>
<div class="template-container">
<div class="content">content</div>
</div>
</template>
var templateHtml = ('#template').html() // this will return the template container div
var template = $(templateHtml);
var content = template.find('.content');
console.log(content);
var $content = $template.content.find('div');
... instead of ...
var $content = $template.find('div');
Worked for me.
HTML5 template is display: none; by default, childNodes in template is invalid, if you inspect it in console you'll find something different

Open sub link in the same page in html

In html I am having the following tags:
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
On Clicking on 2011-2012 or on 2012-2013 I want to set display property of div tag.
I am using the following Javascript code for this and I am calling the Javascript function in body tag. The output is showing style and display is not an object or property.
<script language="javascript">
function clickHnadler()
{
var xid= document.getElementsByTagName("span");
var xsp= xid[0].id;
alert("Span id is "+xsp);
if(xsp.charAt(0)=="M")
{
var oC = document.all("C"& xsp.substring(1,2));
if(oC.STYLE.display == "none")
{
oC.Style.Display = "";
}
else{
oC.Style.Display = "none";
}
}
}
</script>
use jquery:
you can pass in the function the element or the Id:
ex:
<span id=M26>2011-2012</span>
function clickHnadler(element)
{
var id = $(element > span).attr(id);
id[0] = 'c'; //not the nicest way, maybe use a replace or something like that
$(id).show(); //or $(id).css('display','list');
}
You may use clickHandler has following way,
function clickHandler(e) {
window.document.links[0].handleEvent(e);
}
You need to bind event spacifically to elements you want to handle click for. for more information please refer following link,
http://docs.oracle.com/cd/E19957-01/816-6409-10/evnt.htm#1009606
Based on what i understand from your question, I come up with this.
<script type="text/javascript" src="jquery1.8.js"></script>
<span id=M26>2011-2012</span>
<div id=c26 STYLE="display:none">
2011-2012 details</div>
<br />
<span id=M27>2012-2013</span>
<div id=c26 STYLE="display:none">
2012-2013 details
</div>

Categories

Resources