http://jsfiddle.net/HKhw8/67/
HTML:
<p>You can see this text... <span id="text"></span></p>
<p>...but not this: <span id="mathStuffs"></span></p>
<p>Number variables don't seem to show, either- <span id="num"></span></p>
JavaScript:
var text = 'Hello'
var i = 50;
document.getElementById('text').innerHTML = text;
document.getElementById('mathStuffs').innerHTML = math.pow(5,2);
document.getElementById('number').innerHTML = i;
The code doesn't show up in the preview like some of the nicely color-coded syntax highlighting like I've seen in previous posts- sorry about that.
I originally thought that console.log() was the problem, so I have this example set up. Regular text variables show up, but I can't seem to get the numbers or functions that return numbers to appear. Is there something I'm doing wrong? I've tried fiddling with the No wrap - in setting, but I can't understand. I've tried Chrome and FF.
math is not a class of javascript it should be Math
document.getElementById('mathStuffs').innerHTML = Math.pow(5,2);
Also one of the reference of a div is wrong
document.getElementById('number').innerHTML = i;
it should be num
document.getElementById('num').innerHTML = i;
Related
I need advice on how I can create dynamic line breaks ideally with an <li> inside TINY. I have tried using an each loop and also a for loop, and the values just do not appear in the text area. BUT, if I just add them to the text area with a val() they go in fine, BUT as just one long string.
The text area has an id of wo_materials. I'm successfully getting my text into Tiny like this:
$('#wo_materials').val(materials);
tinymce.init({
selector:'textarea'
});
And I get a nice row of text values:
The materials value is an array. If I look at it in the console it looks like this:
0: BP #15 Plain Felt 36"
1: Duraflo Weatherpro 50
2: 1 1/4 Coil Nails - box
Thanks !
If you're only modifying the value of the text area before tinymce is initialized then this might work for you:
$('#wo_materials).val(materials.join('<br/>'));
This works. The secret is adding the incrementing var "text" to the for loop and then wrapping the object / array in an <li>
var materials= JSON.parse(localStorage.getItem('materials'));
var text=" ";
materials.length;
function workorders(){
for (i = 0; i < materials.length; i++) {
text += "<li>"+materials[i]+"</li>";
}
$('#wo_materials').val("<li>"+text+"</li>");
}
workorders();
I'm tinkering with making a WYSIWYG editor. And yes, I'm fully aware of execCommand(), but I don't like how messy, and inconsistent it can get.
Note: This is not a question of how to get it to work, as other questions are, but rather how to keep the end result clean.
The next best option seems to be window.getSelection(), which works great, until I hit a situation like this:
<p id="para" contenteditable="true">
A bit of <b>a</b> <span class="blackColor">lon</span><i>ger</i> sentence.
</p>
Which to the user gives
A bit of a longer sentence
So, this is what I've come up with, so far to bold something:
function bold(){
var box = document.getElementById("para");
var sel = window.getSelection();
if(sel.rangeCount < 1) return;
var range = sel.getRangeAt(0);
if(!validSelection(range.startContainer, box) || !validSelection(range.endContainer, box)){
return;
}
// Get what we need from the first element
var data = range.extractContents();
for(var i = 0; i < data.childNodes.length; ++i){
var b = document.createElement('b');
b.innerHTML = data.childNodes[0].textContent;
data.appendChild(b);
data.removeChild(data.firstChild);
}
range.extractContents();
range.insertNode(data);
}
It works, but it can get messy, very, very fast.
<p id="para" contenteditable="true">
A <b>b</b><b>it</b><b></b> of <b>a</b> <span class="blackColor">lon</span><i>ger</i> sentence.
</p>
That's after calling bold() for "it" and then "bit".
If I call it over multiple elements, such as, "of a long"
<p id="para" contenteditable="true">
A bit <b>of </b><b>a</b><b> </b><b>lon</b><b>g</b><i>er</i> sentence.
</p>
That's seems much worse than execCommand(), but I'd still like to do this in a clean manner. What is the proper way to do this to where I won't have extremely messy code once all is said and done? Also, I do realize that other formatting has been lost from the original. Something I'm working on, but my main thing is keeping it clean right now.
I've noticed in the inspector that if I hit [Ctrl] + B, and and then undo, things break up into multiple text nodes, but stay not-so-messy in the actual code. However, that only works for bold, italics, and underline, and I'd like to implement a few more things.
As an end note, I am open to just cleaning up execCommand(), but if I can instead code it myself... well... I like coding. :)
Thanks.
We were given an assignment to basically make a Madlib by having the user enter words into textfields and then replacing words in a hidden paragraph existing in the html page. We have to use JavaScript and CSS.
the paragraph in the html page:
<span id="story" display="hidden">
Rain was still lashing the windows, which were now <span id="adjs1">__adjective__</span>, but inside all looked bright and cheerful. The firelight glowed over
the countless <span id="adjs2">___adjective___</span> <span id="plnouns">___plural_noun___</span> where people sat <span id="verbs1">___verb_with_ing___</span>
, talking, doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a <span id="foods">___food___</span> to a
<span id="monsters1">___monster___</span>. Fred had "rescued" the <span id="adjs3">___adjective___</span>, fire-dwelling <span id="monsters2">___monster___</
span> from a Care of Magical Creatures class and it was now<span id="verbs2">___verb_with_ing___</span> gently on a table surrounded by a knot of curious peopl.
</span>
Everything was going fine till I keep missing on getting the results I want.
function generateMadlib(){
// Display the story. The story is initially hidden.
document.getElementById("story").style.display = "inline";
// Get the words from the textboxes.
var formElements = $("#madlibForm :text");
// Find the word locations on the hidden paragraph.
var storyWords = $("#story span");
// Replace word loc values with with formElement values
for (var i = 0; i < formElements.length; i++)
{
storyWords.eq(i).innerHTML = formElements.eq(i).val();
}
}
This line
storyWords.eq(i).innerHTML = formElements.eq(i).val();
doesn't change the values inside the spans within the paragraph. (the code returns the proper input on the textfields)
I also tried using the browser console and manually changing document.getElementById("adjs1").innerHTML = "test"; it will return "test" but the value doesn't actually change. Can anyone clarify what .innerHTML actually does?
.eq(i) returns a jQuery object so it don't have the innerHTML property, so you can use .html() to set the html content
storyWords.eq(i).html(formElements.eq(i).val())
or you can use .get() which will return a dom element reference
storyWords.get(i).innerHTML = formElements.eq(i).val();
But you can simplify the overall implementation like
function generateMadlib() {
// Display the story. The story is initially hidden.
$("#story").css('display', "inline");
// Get the words from the textboxes.
var formElements = $("#madlibForm :text");
$("#story span").html(function (idx) {
return formElements.eq(idx).val();
})
}
I was able to get the highlighted text out of a textarea by recording onselect and storing the beginning and end each time. Then, when I click a button, I build the substring myself. Isn't there a simpler way of simply querying the selection?
I was kind of expecting that there would be methods in html5 dom for all these things, something like:
textarea.getSelectedStart()
textarea.getSelectedEnd();
textArea.setSelected(start,end);
Also, is there a way of programmatically deselecting text in a textarea?
I am putting in code based on the first solution below. This sort of works, but has a weird problem:
<script language=javascript>
function replaceCLOZE(code, questionType) {
var v = code.value;
var s = code.selectionStart;
var e = code.selectionEnd;
var t = v.substr(s, e-s);
var rep = "{:" + questionType + ":="+t+"}";
code.value = v.substr(0,s) + rep + v.substr(e,v.length-e+1);
}
function shortAnswer(code) {
replaceCLOZE(code, "SA");
}
function shortAnswerCaseSensitive(code) {
replaceCLOZE(code, "SAC");
}
function multipleChoice(code) {
replaceCLOZE(code, "MC");
}
The text area does in fact have attributes code.selectionStart and code.selectionEnd. But the code above, which now works, sets the highlighted text on the screen to be the first word in the textarea. Mind you, the selectionStart is still correct, but what is actually highlighted in Firefox is wrong.
In Chrome it works fine. Maybe this is just a bug in firefox or is there something else which should be done to properly update the textarea visually?
Following is simple way to get selected text of textarea of html. Still not clear what you want as following method simply will give you selected text in alert.
<html><head>
<script>
function alertme(){
var textarea = document.getElementById("textArea");
var selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);
alert (selection);
}
</script>
</head>
<body>
<p><textarea class="noscrollbars" id="textArea"></textarea></p>
<button onclick="alertme()">Click me</button>
</body></html>
When you select text, the button will alert you what you have selected. selectionStart gives you starting point and selectionEnd gives you end point, while substring needs three arguments string, starting point and ending point.
Well, just like my title says.
Is it possible to search through a whole page's HTML/CSS, and then replacing certain strings using JavaScript?
I tried to make something on my own but I'm doing it wrong.
var i, sig = document.getElementsByClassName('signaturecontainer');
for (i = 0; i < sig.length; i++)
{
var str = sig[i].innerHTML;
var n = str.replace(/< div style='250px;overflow:scroll;'/g, "< div > style='height:100%'");
}
Why I want to replace the string instead of using .innerHTML and just editing is due to that the div I want to change does not have an ID/Class.
This is what the line(s) I need changed:
<!-- edit note -->
<blockquote class="postcontent lastedited">
Last edited by X; Today at <span class="time">06:32 AM</span>.
</blockquote>
<!-- / edit note -->
<div style="height:250px;overflow: auto;"> // <--- This one.
<blockquote class="signature restore"><div class="signaturecontainer">text here</div></blockquote>
</div>
</div>
This line will give trouble:
var new = str.replace(/< div style='250px;overflow:scroll;'/g, "< div > style='height:100%'");
new is a reserved word. Change it to newstr, or whatever.
Your regex pattern is unlikely to find anything: what it's searching for is not valid CSS
The string you want to insert is not valid HTML/CSS. It should probably be <div style='height:100%;'>
It occurs to me that if you're just tweaking the styling then this is a clumsy way to go. You can change the styling directly with Javascript.
var i, sig = document.getElementsByClassName('signaturecontainer');
for (i = 0; i < sig.length; i++)
{
sig[i].parentNode.style.height = "100%";
}
We'll no it is not impossible, with JavaScript you can parse an HTML document by locating the tags is that you are trying to change. For example
<div id="getThisChanged">change this text</div>
By executing this next line of JavaScript, you can change the text inside of the tag
document.getElementById('getThisChanged').innerHTML("text is now changed");
The text will be changed to "text is now changed"