Insert json object in text area [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi I am developing a small application in JSP.
My idea is to give reference to a JSON element while user is typing in the text area.
for example:
If my JSON contains:
cO2,
H2O,
c9O
and in the text area the user is typing a sentence and as soon as the user types a special character such as # or \ or / if he/she writes "c" character I want a small drop down to appear with the two elements starting with c.
The user can select the element afterwards and then when the form is posted I want to extract those information which was entered from JSON.
This is like when you start typing a name in Facebook I guess.
Any ideas?
Thanks in advance
EDIT: JS Fiddle
<form action="./Protocol" method="POST">
<textarea rows=5 cols=50></textarea>
<input type="submit"/></form>
$('textarea').textcomplete([{
match: /(^|\s)(\w{2,})$/,
search: function (term, callback) {
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo'];
callback($.map(words, function (word) {
return word.indexOf(term) === 0 ? word : null;
}));
},
replace: function (word) {
return word + ' ';
}}]);
The above JS Fiddle does what I want partly.
One of the two things I want to accomplish here
1. if in the JSON, each word has an ID like {"ID": "1","name": "GOOGLE"} can I get the IDs that are in the textarea to be posted when the form is posted
2. or just the array index numbers, how do I POST the values in the form separately from the textarea.

OK, despite what I said, here's a basic example of how you might achieve this (because I was bored, but not so bored I'm going to do it all for you :)):
HTML
<input id="input"/>
<div id="dropdown"></div>
JS
// grab the DOM elements
var input = document.getElementById('input');
var dropdown = document.getElementById('dropdown');
// assign an function to the onkeyup event for your input box
input.onkeyup = search;
// define your data structure
var arr = ['cO2', 'H2O', 'c9O'];
function search() {
// get the content and length of the content
// `this` in this instance refers to the element to which
// we assigned the function
var val = this.value;
var len = val.length;
// filter out the elements from the array that match
// the content, or nothing if the input is empty
dropdown.textContent = arr.filter(function(el) {
return val !=='' ? el.substring(0, len) === val : '';
});
}
DEMO
Hope that helps you on your way.

Related

Typoglycemia generator [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
My goal is to create a "typoglycemia generator" using HTML CSS JS.
I.e. A web App which takes the user input and mixes up the letters of each word except for the first and last letter.
For example: USER INPUT = "Hello everyone at stackoverflow"; OUTPUT = "Hlelo eevrnyoe at satckoeovrflw"!
I am new to JS, can anyone guide me as to what the steps would be to create this JS code.
Thanks in advance!
Detailed explanation after snippet.
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function Typoglycemia(word) {
var letters=word.split("");
var first=letters.shift();
var last=letters.pop();
var shuffled=shuffle(letters);
shuffled.push(last);
shuffled.unshift(first);
var typoglycemia=shuffled.join("");
return typoglycemia;
}
function TypoglycemiaWord(word) {
document.getElementById("sTypoglycemiaWord").innerText = Typoglycemia(word);
}
function TypoglycemiaSentence(sentence) {
var words=sentence.split(" ");
var typoglycemias=words.map(word=>Typoglycemia(word));
document.getElementById("sTypoglycemiaSentence").innerText = typoglycemias.join(" ");
}
Enter a word: <input onchange="TypoglycemiaWord(this.value)"><br>
Typoglycemia: <span id="sTypoglycemiaWord">result here</span><br>
<br>
Enter a sentence: <input onchange="TypoglycemiaSentence(this.value)"><br>
Typoglycemia: <span id="sTypoglycemiaSentence">result here</span>
First thing we do is remove and save first and last letters.
It's done in function Typoglycemia that takes a word as it's parameter.
We split that word into letters by telling split to split every time it sees "" = nothing = just split.
shift removes the first element of an Array - we store that in first.
pop removes the last element of an Array - we store that in last.
We need a shuffling function - function shuffle - that takes an Array - array as it's parameter.
It goes from last element back to the second - Arrays are zero-indexed, so back to index 1, which is one after index 0 = the first element.
It randomly swaps, goes back, until done, and returns a shuffled array.
Back to Typoglycemia function:
We add last back to the end using push, and first back to the beginning using unshift.
Lastly, we join the array with no spaces "" and return it.
The rest, for word, is simpler HTML and JavaScript.
For sentences, we split by spaced " ", map each word to it's Typoglycemiad value, and then join the result with a space " " between each word.
The rest, for sentence, is simpler HTML and JavaScript.
The rest: Hitting ENTER in an input element calls a function, passing to it the value of itself (this).
TypoglycemiaWord and TypoglycemiaSentence do what they do (as explained above), and send the result to a span element that is found by using it's id in document.getElementById, by setting it's innerText to that result.
Hope this was fun as it was educational!

Regex to replace all occurrences of li tags [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to replace all occurrences of li tags in a string with "\par {\pntext\f1 ''B7\tab}" and then append whatever data was within tags to the end of it.
Basically converting html to rtf format.
e.g
<ul><li>list1 line1</li></ul>
<ul><li><span>list2 line1</span></li></ul>
In the end i want to remove all ul tags
function convertHtmlToRtf(html) {
var richText = html;
richText = richText.replace(/<(?:b|strong)(?:\s+[^>]*)?>/ig, "{\\b\n");
return richText;
}
Your question is a bit broad, but since you say you are using javascript and want a Regex. Then I assume you have a string and want to replace pairs of <li></li> with the given string. Also assuming that your HTML is always very simple and predictable (no <li>s within <li>s), then you could do something like this:
var str = "<ul><li>list1</li></ul>\n<ul><li><span>list2 line1</span></li></ul>";
str.replace(/<li( [^>]*){0,1}>(.*)<\/li>/, "\\par {\\pntext\f1 ''B7\\tab} $2");
Here I'm using a regular expressions that matches a pair of <li> and replace them by that magic string but keeping whatever is inside (note you can easily extend it to also remove the ul if necessary. Ending result:
<ul>\par {\pntext1 ''B7\tab} list1</ul>
<ul>\par {\pntext1 ''B7\tab} <span>list2 line1</span></ul>
Now you can notice right away that it won't remove tags inside - so the <span> will be left there. If you can use jQuery, then it might be easier to convert the nodes correctly than using Regex (which can get quite complicated)
Edit:
Since it's been clarified that jQuery can be used to help on the parsing, then here is a simple example of how you could use it:
https://jsfiddle.net/nazy8sc6/2/
var html = "<ul><li>list1 <b>line1</b></li></ul><ul><li><span>list2 line1</span></li></ul>";
var TAB_STR = "\\par {\\pntext1 ''B7\\tab}";
function convertLi(parent, node) {
var convertedText = TAB_STR + " " + $(node).text() + "<br>";
var convertedNode = $('<span></span>').html(convertedText);
$(parent).append(convertedNode);
}
function convertHtmlToRtf(html) {
var result = $('<span></span>');
$(html).find('li').each((_, node) => {
convertLi(result, $(node));
})
return result.html().replace(/<br \>/g, "\n");
}
var res = convertHtmlToRtf(html);
console.log(res);
In this solution, you simply find all <li> tags and extract the content from it - I keep the original HTML always there and simply copy the converted content into a new HTML from which we finally extract the fully converted text. Hope this helps you, but let me know if I haven't managed to explain myself very well.

How to switch <td> content with another <td> [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So the thing goes as following: I'm a begginer programmer (so far i know HTML, CSS some JavaScript and some C++) and we have a school project to create a chessboard with figures on them but I want to go a step further and be able to move the figures.
So far I've used the prompt function to get the coordinates and move them around but that feels far too much stone-agish. Now what I wish to accomplish is to be able to click on a , copy its content into a variable and upon clicking on another replace its content with the one stored in the variable. (I'll deal with the rules later..)
Each has its unique id and I have used element.firstChild.nodeValue to acquire the content.. Any suggestions on how to do this in JavaScript without using jQuery (if it can't be done in JavaScript then by all means do it in some other language.. it's about time I start learning them anyway.. :P)
If each <td> has a unique id, what about:
var lastStoredValue = "", lastClicked = ""; // = "" is important in that case
var t1 = document.getElementById("t1"); // td with id="t1"
var t2 = document.getElementById("t2"); // td with id="t2"
t1.onclick = function() {
if (lastClicked !== "t1" && lastStoredValue.trim())
t1.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t1.innerHTML)))
lastStoredValue= t1.innerHTML; // copy its content into a variable
lastClicked = "t1";
}
t2.onclick = function() {
if (lastClicked !== "t2" && lastStoredValue.trim())
t2.innerHTML = lastStoredValue; // replace its content with the one stored in the variable
if (!lastStoredValue.match(new RegExp(t2.innerHTML)))
lastStoredValue= t2.innerHTML; // copy its content into a variable
lastClicked = "t2";
}
This gets what is stored into one td and puts it into a variable; then stores what is in the variable into another td when click on that td.

How to append javascript varible without using jQuery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've simple javascript function mentioned below:
<script>
function getValue(val)
{
document.getElementById('answer').value = val;
}
</script>
This function get's called on click of span and returned value gets displayed in input text.
I've three questions:
1] On click of span, if I want to append current value of varible 'val' with previous value; and return appended value to calling function. can you please suggest, how to achieve same without using jQuery?
2] There is one span which is suppose to work like Backspace. So click of span, i want to remove last character from document.getElementById('answer').value [This also without using jQuery]
3] There is one span which is suppose to work like Navigation keys [Right & Left]. So click of span [Let's say right], i want to move cursor position of the input text one character right and similarly for Left [This also without using jQuery]
Can you please suggest some pointers to achieve this?
For your question 1 I think you can do below. Code not tested
function getValue(val)
{
var currentVal = document.getElementById('answer').value
if(currentVal.length > 0 )
currentVal = parseInt(currentVal);
document.getElementById('answer').value = currentVal + val;
}
For question 2 :
Get the value and then do string operation to remove the last char. Its easy little google search for the string operations
For question 3 :
you can use event oncontextmenu for right click. Example below.
How can I capture the right-click event in JavaScript?
For moving cursor check below
Set keyboard caret position in html textbox
+= oprator appends string to existing string(not applicable in this case).
use return keyword to return updated value.
for removing last character use substring.
so try:
function getValue(val)
{
var currentText = document.getElementById('answer').value;
var updatedText = currentText.substring(0,currentText.length-2) + val;
document.getElementById('answer').value = updatedText;
return updatedText;
}

Regex like parameter function in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I will do a function with parameters that get a regex and check the field of a form with it.
I have this code:
//The first function handler (no one runs):
field.onblur = function(){
checkField(0, /^([a-z ñáéíóúü]{2,60})$/i, "name", "nameError", "Error in name");
}
//The function:
function checkField(numForm, regex, idField, idError, error){
var form = document.getElementsByTagName("form")[numForm];
var field = form.getElementById(idField);
var spanError = form.getElementById(idError);
//Since here runs, so I think the problem is with the regex
if(!regex.test(idField.value))
spanError.innerHTML = error;
else
spanError.innerHTML = "";
}
What is the proper way to make a function and give it a regex like a parameter?
The regexp is passed fine, these two lines are erranous instead:
var field = form.getElementById(idField);
var spanError = form.getElementById(idError);
getElementById() is a method of document only. You can fix the issue by using id string like below:
var field = form[idField];
var spanError = form[idError];
... or using getElementById(): var field = document.getElementById(idField);
Also this line (unless a typo in the post)
if(!regex.test(idField.value))
should be:
if(!regex.test(field.value))

Categories