I'm creating a form and would like to be able to duplicate certain DIVs as needed using javascript. However, I need to replace multiple instances of a certain piece of text. Something like this with the comment replaced by functional code:
<body>
<div id="duplicate">
<p>Section_1 of form</p>
Add A Section
</div>
<script type="text/javascript">
<!--
var num_sections = 1;
function add_section()
{
var orig_div=document.getElementById("duplicate")
var copy_div=orig_div.cloneNode(true);
//Change every "Section_1" in copy_div to "Section_"+num_sections
footer = document.getElementById("footer");
document.body.insertBefore(copy_div,footer);
}
//-->
</script>
<div id="footer"></div>
</body>
Using JavaScript, what is an elegant way to replace every instance of Section_1 when these instances are in every input tag within the section ?
I'm working within the confines of a CMS so I can't implement it using a more powerful processing language.
You can call getElementsByTagName on a DOM node to fetch some elements group identified by the tag.
var num_sections = 1;
window.add_section = function() {
var orig_div=document.getElementById("duplicate")
var copy_div=orig_div.cloneNode(true);
//Change every "Section_1" in copy_div to "Section_"+num_sections
num_sections++;
var p = copy_div.getElementsByTagName('p')[0];
p.innerHTML = p.innerHTML.replace('Section_1', 'Section_' + num_sections);
var footer = document.getElementById("footer");
document.body.insertBefore(copy_div,footer);
};
Here's jsFiddle
Related
So I am creating a table through javascript,
Part of my assignment says: "the output div should only contain the table of the most recent call"
It is a class where we don't talk too much syntax and I am new to web development and javascript.
I have this function and it works:
<body>
<div id="output"></div>
<script type="text/javascript">
var functionCreate = function(strInput) {
var dividedArray = strInput.split("\n");
var dLength = dividedArray.length;
var myRow, myCell;
var myNewTable = document.createElement('table');
myNewTable.border = "1"
for(var i = 0; i< dLength; i++){
if(dividedArray[i].length >0){
myRow = myNewTable.insertRow(-1);//here
for(var j = 0; j<dividedArray[i].length;j++){
if(dividedArray[i][j] != ','){
myCell = myRow.insertCell(-1); //here
myCell.innerHTML = dividedArray[i][j]
}
}
}
}
document.getElementById("output").appendChild(myNewTable);
};
</script>
</body>
When its called one time, it does what it is supposed to do. When it is called twice, I get two tables, naturally(?)
However I have no idea how to only use the table from last call . I have no access to where it is being called. Can anyone direct me towards the right direction? What is the most basic and straight forward approach that I should take to implement this?
The reason why your code is adding new tables is due to the line of code here:
document.getElementById("output").appendChild(myNewTable);
The function appendChild appends (adds) a child (myNewTable) to the end of the element of id output.
So when u run the function multiple times, it just keeps adding a newly created myNewTable element to the output div.
To make sure it only appends the latest table, clear the output div with something like document.getElementById('output').innerHTML = ""; at the beginning of your function
I'd like to use Javascript (on page load) to remove the wording 'Choose a currency to display the price:'.
Leaving just the currency icons in the box (Div id = currency-switch).
How can I do this?
Page url: http://www.workbooks.com/pricing-page
Image example:
You can remove this text with for example:
window.onload = function(){
var el = document.getElementById("currency-switch");
var child = el.childNodes[0];
el.removeChild(child);
};
If you want to keep it stupid simple just add an span around the text and give it an id like "currency_text".
Then you only need this code:
var elem = document.getElementByid("currency_text");
elem.remove();
Try
$(document).ready(function() {
var currencyDiv = $('#currency-switch');
currencyDiv.innerHTML(currencyDiv.innerHTML().replace("Choose a currency to display the price:", ""));
}
This will remove the text as soon as the DOM is ready.
Please see below which will just remove the text:
This will trigger on page load
<script>
// self executing function here
(function() {
var selected_div = document.getElementById('currency-switch');
var text_to_change = selected_div.childNodes[0];
text_to_change.nodeValue = '';
})();
</script>
Since it's a text node, you could do the following in jQuery. This will be triggered on DOM ready.
$(function() {
jQuery("#currency-switch").contents()
.filter(function() {
return this.nodeType === 3;
}).remove();
});
You can use this code:
var requiredContent = document.getElementById('currency-switch').innerHTML.split(':')[1];
document.getElementById('currency-switch').innerHTML = requiredContent;
See it working here: https://jsfiddle.net/eg4hpg4z/
However, it is not very clean, but should work, if you cant directly modify the html.
A better solution would be to modify your code to move the text content within a span and show hide the text like so:
HTML:
<div id="currency-switch">
<span class="currency-label">Choose a currency to display the price: </span>
<span class="gb-background"><span class="GB"> £ </span></span><span class="es-background"><span class="ES"> € </span></span><span class="au-background"><span class="AU"> $ </span></span></div>
Javascript:
document.getElementsByClassName('currency-label')[0].style.display = 'none';
This is a follow up to this question:
How to replace DOM element in place using Javascript?
I wasn't the OP but I am facing a similar situation. The initial question was "how to replace an anchor element with a span using Javascript. The answer that was given (thank you Bjorn Tipling ) was to use replaceChild(), with the following example:
<html>
<head>
</head>
<body>
<div>
<a id="myAnchor" href="http://www.stackoverflow">StackOverflow</a>
</div>
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.innerHTML = "replaced anchor!";
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>
My follow up is: how to add / insert an id (e.g., "xyz")and a function (e.g., onmouseout='doWhatever(this)') to the replaced DOM element?
You can add an id property by simply setting it:
mySpan.id = "xyz";
And you can attach an event like so:
mySpan.onmouseout = function() {
doWhatever(this);
}
I would avoid setting event attributes when dynamically creating DOM elements. Assigning the event handlers programmatically is the right way to go.
mySpan.id = "abcd123";
mySpan.onclick = function () { console.log(this.id + " was clicked"); };
Once you have your HTML element cached to a variable, you can just keep using that variable to work with it.
Use this:
<script type="text/JavaScript">
var myAnchor = document.getElementById("myAnchor");
var mySpan = document.createElement("span");
mySpan.appendChild(document.createTextNode("replaced anchor!"));
mySpan.id = "xyz";
mySpan.onmouseout = function() {
doWhatever(this);
};
myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
I am trying to insert two consecutive spans into an editable body element on Chrome. My problem is that the 2nd span is ending up inside the first span instead of next to it.
I have simplified my example, but in real life, the end user might have moved the cursor or selected some text in between the two inserts.
<html>
<head>
<script>
function load(){
insert("<span style='color:red'>hello</span>");
insert("<span>goodbye</span>");
}
function insert(sHtml){
var oSel = window.getSelection();
var oRange = oSel.rangeCount > 0 ? oSel.getRangeAt(0) : void 0;
if(!oRange){
oRange = window.document.createRange();
oRange.selectNodeContents(window.document.body);
}
var newFrag = oRange.createContextualFragment(sHtml);
oRange.insertNode(newFrag);
oRange.collapse(false);
oSel.removeAllRanges()
oSel.addRange(oRange);
}
</script>
</head>
<body onload="load()">
</body>
</html>
You're doing strange and complex things to insert your nodes. Why using the selection ?
Using jquery, you could define your insert function like this :
function insert(html) {
$("body").append(html);
}
Without jquery, you would have to add the node and set a text in the node :
var newNode = document.createElement("span");
newNode.setAttribute("style", "color:red");
newNode.appendChild(document.createTextNode("hello"));
document.body.append(newNode);
For example if i have a list item like all,a,b,c,d. if i click all means it should not allow to choose other items, if i am not choosing all means it should allow to choose mulitle item from list
<script type="text/javascript">
var creatLimit = 5;
var fCount = 0;
function addFileElement()
{
if(fCount < creatLimit)
{
var fObject = document.getElementById("name");
var addButton = document.createElement("select");
addButton.type = "select";
addButton.name = "List["+fCount+"]";
addButton.setAttribute("class", "normal");
addButton.style.width = "250px";
addButton.onkeydown = function(){
blur();
};
var o2 = document.createElement("br");
var o3 = document.createElement("br");
fObject.appendChild(addButton);
fObject.appendChild(o2);
fObject.appendChild(o3);
fCount++;
}
}
</script>
You are confusing your terminologies here slightly - JavaScript itself doesn't show any UI, it is the HTML (or the XUL or something completely different) which shows the UI.
Assuming that you are talking about html, the way to create a drop down list is simply to write the corresponding html for the drop down list to wherever it is in the document that you wish the drop down list to be placed, for example:
<div id="myDiv"></div>
<script type="text/javascript">
myDiv = document.getElementById("myDiv");
myDiv.innerHtml = "<select><option>a</option><option>b</option><option>c</option><option>d</option>";
</script>
Most likely you will be dynamically writing the HTML based on an existing list of items, but I don't want to go into that in too much detail because that will completely depend on your specific requirements and because jQuery will make this a lot easier.
EDIT: Typo fix in variable names.