Please help me fix this javascript tool - javascript

This is in the head :
<script language="javascript" type="text/javascript"> f
function TextDefine(val) {
var i= 0;
var array1 = val.value.split("\n");
for ( i = 0; i < array1.length; ++i) {
array1[i] = "[b]" + array1[i] + "[/b]";
}
document.getElementById('another').value = array1.join("\n");
}
</script>
Then This is in the body:
<textarea name="data" id="data"></textarea>
<textarea name="another" id="another"></textarea>
<input type="button" name="submit1" value="Submit"
onclick="TextDefine(document.getElementById('data'))" />
i would like to add another text area so that when i click on the generate button, it will also get the content of the text area i just created. example:
text area 1
content of the text area 1
text area i just created
content of the text area 2
then the generated content content in the thrid text area should be:
[b]content of the text area 1[/b]
content of the text area 2
please see the javascript code why it had [b], i do not know how do to it so i need your help :( Thank You!

Is the keyword function being split onto two words something to do with entering it into stackoverflow? The below works for me:
<html>
<head>
<script language="javascript" type="text/javascript"> function TextDefine(val){ var i= 0; var array1 = val.value.split("\n"); for ( i = 0; i < array1.length; ++i) { array1[i] = " [b]" + array1[i] + "[/b]"; } document.getElementById('another').value = array1.join("\n"); }</script>
</head>
<body>
<form>
<textarea name="data" id="data"></textarea>
<textarea name="another" id="another"></textarea>
<input type="button" name="submit1" value="Submit" onclick="TextDefine(document.getElementById('data'))" />
</form>
</body>
</html>

Is this what you want to do?
http://jsbin.com/eligo4/edit

<script language="javascript" type="text/javascript">
function TextDefine(val, anotherval){
var i= 0;
var array1 = val.value.split("\n");
for ( i = 0; i < array1.length; ++i) {
array1[i] = "[b]" + array1[i] + "[/b]";
}
document.getElementById('generate').value = array1.join("\n")+"\n"+ document.getElementById('another').value;
}
</script>
<textarea name="data" id="data"></textarea>
<textarea name="another" id="another"></textarea>
<textarea name="generate" id="generate"></textarea>
<input type="button" name="submit1" value="Submit" onclick="TextDefine(document.getElementById('data'), document.getElementById('another'))" />

Related

for loop with array of strings rendering the same thing twice?

I am building in javascript a simple feedback that has a text area and is grabbing the text and displaying a successful message when the add button is clicked. When the view feedback button is clicked it should render the feedback and it does but if I click the button once and then type in the text area again and again it keeps rendering multiple times the same feedback message. Attached is my javascript code.
var array = Array();
var x = 0;
function addFeedback() {
array[x] = document.getElementById('feedback').value;
x++;
document.getElementById('feedback').value = '';
document.getElementById('result').innerHTML =
'<h2><h3> Your have successfully Added Feedback!</h3></h2>';
}
var feedback = '';
function displayFeedback() {
for (var i = 1; i < array.length + 1; i++) {
feedback = array[i - 1] + '<br/>';
console.log(feedback);
}
document.getElementById('result').innerHTML =
'<h2>feedback Details: </h2>' + feedback.split('<br>');
}
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<!-- Fill code here -->
<div>
<h2>Feedback for the ART OF LIVING</h2>
<div>
<label for="feedback"></label>Enter the Feedback:
<textarea id="feedback" name="feedback" value="feedback" type="text"></textarea>
<div>
<input type="button" id="create" name="create" onclick="javascript:addFeedback()">Add Feedback</input><br/>
<input type="button" id="view" name="view" onclick="javascript:displayFeedback()">View feedback</input>
</div>
<div id="result"></div>
</div>
</div>
</body>
</html>

How to focus cursor in specific point in textarea using js?

I am trying to create "quicklink" option in textarea using which users can insert html tags by directly clicking over them. It is working fine but after I click any quicklink button the cursor moves to the end of the text present in the textarea.
How to keep/focus cursor just after the inserted tag?
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
function quicklink(link){
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").focus();
}
// Getting closest number for array
// https://stackoverflow.com/questions/8584902/get-closest-number-out-of-array
function closest (num, arr) {
var curr = arr[0];
var diff = Math.abs (num - curr);
for (var val = 0; val < arr.length; val++) {
var newdiff = Math.abs (num - arr[val]);
if (newdiff < diff) {
diff = newdiff;
curr = arr[val];
}
}
return curr;
}
$('#txtarea').click(function(){
var str = $(this).val();
var regex = /\<([a-zA-Z\/]+\>)/gi, result, indices = [];
// Getting positions as array
// https://stackoverflow.com/questions/3410464/how-to-find-indices-of-all-occurrences-of-one-string-in-another-in-javascript
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
var cursorPosition = $(this).prop("selectionStart");
$(this).prop('selectionEnd');
var closestPosition = closest(cursorPosition,indices)
$(this).prop('selectionEnd', closestPosition);
})
<!--index.php -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>QuickLink</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery.min.js"></script><script src="quicklink.js"></script>
<script>
$(document).ready(function() {
$("#txtarea").keyup(function(){
var txt = $("#txtarea").val();
var len = txt.length;
$("#count").html("Word Count: " + len );
});
});
</script>
</head>
<body>
<div class="text_top">
<input type="submit" onClick="quicklink('<div>')" value="<div>" >
<input type="submit" onClick="quicklink('</div>')" value="</div>">
<input type="submit" onClick="quicklink('<span>')" value="<span>" >
<input type="submit" onClick="quicklink('</span>')" value="</span>" >
<input type="submit" onClick="quicklink('<B>')" value="<B>" >
<input type="submit" onClick="quicklink('<I>')" value="<I>" >
<input type="submit" onClick="quicklink('<U>')" value="<U>" >
<input type="submit" onClick="quicklink('<ul>')" value="<ul>" >
<input type="submit" onClick="quicklink('<li>')" value="<li>" >
<input type="submit" onClick="quicklink('<sup>')" value="<sup>" >
<input type="submit" onClick="quicklink('<sub>')" value="<sub>" >
<input type="submit" onClick="quicklink('<strike>')" value="<strike>">
</div>
<textarea id="txtarea" class="textarea"></textarea><div id="test">
</div>
<div id="count" class="text_down">Word Count: 0</div>
</body>
</html>
You can get current cursor position by using following solution:
https://stackoverflow.com/a/1909997/7676742
And increment it by the length of your new added html tag (for instance 3 for <a>) and set position of cursor by using following solution:
https://stackoverflow.com/a/49750025/7676742
I found an easy way to do this:
function quicklink(link){
var linklen=link.length;
var cursorPos= $("#txtarea").prop('selectionStart');
var v= $("#txtarea").val();
var textBefore= v.substring(0, cursorPos);
var textAfter= v.substring(cursorPos,v.length);
$("#txtarea").val(textBefore + link + textAfter);
$("#txtarea").prop('selectionEnd', cursorPos+linklen);
$("#textarea").focus();
}

Keeping value of search box Javascript/HTML

I made a tool which make my work a little easier by inserting a value into a url in a new window on multiple sites. It was working quite well but now I am having the problem of the search value being cleared onsubmit.
Javascript:
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
if(document.search.website.checked) {
var website = open( "https://www.website.com/" + req, "website");
}
//--></script>
HTML:
<form name="search">
Please select the networks you want to use.
<p>
</center>
</p>
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
So far, return false had been working to keep the value of the input in the form="text" input name="query" but now it seems to clear it and reload the page. I'm not sure what changed.
You have errors in your code opening and closing the tags.
Try this code. It works:
<html>
<head></head>
<body>
Please select the networks you want to use
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
</form>
</div>
</div>
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
var checkbox = document.getElementsByName("website");
if(checkbox[0].checked) {
var website = open("https://www.website.com/" + req,
"website");
}
}
</script>
</body>
</html>
Hope it helps.
I fixed it. It was not the tags. I had only pasted a small amount of the total code to make it easier to read but I failed at making it easier to read. The problem was undefined inputs. I have been adding many if statements but didn't have a corrosponding checkbox. Oops.
Thanks for the help.

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

DOM event clearing text values

I'm writing a JS code to calculate a final grade given some individual grades and output the result in the html page but when I trigger the event and function it outputs a wrong answer for a split second then immediately disappears along with the values entered into the text box.
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Problem 2</title>
<script src="grades.js" type="text/javascript"></script>
</head>
<body>
<h1>Grade Calculator</h1>
<form id ="myForm">
<div id="assignments">
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/><br/>
HW <input type="text" size="1"/> / <input type="text" size="1"/>
</div>
<div>
<input type="checkbox" /> Curve +5?
</div>
<div id="resultsarea">
<p>
<!--add buttons here -->
<button id="comp">Compute</button>
<button id="clr">Clear</button>
</p>
<!-- add results here -->
</div>
</form>
</body>
</html>
JS:
window.onload = pageLoad;
function pageLoad()
{
var cbutton = document.getElementById("comp");
cbutton.onclick = compute;
}
function compute()
{
var values = document.getElementsByTagName("input");
var marks = 0;
var total = 0;
for (var i=0; i < values.length; i++)
{
if(values[i].type == "text")
{
if (i%2 == 0)
marks += parseInt(values[i].value);
else
total += parseInt(values[i].value);
}
}
var result = Math.round(marks/total);
document.writeln(result);
}

Categories

Resources