How to output a reverse string using innerHTML? - javascript

I'm trying to reverse a string and output the results using innerHTML. Nothing is output when I click the button.
<input type="text" id="text">
<button id="reversal">Reverse</button>
<div id="results"></div>
<script type="text/javascript">
var input1 = document.getElementById("text").value;
var button = document.getElementById("reversal");
var result = document.getElementById("results");
var reversals = function(string) {
result.innerHTML = string.split("").reverse().join("");
}
button.onlclick = function() {
reversals(input1);
}
</script>

This is what you should do.
input1 = document.getElementById("text").value; should be assigned within onclick handler.
var button = document.getElementById("reversal");
var result = document.getElementById("results");
var reversals = function(string) {
result.innerHTML = string.split("").reverse().join("");
}
button.onclick = function() {
var input1 = document.getElementById("text").value;
reversals(input1);
}

As already mentioned you have a typo, you need to change button.onlclick to button.onclick. Next when you do a refersal it still has the value of text from when the document loaded, which is empty. You need to get the new value:
button.onclick = function() {
var input1 = document.getElementById("text").value;
reversals(input1);
}

Related

How do you get the user data from a HTML input (text) created using createElement()?

My Problem
I would like some help understanding how to access the value inside input1 and input2, store them in a variable so I can later use them with a function that will calculate the two values and display it in the result div.
const input1 = document.createElement("input");
document.body.appendChild(input1);
const input2 = document.createElement("input");
document.body.appendChild(input2);
const result = document.createElement("div");
document.body.appendChild(result);
an idea can be to use EventListener on the created input to manipulate the data
const input1 = document.createElement("INPUT");
document.body.appendChild(input1);
input1.addEventListener('change', function (e) {
var target = e.target || e.srcElement;
console.log(target.value);
});
you can also add a selector (id or class) to the created element and recover it by this selector
const input1 = document.createElement("INPUT");
document.body.appendChild(input1);
input1.id = 'test';
function showData() {
var input = document.getElementById('test');
console.log(input.value);
}
<button onclick="showData()">show data</button>
with your sample it can look like
const input1 = document.createElement("INPUT");
input1.id = 'input1';
document.body.appendChild(input1);
const input2 = document.createElement("INPUT");
input2.id = 'input2';
document.body.appendChild(input2);
const result = document.createElement("DIV");
result.id = 'result';
document.body.appendChild(result);
function showResult() {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
var result = document.getElementById('result');
if (input1 && input2 && result) {
result.innerText = input1.value * input2.value;
}
}
<button onclick="showResult()">show result</button>
if you have to dynamically create div and showresult you can also create the button and manipulate the onclick event
var numberOfRow = 0;
function copyResultInNextInput(nextNumber, result) {
var next = document.getElementById('input1_' + (nextNumber));
if (next) {
next.value = result.innerText;
}
}
function createNewRow(haveSeveralButtons) {
numberOfRow++;
const nextNumber = numberOfRow + 1;
const input1 = document.createElement("INPUT");
input1.id = 'input1_' + numberOfRow;
document.body.appendChild(input1);
const input2 = document.createElement("INPUT");
input2.id = 'input2_' + numberOfRow;
document.body.appendChild(input2);
const result = document.createElement("DIV");
result.id = 'result_' + numberOfRow;
document.body.appendChild(result);
const button = document.createElement("BUTTON");
button.innerText = 'show result';
button.addEventListener('click', function() {
result.innerText = input1.value * input2.value;
if (!haveSeveralButtons) {
copyResultInNextInput(nextNumber, result);
}
});
document.body.appendChild(button);
if (haveSeveralButtons) {
const button2 = document.createElement("BUTTON");
button2.innerText = 'copy result in next input1';
button2.addEventListener('click', function() {
copyResultInNextInput(nextNumber, result);
});
document.body.appendChild(button2);
}
const hr = document.createElement("HR");
document.body.appendChild(hr);
}
<button onclick="createNewRow(false)">create New Row with one button</button>
<button onclick="createNewRow(true)">create New Row with two buttons</button>
<hr/>
OK, so the Id work, but it only works for that one row. I need to repeat that process (equation) independanly on each new row that's created.

focus is not working on textarea

I am creating a page in which a user can add a question and its solution, he can delete the problem and can also edit it dynamically using DOM in javascript. I want that whenever user clicks on edit button the textbox which appears get autofocus.
This the javascript code of my page...
var questionText;
var answerText;
var questionArray=[];
var answerArray=[];
var i=0;
var j=10000;
function addProblem(){
var body = document.getElementsByTagName('body')[0];
questionText = document.getElementById('questionId').value;
answerText = document.getElementById('answerId').value;
questionArray.unshift(questionText);
answerArray.unshift(answerText);
var myContainer = document.getElementById('container');
var myDiv = document.createElement("div");
var questionLogo = document.createElement("p");
questionLogo.id = "questionLogo";
var textNode = document.createTextNode("Question:");
var question = document.createElement("p");
question.id = "question";
var questionDetail = document.createTextNode(questionArray[0]);
var deleteButton = document.createElement("button");
deleteButton.innerHTML = "Delete";
deleteButton.id = i;
var editButton = document.createElement("button");
editButton.innerHTML = "Edit";
editButton.id = j;
var answerLogo = document.createElement("p");
answerLogo.id = "answerLogo"
var ansTextNode = document.createTextNode("Answer: ");
var answer = document.createElement("p");
answer.id = "answer";
var answerDetail = document.createTextNode(answerArray[0]);
var mybr = document.createElement("br");
if(i==0){
myContainer.appendChild(myDiv);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answerLogo.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
else if (i > 0)
{
myContainer.insertBefore(myDiv,myContainer.firstChild);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answer.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
i++;
j++;
myDiv.childNodes[7].addEventListener("click", function(){
var deleteElement = document.getElementById(this.id);
deleteElement.parentNode.parentNode.removeChild(deleteElement.parentNode);
});
myDiv.childNodes[9].addEventListener("click",function(){
var editElement = document.getElementById(this.id);
var quesEdit = editElement.parentNode.childNodes[1];
var quesEditText = quesEdit.innerHTML;
var ansEdit = editElement.parentNode.childNodes[4];
var ansEditText = ansEdit.innerHTML;
var editDiv1 = document.createElement("div");
editDiv1.id = "editDiv1"
var quesTextArea = document.createElement("textarea");
quesTextArea.innerHTML += quesEditText;
quesTextArea.focus();
var saveButton1 = document.createElement("button");
saveButton1.innerHTML = "Save";
editDiv1.appendChild(quesTextArea);
editDiv1.innerHTML += ' ';
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
var editDiv2 = document.createElement("div");
editDiv2.id = "editDiv2"
var ansTextArea = document.createElement("textarea");
ansTextArea.innerHTML += ansEditText;
var saveButton2 = document.createElement("button");
saveButton2.innerHTML = "Save";
editDiv2.appendChild(ansTextArea);
editDiv2.innerHTML += ' ';
editDiv2.appendChild(saveButton2);
ansEdit.parentNode.replaceChild(editDiv2,ansEdit);
});
}
I have tried to focus the textarea using
quesTextArea.focus();
but its not working where questextArea is the name of the textarea. Please help how i can do it.
For the element could be got focused, it must be in the DOM when you invoke focus on it. You should invoke focus function after replaceChild function
editDiv1.appendChild(quesTextArea);
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
quesTextArea.focus();
I've created a simple sample as below link, you could check it
https://jsfiddle.net/pd9c6c7a/3/
Add autofocus attribute to the textarea element. So that whenever it is appended to the DOM, will get cursor activated in it.
The 'textarea' has not been added to window to be shown, an element must be part of the document object tree. In case that didn't work, add a 50ms delay.
setTimeout(function(){e.focus();}, 50);
Try the following approach:
var body=document.getElementsByTagName('body')[0];
var quesTextArea=document.createElement("textarea");
var button=document.createElement("button");
button.innerHTML = "click Me";
button.addEventListener("click",function(e){
e.preventDefault();
quesTextArea.focus();
});
body.appendChild(quesTextArea);
body.appendChild(button);
<html>
<body>
<body>
</html>
Try to add preventDefault.
var div = document.getElementById('parent');
var txt = document.createElement('textarea');
div.appendChild(txt);
txt.focus();
<html>
<head></head>
<body>
<div id="parent">
<input type="text" value="" />
</div>
</body>
</html>
The element must be in the DOM when you invoke the focus function. Move your focus() function after the appendChild() is invoked.
quesTextArea.innerHTML += quesEditText;
var saveButton1=document.createElement("button");
saveButton1.innerHTML="Save";
editDiv1.appendChild(quesTextArea);
quesTextArea.focus();

Javascript: How to implement the "enter/return key" to save a value?

Sorry, I am not really good with JS.
The code is essentially the user double clicks on the text, textbox appears, changes text, and saves a new value. However, I want the user to be able to also click enter to save the new value.
In addition, if possible, to have a dedicated "Save" button to save the new value and "discard" to keep the old value.
Also, if I double click many times, the text appears as "(input type="text")". Is there a way to remove that?
Please help if you can.
The HTML + JS code
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var elements = getElementsByClassName('text-edit', '*', document);
for(var i = 0; i < elements.length; i++) {
elements[i].ondblclick = function() {
this.setAttribute('oldText', this.innerHTML); // not actually required. I use this just in case you want to cancel and set the original text back.
var textBox = document.createElement('INPUT');
textBox.setAttribute('type', 'text');
textBox.value = this.innerHTML;
textBox.onblur = function() {
var newValue = this.value;
this.parentNode.innerHTML = newValue;
}
this.innerHTML = '';
this.appendChild(textBox);
}
}(i);
}
function getElementsByClassName(className, tag, elm) {
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i = 0; i < length; i++) {
current = elements[i];
if(testClass.test(current.className)) {
returnElements.push(current);
}
}
return returnElements;
}
</script>
</head>
<div><span class="text-edit">Some text</span></div>
</html>
The snippet below allows you to modify the value of a textbox using save button or enter key and discarding any changes using cancel button.
<!-- HTML -->
<h1 id="editable">Lorem Ipsum</h1>
// JavaScript
window.onload = function(){
var h1 = document.getElementById('editable');
h1.onclick = function(){
var old = this;
var input = document.createElement("INPUT");
input.type = "text";
input.value = this.innerHTML;
input.onkeyup = function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
save.parentNode.removeChild(save);
cancel.parentNode.removeChild(cancel);
}
};
this.parentNode.replaceChild(input, this);
var save = document.createElement("INPUT");
save.type = "button";
save.value = "Save";
(function(old, input){
save.onclick = function(){
old.innerHTML = input.value;
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
cancel.parentNode.removeChild(cancel);
};
})(old, input);
input.parentNode.insertBefore(save, input.nextSibling);
var cancel = document.createElement("INPUT");
cancel.type = "button";
cancel.value = "Cancel";
(function(old, input){
cancel.onclick = function(){
input.parentNode.replaceChild(old, input);
this.parentNode.removeChild(this);
save.parentNode.removeChild(save);
};
})(old, input);
input.parentNode.insertBefore(cancel, input.nextSibling);
};
};
Working jsBin

get information from array to input

how i get information from array and send it to input?
i have a filter, after filtering information i have 2 value (v1,v2) and 2 button - for v1 and v2. I need to do- by pressing the button v1 information from mynewvarv1 go to input whith id='one' - can you help me to write this function?
sorry for my english
var myvar = [ // filter start
{name:'v1',val1:'31',val2:'',val3:true,val4:false,val5:false,val6:false,},
{name:"Срочный на 91 день",val1:'91',val2:'',val3:true,val4:false,val5:false,val6:false,},
{name:"v2",val1:'181',val2:'',val3:true,val4:false,val5:false,val6:false,},
];
document.getElementById('filterButton').onclick = function(){
var filter = [];
filter.push(document.getElementById('val1').options[document.getElementById('val1').selectedIndex].value);
filter.push(document.getElementById('val2').value);
filter.push(rbvalue('val3')=='1');
filter.push(rbvalue('val4')=='1');
filter.push(rbvalue('val5')=='1');
var filtered_data = [];
var data_accepted = true;
for(i=0;i<myvar.length;i++){
data_accepted = true;
for(j=0;j<filter.length;j++){
if(filter[j]!=='' && filter[j]!=myvar[i][('val'+(j+1))]){
data_accepted = false;
}
}
if(data_accepted){
filtered_data.push(myvar[i]);
}
}
function getmesseg (){
container.innerHTML = ' v1 <button onclick="myFunction()">Try it</button>'
container.innerHTML = ' v2<button onclick="myFunction()">Try it</button>'
var mynewvarv1 = [ {vaal1:value="12",vaal2:'10.2',vaal3:'9',} ];
var mynewvarv2 = [ {vaal1:value="12",vaal2:'10.2',vaal3:'9',} ];
//what the function this needs???
};
function ab(){ if(filtered_data[i].name == "v1","v2") {getmesseg(); }};
var container = document.getElementById('container');
container.innerHTML = '';
for(i=0;i<filtered_data.length;i++){
container.innerHTML+=filtered_data[i].name+'<br />';
ab();
}
};
function rbvalue(html_name){
var undefined,default_value,i,rb_collection = document.getElementsByName(html_name);
if(rb_collection!==undefined){
default_value = rb_collection[0].value;
}
for(i=0;i<rb_collection.length;i++){
if(rb_collection[i].checked){
return rb_collection[i].value;
}
}
return default_value;
}// filter end
You should be able to use:
var input1 = document.getElementById("one");
input1.value = mynewvarv1[0].vaal1;

jQuery: Searching textarea value for words using regex

I have the following code:
<script type="text/javascript">
$(function(){
var txt = new Array();
var count = 0;
$('textarea[id*="page_parts_attributes_"]').each(function(){
var html = $(this).html($(this).val());
var matches = $(html).match(/\b/g)
if(matches) {
txt[count] = jQuery.trim(matches).length / 2
count++;
}
});
var final_count = eval(txt.join('+'));
console.log(Math.floor(final_count));
})
</script>
I am basically trying to search the textarea for words. I have to convert the value of the textarea to HTML, then I want to search the HTML for words... but its not working...
any ideas?
var html = $(this).html($(this).val());
var matches = $(html).match(/\b/g)
should be
var matches = $(this).val().match(/\b/g);
The value of the textarea is aalready a string. The html method doesn't work the way you think it does. It should be a simple matter of removing the bits where you are attempting to use html.
<script type="text/javascript">
$(function(){
var txt = new Array();
var count = 0;
$('textarea[id*="page_parts_attributes_"]').each(function(){
var text = $(this).val();
var matches = text.match(/\b/g)
if(matches) {
txt[count] = jQuery.trim(matches).length / 2
count++;
}
});
var final_count = eval(txt.join('+'));
console.log(Math.floor(final_count));
})
</script>

Categories

Resources