This question already has answers here:
How to add line breaks to an HTML textarea
(9 answers)
Closed 5 years ago.
I'm trying to input text into a textarea and have it start on a new line with every insert.
Currently this is my code, so when you enter a username/text and click post it will paste this into a text area.
<script type="text/javascript">
document.getElementById("post").addEventListener('click', function () {
var username = document.getElementById('username').value;
var input = document.getElementById('input').value;
var output = document.getElementById('output');
var outputtext = username + ":" + input;
output.value += outputtext;
});
</script>
currently the output looks like this:
Username1:Text1Username2:Text2Username3:Text3
Where As i want it to display as:
Username1:Text1
Username2:Text2
Username3:Text3
Cheers for any help
JUst add the <br> as \nto the string of outputtext:
var outputtext = username + ":" + input +"\n";
\n - a new line character n that must be escaped with backslash \ and encapsulated in double quotation marks "
Related
I have a <textarea> that I am attempting to add quotation marks around each value a user puts inside the text box upon clicking a button. My code appears to be viewing every row as 1 large value and just adds quotation marks at the beginning of the first word and end of the last word where it looks like this:
"one word
two word
three word"
I am attempting to achieve this output:
"one word"
"two word"
"three word"
Here's my current code:
document.getElementById("phraseButton").addEventListener('click', function () {
var keywordBox = document.getElementById('keywordBox');
keywordBox.value = ('"' + keywordBox.value + '"');
});
<textarea id="keywordBox" type="text" rows="100" cols="30">Insert Keywords</textarea>
<button id="phraseButton">Phrase</button>
you can replace all \n in your textarea with "\n" using replace(). something like this:
document.getElementById("phraseButton").addEventListener('click', function () {
var keywordBox = document.getElementById('keywordBox');
keywordBox.value = ('"' + keywordBox.value + '"');
keywordBox.value = keywordBox.value.replace(/\n/g, '"\n"')
});
<textarea id="keywordBox" type="text" rows="100" cols="30">Insert Keywords</textarea>
<button id="phraseButton">Phrase</button>
I have a string that conains HTML. In this HTML I have a textbox with text inside:
<div class="aLotOfHTMLStuff"></div>
<textbox>This textbox must be terminated! Forever!</textbox>
<div class="andEvenMoreHTMLStuff"></div>
Now I want to remove the textbox from that string, including the text inside. The desired result:
<div class="aLotOfHTMLStuff"></div>
<div class="andEvenMoreHTMLStuff"></div>
How can I achieve it? The two main problems: It is a string and not part of the DOM and the content inside the textbox is dynamic.
Here is an example that will look for the opening and closing tags in the string and replace anything in between.
const template = document.querySelector('#html')
const str = template.innerHTML
function removeTagFromString(name, str) {
const reg = new RegExp('<' + name + '.*>.*<\/'+ name +'.*>\\n*', 'gm')
return str.replace(reg, '')
}
console.log('before', str)
console.log('after', removeTagFromString('textbox', str))
<template id="html">
<div class="aLotOfHTMLStuff"></div>
<textbox>This textbox must be terminated! Forever!</textbox>
<div class="andEvenMoreHTMLStuff"></div>
</template>
If it is text string not HTML, you can convert it to DOM:
var str = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
var $dom = $('<div>' + str + '</div>');
Then remove element from DOM:
$dom.find('textbox').remove();
If you need, can get string back:
console.log($dom.html());
Try this:
var string = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
if ( string.includes("<textbox>") ) {
var start = string.indexOf("<textbox>");
var stop = string.indexOf("</textbox>");
string = string.replace(string.slice(start, stop+10), "");
}
console.log(string);
You can use parseHTML to convert string to html,
like..
var str = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
var a = $.parseHTML(str);
var newstr = "";
a.forEach(function(obj) {
if ($(obj).prop('tagName').toLowerCase() != "textbox") {
newstr += $(obj).prop("outerHTML")
}
});
It's very simple and you can remove any tag in future by just replacing "textbox"
It is a string and not part of the DOM and the content inside the
textbox is dynamic.
So that html is in a js variable of type string? like this?:
var string = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
So in that case you could use .replace(); like this:
string = string.replace('<textbox>This textbox must be terminated! Forever!</textbox>', '');
This question already has answers here:
How to set value of input text using jQuery
(7 answers)
Closed 8 years ago.
There is a function that calculates and displays the difference of 2 time variables the user selects in separate drop down lists. The display is invoked when the paragraph tags are used in the form. Function below:
<script type='text/javascript'>//<![CDATA[
$(window).load(function () {
$(document).ready(function () {
function calculateTime() {
//get values
var valuestart = $("select[name='timestart']").val();
var valuestop = $("select[name='timestop']").val();
//create date format
var timeStart = new Date("01/01/2007 " + valuestart).getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();
var hourDiff = timeEnd - timeStart;
$('p').html("Total Hours: " + hourDiff)
}
$("select").change(calculateTime);
calculateTime();
});
});//]]>
</script>
The function works. However, I'm needing the "difference in time" value to be passed to an HTML input tag and displayed instead of simply being displayed when paragraph tags are used.
Is there be a way to do this?
Yes:
$("input").val(hourDiff);
I am trying to get the value of a javascript variable within an html page. I have figured out how to get the text of all script tags but can't seem to figure out how to get the text of a specific variable within a script tag. Does anyone know how to get the text of a javascript variable?
The following is an example of what I'm trying to parse from. I'm trying to get the value of "var d"
<div id="box" style="position:absolute;z-index:6;left:px;top:450px;"></div>
<script language="javascript">
function showTooltip(element, town_name, p, points, a, town_type){
var t = $('tt');
t.style.top = (-75 + element.offsetTop) + 'px';
t.style.left = (25 + element.offsetLeft) + 'px';
t.style.backgroundImage="url('images/odd.png')";
t.innerHTML = '<font color=#AD4100>' + unescape(town_name) + '<br/>' + unescape(p) + '<br/>' + points + '<br/>' + unescape(a) + '<br/>' + unescape(town_type) + '</font>';
t.show();
}
function hideTooltip(){
$('tt').hide();
}
var d = [[1490.77265625,1373.4140625,30983,'TownID: 30983','GREY','circle_grey.png',1248,'planet x\'s city 5','','N/A'],[1186.45390625,1538.265625,33009,'TownID: 33009','GREY','circle_grey.png',1150,'wendyshome','','N/A'],[1234.496875,856.18203125,31646,'TownID: 31646','GREY','circle_grey.png',1312,'...','','N/A'],[1041.30078125,812.55859375,35358,'TownID: 35358','GREY','circle_grey.png',1207,'Waterville','','N/A'],
The following is a snippet of my code that gets the text of all script tags.
for element in page.iter('script'):
scriptText = element.text_content()
print(scriptText)
You'll have to use string processing on scriptText once you have that extracted. lxml cannot help you any more here.
If var d is the last entry in the script, you could use:
var_d_source = scriptText.split('var d =', 1)[-1].rsplit(';', 1)[0].strip()
which should give you everything after var d = up to the last semicolon.
You'd then convert the value to Python with the json module:
var_d_value = json.loads(var_d_value)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am using a HTML page where I have multiple textbox inputs, lets say five for example. I have a submit button. Once I enter all values in the text boxes and hit submit, i want all the values to be displayed in the area below submit button on the document in an ascending order. I want to sort all the values to display as result. I just used an array to test if my concept is right, but no luck. Anyone could help is highly appreciated.
This is the code:
function myFunction() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
}
The .text-1, .text-2, etc are the classes of your input fields. The .val() will get the user input of those once they click on your submit button. The last line creates a new div and appends the user input to the results div.
$('.submit-button').on('click', function() {
aaa = $('.text-1').val();
bbb = $('.text-2').val();
ccc = $('.text-3').val();
ddd = $('.text-4').val();
eee = $('.text-5').val();
$('<div>' + aaa + '<br />' + bbb + '<br />' + ccc + '<br />' + ccc + '<br />' + ddd + '<br />' + eee + '</div>').appendTo('.results-div');
});
Here is a fiddle that does what I think you want done:
http://jsfiddle.net/KjHB3/3/
Here is the HTML code:
<input type="text" name="text1" id="text1" /><br/>
<input type="text" name="text2" id="text2" /><br/>
<input type="text" name="text3" id="text3" /><br/>
<input type="text" name="text4" id="text4" /><br/>
<input type="text" name="text5" id="text5" /><br/>
<input type="button" value="submit" id="submit" />
<div id="result">replace</div>
Here is the javascript code:
$("#submit").click(function() {
// Extract all the values into an array
var valArray = [];
$("input[type=text]").each(function(index, el) {
valArray[index] = jQuery(el).val();
});
// Output list of values (in order they appear in form)
$("#result").html("In order of text box: <ol id='list1'></ol>");
$.each(valArray, function(index, value) {
$("#list1").append("<li>" + value + "</li>");
});
// Output list of values (in sorted order)
$("#result").append("In sorted order: <ol id='list2'></ol>");
valArray = valArray.sort();
$.each(valArray, function(index, value) {
if (value != null && value != "") {
$("#list2").append("<li>" + value + "</li>");
}
});
});
Your code appears to be correct, except for the line document.getElementById('txt[i]').value + ' ';. There's nothing writing the values back to the document.
First, starting with the selector, you need to change 'txt[i]' to 'text'+i, because the browser is looking for an element with id txt[i] and finding nothing, thus doing nothing. Also, you should use jQuery, since it makes everything more concise.
Then, to write back to the document, you need to set the value. What your current code (.value + ' ';) does is it gets a value, then adds it to the string ' ', then the statement ends. What you need to do is to set the value of the string, with jQuery (.val(txt[i]);) or stock Javascript (.value = txt[i];).
So, to conclude, just swap the code inside the for loop in your code with this line:
$("input:text[name=text"+i+"]").val(txt[i]);
Let me break down your code in two part to show why it is not working yet.
function GetInputValues() {
var txt = new array[];
var txt[0] = $('input:text[name=text1]').val();
var txt[1] = $('input:text[name=text2]').val();
var txt[2] = $('input:text[name=text3]').val();
var txt[3] = $('input:text[name=text4]').val();
var txt[4] = $('input:text[name=text5]').val();
txt.sort();
return txt; // added by me to encapsulate getting the values
}
The first part of your function myFunction() is correct. You are using jQuery to get the values of the input boxes and writing the values into an array.
The second part has some mistakes:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').value + ' ';
}
The function document.getElementById("lastname") returns the html-element whose id is lastname. So in your for-loop you are trying to get the value but you already have the values in your array txt. On top this 'txt[i]' is only a string. So javascript tries to find an element that matches <... id="txt[i]" ...>. But you do not want to get the values you want to write the values back into the document. Assuming you have a div like this <div id='txt[i]'> ...</div> you could wrhite your code like this:
for (var i = 0; i < txt.length; i++) {
document.getElementById('txt[i]').innerHTML += txt[i];
}
Another way would be to join the array:
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
This assumes that you have a element with id=myResult for example <div id='myResult'>..</div>
Update to adress issues in your code
Your fiddle has this part:
myFunction(txt) { // <-- function declaration: there is something missing here
var myInputValues = GetInputValues(); // this returns your array txt
document.getElementById('myResult').InnerHTML = myInputValues.join(", ");
} //<--- this is the end of myfunction
}); // <-- these do not belong here
// you never execute myFunction
You have to define the function and later call it. Since your mistakes are so basic i really recommend to start with a tutorial to learn javascript. I can recommend Eloquent JavaScript:
to learn the basics of functions
to understand the basics about the Document-Object Model