Javascript Complete Amateur? - javascript

I have a javascript function I wrote to append a select box to a radiobutton set based on which radio button is clicked. It does this when one clicks one or the other. The problem is, I'm such an amateur that I can't get it to stop adding new select elements to the span I set to place them in. I keep trying different ways to check if the element or its innerHtml have been set and then use that check to decide whether to create another select. None of this has worked for me. Can anyone point me in the direction of a tutorial for this (i've been searching, tried nearly everything, no fez which makes me think its a simpler problem with the structure of the whole function).
Here is the code, any light shed on this would be SUPER helpful. I just taught myself to code so I know this is horrible. Thanks for the help!!
function moreInput(vInput) {
var moreD = document.getElementById('moreD');
//document.write(moreD);
if(vInput == \"approved\") {
if(moreD.length > 0) {
moreD.removeChild(approvedOpts);
}
var select = document.createElement(\"select\");
select.options[0] = new Option('a');
select.options[1] = new Option('b');
select.options[2] = new Option('c');
select.setAttribute(\"name\",\"approvedOptsA\");
}
if(vInput == \"denied\") {
//alert(moreD.innerHtml);
//if(moreD.innerHtml === 'undefined') {
//moreD.removeChild(approvedOptsD);
var select = document.createElement(\"select\");
select.options[0] = new Option('x');
select.options[1] = new Option('y');
select.options[2] = new Option('z');
select.setAttribute(\"id\",\"approvedOptsD\");
select.
//}
}
moreD.appendChild(select);
}

Remove all elements before you add any new elements.
This code should work:
<script type=\"text/javascript\">
function moreInput(vInput) {
var moreD = document.getElementById('moreD');
if(vInput == \"approved\") {
removeAllChildrens(moreD);
var select = document.createElement(\"select\");
select.options[0] = new Option('Comped Table');
select.options[1] = new Option('Comped Drink');
select.options[2] = new Option('Comped Cover');
select.setAttribute(\"name\",\"approvedOptsA\");
}
if(vInput == \"denied\") {
removeAllChildrens(moreD);
var select = document.createElement(\"select\");
select.options[0] = new Option('Need to Reserve Table');
select.options[1] = new Option('At Capacity');
select.options[2] = new Option('Private Event');
select.setAttribute(\"id\",\"approvedOptsD\");
}
moreD.appendChild(select);
}
function removeAllChildrens(cell) {
if ( cell.hasChildNodes() ) {
while ( cell.childNodes.length >= 1 ) {
cell.removeChild( cell.firstChild );
}
}
}
</script>

You only ever append new selects, you need to delete the old one before appending a new one. Try the below code (I've removed your commented lines):
function moreInput(vInput) {
var moreD = document.getElementById('moreD');
if(vInput == "approved") {
if(moreD.length > 0) {
moreD.removeChild(approvedOpts);
}
var select = document.createElement("select");
select.options[0] = new Option('a');
select.options[1] = new Option('b');
select.options[2] = new Option('c');
select.setAttribute("name","approvedOptsA");
}
if(vInput == "denied") {
var select = document.createElement("select");
select.options[0] = new Option('x');
select.options[1] = new Option('y');
select.options[2] = new Option('z');
select.setAttribute("id","approvedOptsD");
}
moreD.removeChild(document.getElementById("approvedOptsD"));
moreD.removeChild(document.getElementById("approvedOptsA"));
moreD.appendChild(select);
It may throw some warnings, I haven't tested it but you should get the idea of what you are looking for.
This is and old but still accurate and useful article on adding and removing dom nodes dynamically with javascript.

Related

Get option value of dynamically added options

Here the code which creates options for select tag, i wanted the option value on change the option, i have tried almost everything that i can put in it, but no luck
i can't even see the "selected" attribute in options, i have added the picture of html structure & code. Please share your thoughts on this. Thanks.
Here is the fiddle - https://jsfiddle.net/pa8e47nx/1/
Product.Config.prototype.loadOptions = function() {
this.settings.each(function(element){
element.disabled = false;
element.options[0] = new Option(this.config.chooseText, '');
var attributeId = element.id.replace(/[a-z]*/, '');
var options = this.getAttributeOptions(attributeId);
if(options) {
var index = 1;
for(var i=0;i<options.length;i++){
options[i].allowedProducts = options[i].products.clone();
element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
if (typeof options[i].price != 'undefined') {
element.options[index].setAttribute('price', options[i].price);
}
element.options[index].setAttribute('data-label', options[i].label.toLowerCase());
element.options[index].config = options[i];
index++;
}
}
this.reloadOptionLabels(element);
}.bind(this));
},

Making dynamically added p elements clickable

I am trying to make the elements clickable. However on clicking any of the <p> elements there is no alert box saying "hello". Please could you look at my code and possibly point me in the right direction?
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
a.onclick = function(e) {
e.preventDefault();
alert("hello");
};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
var txtFile8 = new XMLHttpRequest();
txtFile8.open("GET", "http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt", true);
txtFile8.onreadystatechange = function() {
if (txtFile8.readyState === 4) { // Makes sure the document is ready to parse.
if ((txtFile8.status == 200) || (txtFile8.status == 0)) { // Makes sure it's found the file.
allText8 = txtFile8.responseText;
arrayOfLines8 = allText8.match(/[^\r\n]+/g);
for (i = 0; i < arrayOfLines8.length - 1; i++) {
createLink(arrayOfLines8[i], document.getElementById("previousResultsList"));
}
}
}
};
txtFile8.send(null);
The script parses a text file online:
http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt
Which is updated weekly and has dates written in it like so:
19/04/16
12/04/16
...
My script separates the text document into each line and stores it as an array. A for loop is then used to show the dates on the screen in a column which looks like so:
The problem is that on clicking each date an alert box is not shown saying "hello" and there seems to be no response at all.
All help is greatly appreciated.
I solved the issue!!
The problem was that I had divs with opacity 0 that were overlaying my parentElement! sorry stupid mistake!

Auto type inside text input

I would like to let there automatically appear text inside an input type=text element.
I would like to accomplish that the different kind of texts are stored inside an array and that every 5 seconds or so, a text is 'typed' by javascript into this field. Then I also like that when I focus on the field (to input text in it by keyboard) that it stops auto-typing and shows an empty input element.
Anybody know how to go about this?
I'm a back-end programmer, but need to do some frontend programming and just haven't had the time to thoroughly learn Javascript. At the moment I only know PHP thoroughly, but would expand my knowledge to css, html and javascript too.
Hope somebody is able to help me out :)
EDIT: This is the solution I came up with and it works. The input field has as ID: searchBar. The code is not very elegant, but I'm still learning :) Thanks for the answers. It helped me a lot.
var searchBar = document.getElementById('searchBar');
var keywords = ['Auto typed text number 1',
'This is number 2 auto typed',
'Yet another auto typed line',
'The last line before it loops again'];
var index = 0;
var arrCounter = 0;
var focus = false;
var timer1, timer2;
function resetBox() {
searchBar.value = '';
index = 0;
autoType();
}
var autoType = function() {
if (focus) {
return;
}
if (index <= keywords[arrCounter].length) {
searchBar.value = keywords[arrCounter].substr(0, index++);
timer1 = setTimeout("autoType()", 50);
} else {
arrCounter++;
if(arrCounter === keywords.length){
arrCounter = 0;
}
timer2 = setTimeout(resetBox, 5000);
}
};
autoType();
$("#searchBar").on("focus", function(){
focus = true;
searchBar.value = '';
clearTimeout(timer1);
clearTimeout(timer2);
}).on("blur", function(){
setTimeout(function() {
focus = false;
resetBox();
}, 1000);
});
Try like this:
html
<input id='demo_input' size='100'/>
javascript:
var demo_input = document.getElementById('demo_input');
var type_this = "try this example";
var index = 0;
window.next_letter = function() {
if (index <= type_this.length) {
demo_input.value = type_this.substr(0, index++);
setTimeout("next_letter()", 50);
}
}
next_letter();

Javascript - strikethrough

i try to make text strikethrough with javascript.
I know nothing about Javascript and try to search on the net how to that.
<script language="JavaScript">
function recal(val,sum)
{
if(sum == true)
{
var total = parseInt(document.getElementById("total").innerHTML, 10);
total+=val;
document.getElementById("total").innerHTML=total;
}
else
{
var total = parseInt(document.getElementById("total").innerHTML, 10);
total-=val;
document.getElementById("total").innerHTML=total;
var pnl = document.getElementById("totalEvents");
}
var pnl = document.getElementById("totalEvents");
var pnl2 = document.getElementById("eventCategory");
var pnl3 = document.getElementById("nameID");
**strikethrough starts here**
if (!sum && pnl.firstChild.tagName != "S" && pnl2.firstChild.tagname !="S")
{
pnl.innerHTML = "<S>"+ pnl.innerHTML+"</S>";
pnl2.innerHTML = "<S>"+ pnl2.innerHTML+"</S>";
}
else
{
pnl.innerHTML = pnl.firstChild.innerHTML;
pnl2.innerHTML = pnl2.firstChild.innerHTML;
}
}
</script>
it makes textstrikethrough but something is wrong. Even if i choose second checkbox it affects first checkbox why :(
http://jsfiddle.net/aHH9w/ (my full html page)
You are peforming a pretty convoluted way of achieving this, something that can actually be quite easily done. If you have an HTML element, say with the id 'myelement':
<div id="myelement">Hello world</div>
To create a strikethrough, all you need to do in JS is:
var ele = document.getElementById("myelement");
ele.style.setProperty("text-decoration", "line-through");
If you need to check if there is a strikethrough on an element:
var ele = document.getElementById("myelement");
var isStruck = (ele.style.getProperty("text-decoration") == "line-through");
Although this is not really recommended. Use an internal variable to keep track of state.

Javascript failing because the dom has been altered?

These two javascript functions work perfectly on unaltered dom elements. However the delete_route function fails when asked to delete elements appended to the dom via the second function. For clarity, I am only looking at elements where parts[0] is always option - it is created by spliting the a > id on the "_".
Why is Javascript apparently seeing this difference between "native" dom objects and inserted objects?
//handle delete events
function delete_route (parts) {
if (parts[0] == "field") {
var select_container = "container_"+parts[2];
var getContainer = document.getElementById(select_container);
getContainer.parentNode.removeChild(getContainer);
} else if (parts[0] == "option") {
var optionId = parts[0]+"_"+parts[2]+"_"+parts[3];
var getOption = document.getElementById(optionId);
getOption.parentNode.removeChild(getOption);
}
}
//handle new events
function new_route (parts) {
var highest_number = -1;
if (parts[0] == "field") {
} else if (parts[0] == "option") {
var selectContainer = "container_"+parts[2];
var thisContainer = document.getElementById(selectContainer);
//get last option id (for new object tagging)
var optionList = thisContainer.getElementsByTagName("input");
var optionListLength = optionList.length -2;
//more accurate new node placement than last option which didn't work correctly anyway
lastChild = "options_wrapper_"+parts[2];
var lastChildNode = document.getElementById(lastChild);
//generate option
var labelNode = document.createElement ("label");
var inputNode = document.createElement ("input");
var linkNode = document.createElement ("a");
var breakNode = document.createElement ("br");
inputNode.setAttribute("type", "text");
var inputNodeId = parts[0]+"_"+parts[2]+"_"+optionListLength;
inputNode.setAttribute("id", inputNodeId);
inputNode.setAttribute("name", inputNodeId);
inputNode.setAttribute("value", "Undefined");
labelNode.setAttribute ("for", inputNodeId);
var labelNodeText = document.createTextNode ("Option Value");
linkNode.setAttribute("href", "#");
var linkId = parts[0]+"_delete_"+parts[2]+"_"+optionListLength;
linkNode.setAttribute("id", linkId);
var linkNodeText = document.createTextNode ("Delete option");
lastChildNode.appendChild (labelNode);
labelNode.appendChild (labelNodeText);
lastChildNode.appendChild (inputNode);
lastChildNode.appendChild (linkNode);
linkNode.appendChild (linkNodeText);
lastChildNode.appendChild (breakNode);
}
}
HTML this applies to (I have gone though some effort with the creating part - options that were inserted by javascript are exactly indentical to "native" page elements):
<div id="options_wrapper_7">
<label for="option_7_0">Option Value</label><input type=text id="option_7_0" name="option_7_0" value="Red"> <a id="option_delete_7_0" href="#">Delete option</a><br>
<label for="option_7_1">Option Value</label><input type=text id="option_7_1" name="option_7_1" value="Green"><a id="option_delete_7_1" href="#">Delete option</a><br>
<label for="option_7_2">Option Value</label><input type=text id="option_7_2" name="option_7_2" value="Blue"><a id="option_delete_7_2" href="#">Delete option</a><br>
</div>
Based on the code from your previous questions, you're assigning event handlers at window.onload by calling the clickDetection() function.
I assume when you've created new elements, you haven't bothered to give those new elements the same event handlers that your initial clickDetection() does.
If that's the case, you'll need to be sure that those new elements get handlers that can respond to clicks.
// make a separate reference to the handler so we can use it
// for elements that are created later.
function clickHandler() {
clickRoute(this);
return false
};
function clickDetection() {
var canvas = document.getElementById("content");
var dumbLinks = canvas.getElementsByTagName("a");
for (var i = 0; i < dumbLinks.length; i++) {
// Assign the "clickHandler" when the page loads
dumbLinks[i].onclick = clickHandler;
}
}
Then in your new_route function, manually assign clickHandler to the new <a> element.
function new_route (parts) {
var highest_number = -1;
if (parts[0] == "field") {
} else if (parts[0] == "option") {
var selectContainer = "container_"+parts[2];
var thisContainer = document.getElementById(selectContainer);
//get last option id (for new object tagging)
var optionList = thisContainer.getElementsByTagName("input");
var optionListLength = optionList.length -2;
//more accurate new node placement than last option which didn't work correctly anyway
lastChild = "options_wrapper_"+parts[2];
var lastChildNode = document.getElementById(lastChild);
//generate option
var labelNode = document.createElement ("label");
var inputNode = document.createElement ("input");
var linkNode = document.createElement ("a");
var breakNode = document.createElement ("br");
// ********RIGHT HERE*********
// Assign the handler to the new "linkNode" element
linkNode.onclick = clickHandler;
// ...and so on with the rest of the code...
}

Categories

Resources