jQuery, appending HTML string not working - javascript

When using the code below I am unable to add the HTML string to the innerHTML of the target HTMLElement. What am I doing wrong? Is there a better way to do this?
<html>
<head>
<title>Add HTML input with jQuery</title>
<!--
* This code is meant to include the jQuery library v.1.9.1
* from Google API
-->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'></script>
<script>
$('document').ready(function(){
$('#add').click(function(){
var src = $('#src'); // alert(src);
var trgt = $('#src'); // alert(trgt);
var x = null;
var child = null;
var str = null;
if(null != src.val()){
alert(1);
x = trgt.children().length;
str = '<input type="text" name="array[]" id="index' + x + '" value="' + src.val() + '" />';
trgt.html().append(str);
src.val() = null;
}else{
alert('src value is emppty');
}
});
});
</script>
</head>
<body>
<div id="box">
<label></label> <input type="text" name="src" id="src" value="" /> <button id="add">+</button>
<div id="trgt">
</div>
</div>
</body>
</html>

var trgt = $('#src'); ... Your source and target selectors are the same.

This var trgt = $('#trgt') is not the only problem I noticed.
There is trgt.html().append(str); which should be trgt.append(str);.
And then src.val() = null;, are you trying to reset the <input> value? You can simply do it with src.val('');
See this jsfiddle.

Related

How to assign Multiple line html code as a value to a javascript variable?

This my code..
<!DOCTYPE html>
<html>
<head>
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name ").value;
var school_site= document.getElementById("school_site ").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>
<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br> <input type="text" name="name" id="name"></p>
<p>School Website:</br> <input type="text" name="school_site" id="school_site"></p>
<p>School Name:</br> <input type="text" name="school_name" id="school_name"></p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
"content" is the javascript variable.
I need to assign HTML code as value for "content" variable,
And i also need to add some Javascript variable inside the HTML
code,
How to add javascript variable in html Hypertext link?
There are many ways to achieve this. For a simple use-case, you can use an array of string to perform work and at the end you can join with "" or "\n".
var template = [
"<h2>Student Details:</h2>",
"<div align='justify'><p>"+name+"is studing in "+school_name+"</p>",
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p></div>"
].join("<br/>");
For more complex case, I will say use jquery or Plain JavaScript method. As given below.
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
//jQuery:
var node = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
);
//Plain JavaScript
var h2 = document.createElement("h2");
h2.textContent = "Student Details:";
var div = document.createElement("div");
var p1 = document.createElement("p");
p1.textContent = name+"is studing in "+school_name;
var p2 = document.createElement("p");
p2.textContent = "Visit site: ";
div.appendChild(p1);
div.appendChild(p2);
//add attribute node
var node = document.getElementById("div1");
var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);
//Once done return as string
return div.outerHTML;
}
You have extra space in id in school_name and school_site`.
So it is not being recognized and you are getting exception. Also your syntax to concatenate string is also incorrect.
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
Your full javascript code would be like this
<script>
function generate(){
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site= document.getElementById("school_site").value;
var content= "<h2>Student Details:</h2>"+"/n"+
"<div align='justify'>"+
"<p>"+name+"is studing in "+school_name+"</p>"+"/n"+
"<p>Visit site: <a href='http://"+school_site+"'>http://"+school_site+"</a></p>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
You can write a string on multiple lines using template literals, i.e. using the character " ` ".
You can easily integrate variables using ${yourVar} in the template literal
Example:
let lit = "literal";
var content = `This string
uses a template ${lit}`;
console.log(content);
Note: this is an ES6 feature, aka the not so new JavaScript that is not yet fully supported by browsers. To make this code compatible with older browsers, use a transpiler like babel
You have to use <br> instead of '/n' while assigning to javascript variable.
The problem as I see it is you have hit enter in the mid of string and you have extra space in the id selector.
Don't hit enter or use tilt ` to declare string instead of quotes.
<!DOCTYPE html>
<html>
<head>
<script>
function generate() {
document.getElementById("show").style.display = "block";
var name = document.getElementById("name").value;
var school_name = document.getElementById("school_name").value;
var school_site = document.getElementById("school_site").value;
var content = "<h2>Student Details:</h2>" +
"<div align='justify'><p>" + name + "is studing in " + school_name + "</p>" +
"<p>Visit site: <a href='http://" + school_site + "'>http://" + school_site + "</a></p></div>";
document.getElementById("displayarea").innerHTML = content;
}
</script>
</head>
<body>
Privacy Policy Page
<p>Name:</br>
<input type="text" name="name" id="name">
</p>
<p>School Website:</br>
<input type="text" name="school_site" id="school_site">
</p>
<p>School Name:</br>
<input type="text" name="school_name" id="school_name">
</p>
<button id="click" onclick="generate()">Generate</button>
<div style="display:none" id="show">
<div style="height:200px; width:540px; overflow:auto;" id="displayarea">
</body>
</html>
Suggestion : No need to use /n for new line, h2 is block element no need of break too.

How can I run a function when a radio is selected and I click a button?

I've created this simple code that I'll use to store in the user's browser, so, I'd like to know how can I run a function when there's a selected radio and when I click the delete button, using JS or JQuery. Any help is appreciated.
Thanks in advance.
check it on liveweave
P.S.: Your browser should have WebStorage support
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de"+ taskCounter;
for(var i=1;i<taskCounter;i++){
var temp = "de" + i;
document.writeln("<br/>"+'<input type="radio" name="rad" value="'+localStorage.getItem(temp)+'" /> <label>'+localStorage.getItem(temp)+'</lable>');
}
function saveItUp(){
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp(){
$('input:radio').selected(function(){
if (this.checked) {
alert(this.value);
}
});
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label> <textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
I have edited your snippet. Use $('input[type="radio"]').prop('checked') to see whether the radio button is checked. You will need to modify the selector to get the appropriate radio button if there are multiple on the page.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + localStorage.getItem(temp) + '" /> <label>' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
//This is where I'm trying to do that, I know selected doesn't exist, but I put it just for a better comprehension
function deleteItUp() {
if ($('input[type="radio"]').prop('checked')) {
alert('Deleting!');
} else {
alert('Delete radio not checked!');
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
<input type="radio">Check to delete
</div>
</body>
</html>
I've been trying other ways to achieve it, and I found a nice way that gave me the expected result, thank all of you who tried to help me.
var taskCounter = 1 + Number(localStorage.getItem("count"));
var name = "de" + taskCounter;
for (var i = 1; i < taskCounter; i++) {
var temp = "de" + i;
document.writeln("<br/>" + '<input type="radio" name="rad" value="' + temp + '" /> <label>' + 'Code: ' + temp + ' | Value: ' + localStorage.getItem(temp) + '</lable>');
}
function saveItUp() {
var desc = $('#descrip').val();
alert(desc);
// Store
localStorage.setItem(name, desc);
localStorage.setItem("count", taskCounter);
// Retrieve
console.log(localStorage.getItem(name));
console.log(localStorage.getItem("count"));
}
var selectedRadioId = 0;
$('input:radio').change(function() {
if (this.checked) {
selectedRadioId = this.value;
}
});
function deleteItUp() {
if (selectedRadioId !== 0) {
alert('Deleting!');
} else {
alert("Radio hasn't been checked!");
}
}
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="main">
<label>Task</label>
<textarea id="descrip"></textarea>
<button onclick="saveItUp();" id="save">Save it</button>
<button onclick="deleteItUp();" id="delete">Delete</button>
</div>
</body>
</html>
You are talking about firing an event when a radio button is checked and then calling a callback function: https://api.jquery.com/checked-selector/

Onclick is not working when use that as object

This is works fine when i am using addEventListener. But, it is not working when i use button.click . what is the mistake on the below code? what is the cause it is not working on varNext.click= myFunc;?
[code]
<!doctype html>
<html>
<head>
<title>Slideshow</title>
<script type="text/javascript">
var images = ['home_default.png','about_default.png','blog_default.png','logo.png'];
function myFunc(){
var var1 = document.getElementById("slideimage");
var var2 = var1.name.split("_");
//alert(var2);
index = var2[1];
if(index == images.length - 1){
index = 0;
}else {index++;}
var1.name = "image_" + index;
var1.src = images[index];
}
</script>
</head>
<body>
<p><img id="slideimage" name="image_0" src="home_default.png" alt="Home"></p>
<form name="slideform">
<input type="button" id="nextbtn" value="Next">
</form>
<script type="text/javascript">
var varNext = document.getElementById("nextbtn");
//varNext.addEventListener("click", myFunc, false);
varNext.click= myFunc;
</script>
</body>
</html>
[/code]
Rather than .clickfires the element's click event it must be .onclickproperty returns the onClick event handler
Try this
varNext.onclick = myFunc;
Demo Fiddle of your code
You need to use the onclick attribute
varNext.onclick = myFunc;

Google Places Autocomplete on dynamic inputs

Good day.
I'm trying to add Google Places Autocomplete on dynamically created inputs using code below:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var container = document.getElementById('AutoComplInputs');
container.innerHTML += "<br>" + _id;
var _elem_for_upd = document.createElement("input");
_elem_for_upd.type = "text";
_elem_for_upd.id = _id;
container.appendChild(_elem_for_upd);
assignAutoCompl(_id);
}
</script>
</head>
<body>
<div id="AutoComplInputs"></div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
But when I press on button, autocomplete works only on last input, and all prevoius become broken. I think that it can be connected to dynamic creation of inputs, as the code below works fine:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
document.getElementById(_id).hidden = false;
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
assignAutoCompl("AutoCompl0");
assignAutoCompl("AutoCompl1");
}
</script>
</head>
<body>
<div id="AutoComplInputs">
<input id="AutoCompl0" type="text" hidden>
<input id="AutoCompl1" type="text" hidden>
</div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
I don't understand what I'm doing wrong ...
Don't use innerHTML to add content to container, you will lose all handlers bound to existing elements.
Use appendChild instead:
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode(_id));

how to add text boxes dynamically without losing values of previous textboxes?

i am using innerHTML to add text boxes dynamically. The code sample is as follows:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
document.getElementById("y").innerHTML += tag;
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html
Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(
What if I want to add textbox in this situation:
function add() {
var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
document.getElementById("addskills").innerHTML += element;
i++;
}
Yes, through DOM Manipulation:
function add() {
var tag = document.createElement('input'); // Create a `input` element,
tag.setAttribute('type', 'text'); // Set it's `type` attribute,
tag.setAttribute('name', i); // Set it's `name` attribute,
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(tag); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
This doesn't trigger the browser's DOM parser like a innerHTML does, leaving everything intact.
(innerHTML forces the browser to re-parse the entire DOM, because anything could be added with innerHTML, so the browser can't predict anything, in contrast to adding a node to a element.)
Now, to add this:
<li class="ie7fix" style="width:620px;">
<div class="m_elementwrapper" style="float:left;">
<label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
<span>
<span class="pspan arial" style="text-align:right;font-size:14px;">
<span class="ispan" xml:space="preserve">
</span>
</span>
</span>
</label>
<div style="float:left;width:475px;" class="m_elementwrapper">
<input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent">
<div class="fielderror">
</div>
</div>
</div>
<div style="clear:both;font-size:0;">
</div>
</li>
You'll need:
function add() {
// Create elements
var d1 = c('div'), s1 = c('span'), ip = c('input'),
d2 = c('div'), s2 = c('span'), li = c('li'),
d3 = c('div'), s3 = c('span'), la = c('label'),
d4 = c('div');
// You can "chain" `appendChild`.
// `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
d1.appendChild(d2).appendChild(ip);
d2.appendChild(d3);
li.appendChild(d4);
setAttributes(
[li, d1, la, s2, s3, d2, ip, d3, d4],
[
{'class':"ie7fix", 'style':"width:620px;" },
{'class':"m_elementwrapper", 'style':"float:left;" },
{'class':"fieldlabel", 'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
{'class':"pspan arial", 'style':"text-align:right;font-size:14px;" },
{'class':"ispan", 'xml:space':"preserve" },
{'class':"m_elementwrapper", 'style':"float:left;width:475px;" },
{'class':"fieldcontent", 'type':"text", 'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
{'class':"fielderror" },
{'style':"clear:both;font-size:0;" }
]
);
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(li); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
var el = elements.length,
al = attributes.length;
if(el === al){
for(var n = 0; n < el; n++){
var e = elements[n],
a = attributes[n];
for(var key in a){
e.setAttribute(key, a[key]);
}
}
}else{
console.error("Elements length " + el + " does not match Attributes length " + al);
}
}
// Alias for shorter code.
function c(type){
return document.createElement(type);
};
use jquery library
<html>
<head>
<script src='jquery.js' type="text/javascript"></script>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
var div_content=$('#y').append(tag);
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>
I've got round this before by reading all of the values into an array before replacing the innerHTML and then writing them back again afterwards. This way you can write whatever you like into the div. Following works on all browsers that I have tried:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add() {
if(i>0) {
values=new Array();
for(z=0;z<i;z++) {
values.push(document.getElementById(z).value);
}
}
var tag = '<input type="text" name="' + i + '" id="' + i + '" /> <br/>';
document.getElementById("y").innerHTML += tag;
if(i>0) {
for(z=0;z<i;z++) {
document.getElementById(z).value=values[z];
}
}
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>

Categories

Resources