Dynamically Add and Remove HTML Elements not working - javascript

I need to dynamically add and remove HTML elements to my product form (attribute addition purpose) and was searching stack overflow.
I found this solution to be very close (except it does not has a remove option plus I sincerely do not know how to retrieve the data of each textbox, but all this later).
https://jsfiddle.net/nzYAW/
The code in the fiddle works fine. But as I tried it on my local machine it fails to produce any result.
Here is what I did
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.extraPersonTemplate {display:none;}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function () {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
})
function GetHtml() {
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=firstname]')[0].name = "firstname" + len;
$html.find('[name=lastname]')[0].name = "lastname" + len;
$html.find('[name=gender]')[0].name = "gender" + len;
return $html.html();
}
</script>
</head>
<body>
<div class="extraPersonTemplate">
<div class="controls controls-row">
<input class="span3" placeholder="First Name" type="text" name="firstname">
<input class="span3" placeholder="Last Name" type="text" name="lastname">
<select class="span2" name="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div id="container"></div>
<i class="icon-plus-sign icon-white"></i> Add another family member</p>
</body>
</html>
and this is the result
Where did I go wrong at copy paste?

You need to load jQuery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You need to include jQuery. If you check your javascript console (which you definetly should) you will probably find this error:
$ is not defined
That is because jQuery wasn't loaded before you try to use it. Add this to your page before your javascript code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can see in the JSFiddle that you include these libraries, but you don't include them when you just copy paste this.
Include these javascripts
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Move the JavaScript to be right above the </body> tag.
I think if you're trying to access elements before the page has loaded them, then it won't work.
Also as other answers have pointed out, be sure you've included jQuery in the <head></head> section of your page.

Related

Javascript Input Paste registers as Undefined

I am currently writing a function that writes a bit of code for me based on an input. I am currently working on creating the input and the code that pastes the input, but whenever it writes, it shows up as undefined. This is the code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript YAML Generator</title>
</head>
<body>
<form class="yamlform" action="index.html" method="post">
<input type="text" name="appname" value="Name">
<button type="submit" onclick="writeAppName()">Submit</button>
</form>
<script type="text/javascript">
var appname = document.getElementsByName("appname").value
function writeAppName() {
document.write(appname)
}
</script>
</body>
</html>
NOTE: This is not my final version of the code, at the moment I just want a system for writing an input value that I can duplicate. Final version will be using document.getElementbyID.
document.getElementsByName returns colection. Use document.getElementsByName("appname")[0].value.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript YAML Generator</title>
</head>
<body>
<form class="yamlform" action="index.html" method="post">
<input type="text" name="appname" value="Name">
<button type="submit" onclick="writeAppName()">Submit</button>
</form>
<script type="text/javascript">
var appname = document.getElementsByName("appname")[0].value
function writeAppName() {
document.write(appname)
}
</script>
</body>
</html>
You need to refer to the first element with name "appname", because it could be a collection. Also I but the assignment for appanme variable inside of the function, this will make it so appname isn't being assigned to "Name" right away and is instead assigned to whatever is in the text box when you click the botton
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript YAML Generator</title>
</head>
<body>
<form class="yamlform" action="index.html" method="post">
<input type="text" name="appname" value="Name">
<button type="submit" onclick="writeAppName()">Submit</button>
</form>
<script type="text/javascript">
function writeAppName() {
var appname = document.getElementsByName("appname")[0].value
document.write(appname)
}
</script>
</body>
</html>
The problem is with your document.getElementsByName
It is possible that multiple elements would have same name.
While using document.getElementsByName, there might be multiple elements instead of a single element present in DOM with similar name, so document.getElementsByName returns an array (a list of elements) and not a single element
To use different elements of the Array, use
document.getElementsByName("appname")[0] // For first element with name
document.getElementsByName("appname")[1] // For second element with name
// and so on
So in your code, you would use
var appname = document.getElementsByName("appname")[0].value;

How to select an ID in Jquery for an if statement

I want to use a form selector as shown, and depending on the option selected, a different output. Simple, yet I am not getting it to work. Here is what I have.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(document).ready(function(){
if ("#1") {
$("#display").html("<table width="221"><tbody><tr class="su-even"><td width="64"><strong>Level</strong></td><td width="64"><strong>Damage</strong></td><td width="93"><strong>Crown Tower Damage</strong></td></tr><tr><td width="64">1</td><td width="64">80</td><td width="93">32</td></tr></tbody></table>");
}
if ("#2") {
$("#display").html("<table width="221"><tbody><tr class="su-even"><td width="64"><strong>Level</strong></td><td width="64"><strong>Damage</strong></td><td width="93"><strong>Crown Tower Damage</strong></td></tr><tr><td width="64">2</td><td width="64">88</td><td width="93">36</td></tr></tbody></table>");
}
});
</script>
</head>
<body>
<div>
<form id="option">
<label for="level">Level at a glance:</label>
<select name="level" id="level">
<option id="1">1</option>
<option id="2">2</option>
</select>
</form>
<div id="display">
</div>
</div>
</body>
</html>
There were a couple issues here.
First of all, "#1" and "#2" are always going to == true, since they are strings.
Second, the code that changes the text only happens once, on page load. There is nothing telling it to update after the menu is changed.
Third, on the lines starting with $("#display").html...., you had what should have been a very long string, but you broke it up by using double quotes every time. You need to switch between single and double quotes. If I say, "class="potato">", it sees "class=" as one string, and ">" as another, but it doesn't know what to do with potato. You need to use single quotes, like "class='potato'>" or 'class="potato">'.
This is the fixed code:
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
function changeText(){
if ($("#level option:selected").text() == "1") {
$("#display").html("<table width='221'><tbody><tr class='su-even'><td width='64'><strong>Level</strong></td><td width='64'><strong>Damage</strong></td><td width='93'><strong>Crown Tower Damage</strong></td></tr><tr><td width='64'>1</td><td width='64'>80</td><td width='93'>32</td></tr></tbody></table>");
}
if ($("#level option:selected").text() == "2") {
$("#display").html("<table width='221'><tbody><tr class='su-even'><td width='64'><strong>Level</strong></td><td width='64'><strong>Damage</strong></td><td width='93'><strong>Crown Tower Damage</strong></td></tr><tr><td width='64'>2</td><td width='64'>88</td><td width='93'>36</td></tr></tbody></table>");
}
}
$(document).ready(function(){
changeText();
});
</script>
</head>
<body>
<div>
<form id="option">
<label for="level">Level at a glance:</label>
<select name="level" id="level" onchange="changeText()">
<option id="1" >1</option>
<option id="2">2</option>
</select>
</form>
<div id="display">
</div>
</div>
</body>
Your javascript conditions are executed once, when the document is ready.
You have to add an event, when the select value change !
Add some values in your option elements ( <option value="1">1</option> )
$(document).ready(function(){
// Set event
$("#level").change(function(){
if ($(this).val() === "1") {
$("#display").html(...);
} else {
$("#display").html(...);
}
}
// Call event when document loaded
$("#level").change();
});

populate a HTML select in form using Javascript

I have a problem by populating a HTML select.
This select is in an form that first is loaded into a div. (see the code below)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" />
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function createForm(){
$("#formdiv").load("Register.html");
var itemval= '<option value="OT">OT</option>';
document.getElementById("sel").appendChild(itemval);
}
function validateForm(){
// ...
}
</script>
</head>
<body onload="createForm()">
<div id="formdiv" >
// here will be the form
</div>
</body>
The Register.html is a simple form
<h2>Register</h2>
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
The function createForm() should populate, here as a first test, the select tags. But unfortunately it does not show any option in the browser.
Hope some of you are more experienced than I and can hint me to the solution.
Thanks in advance!
Here the problem is that you use appendChild with a String,
you should use innerHTML to insert a string, or of you want to append
do createElement and then append, appendChild accepts Node as a parameter,
in your case its better use add() method on select
http://www.w3schools.com/jsref/met_select_add.asp
<script type="text/javascript">
function createForm() {
var option = document.createElement("option");
option.text = "OT";
option.value = "OT";
document.getElementById("sel").add(option);
}
function validateForm() {
// ...
}
</script>
<div id="formdiv">
<form name="registerForm" id="registerForm" onsubmit="validateForm()">
Select:
<select name="sel" id="sel"></select>
<input type="submit" value="Submit">
</form>
</div>
<h2>Register</h2>
See jsfiffle link: http://jsfiddle.net/qgfbhgwd/
with a working example
You have 2 mistakes:
Use jQuery load function because is async so you are creating the content before loading the file register.html
appendChild needs a DOM Element instead of a string
This code fix your problem, hope it helps:
function createForm(){
var populateSelect = function() {
var itemsValues = ['OT', 'FOO', 'BAR'];
var items = document.createDocumentFragment();
itemsValues.forEach(function(el) {
var option = document.createElement("option");
option.value = el;
option.innerHTML = el;
items.appendChild(option);
});
document.getElementById("sel").appendChild(items);
};
$("#formdiv").load("register.html", populateSelect);
}
You can't add <option value="OT">OT</option> directly as appendChild, so use javascript createElement and always better to write a callback function for jquery load() to manipulate DOM.
function createForm() {
$("#formdiv").load("Register.html", function () {
//var itemval = '<option value="OT">OT</option>';
var itemval = document.createElement("option");
itemval.setAttribute("value", "OT");
itemval.innerText = "OT";
document.getElementById("sel").appendChild(itemval);
});
}

javascript works in Chrome does not work in IE

In Chrome browser, when you click on CloudCover on this web page, a description is revealed below. In IE the description is not revealed. Any suggestions to make this work in IE?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>min test</title>
<script type='text/javascript'>
function showDescription (sel) {
var myVarDescip, myVarTEXT;
var myVar = (sel.value);
document.getElementById('putDescriptionHere').innerHTML = "";
myVarDescip = (myVar + "Descrip");
myVarTEXT = document.getElementById(myVarDescip).innerHTML;
document.getElementById('putDescriptionHere').innerHTML = myVarTEXT;
}
</script>
</head>
<body>
<select id="destSelect" size="3" multiple="multiple">
<option value="CloudCover" onclick="showDescription(this);">Cloud Cover</option>
</select>
<div id="CloudCoverDescrip" style="display: none">
<b>Cloud Cover:</b> The percentage of sky occluded by clouds.
</div>
<div id="putDescriptionHere"></div>
</body>
</html>
You can't attach mouse events on options in IE, so the click never fires.
Use the onchange event on the select instead
<select id="destSelect" size="3" multiple="multiple" onchange="showDescription(this);">
FIDDLE

changing color by javascript function

In the following code , I have a javascript function and I am tring to change the backgroundColor of the page to a color passed in as a parameter. But my code doesn't work, can anybody help me what is wrong in my code?
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Changing Color</title>
<head>
<style type="text/css">
body {
background-color:#ffcccc;
}
</style>
</head>
<body>
<form>
<label>color: <input type="text" name="color"> </label>
<input name="color" type = "button" onClick = "changecolor(color.value) " value = "color">
</form>
</body>
</html>
Javascript:
function changecolor(colour)
{
document.bgcolor=colour;
}
Assuming colour contains a valid CSS color descriptor, you can write:
document.body.style.backgroundColor = colour;
you have to put the function in a script block.
...
</form>
<script type="text/javascript>
//function declaration
</script>
Try this code it works finely man .i have just tried it.you can use it where-ever you want.also appended the code for onmouse click and onmouseover.
<html>
<head>
<script language="javaScript">
function change_background(color){
document.bgColor = color;
}
</script>
</head>
<body>
<form>
<label>color: <input type="text" name="color" >
</label>
<input name="clrs" type ="button" value="getcolor" onClick = "change_background(color.value) " >
</form>
ClickBlue
Mouseoverblack
Mouseover white
</body>
</html>`

Categories

Resources