I'm really new to Javascript. I am trying to output the current date and also the content in the textarea tag in HTML on button click.
However I do not know how to obtain the content when the textarea is not declared along with a name/id/class.
Here's my code:
<script>
function displayPost() {
var thisDiv = document.getElementById("posts");
var date = new Date();
date.classList.add("post-time");
var textarea = document.getElementByTagName("textarea");
textarea.classList.add("post-content");
thisDiv.innerHTML = date + textarea;
}
</script>
<html>
<div id="posts"></div>
<textarea rows="4" cols="60">Type your text here...</textarea>
<button onclick = "displayPost()">Post</button>
</html>
Any sort of help is appreciated! Thank you in advance!
You can use document.querySelector when a dom element does have any name/id/class like:
var textarea = document.querySelector('textarea');
To get the current date in a readable format, you can use toLocaleString() method:
var date = new Date();
console.log(date.toLocaleString());
// → "3/21/2020, 7:00:00 PM"
To get <textarea> current entered value you can use:
var textarea = document.querySelector('textarea');
console.log(textarea.value);
DEMO:
function displayPost() {
var thisDiv = document.getElementById('posts');
var date = new Date();
thisDiv.classList.add("post-time");
var textarea = document.querySelector('textarea');
textarea.classList.add("post-content");
thisDiv.innerHTML = date.toLocaleString() + ': '+ textarea.value;
}
.post-time{padding:20px 0}
<div id="posts"></div>
<textarea rows="4" cols="60" placeholder="Type your text here..."></textarea>
<button onclick="displayPost()">Post</button>
you can make use of document.querySelector() which returns first matching element or document.getElementsByTagName() which returns NodeList of all the textarea elements
var textarea = document.querySelector('textarea').value;
or
var textarea = document.getElementsByTagName('textarea')[0].value;
Related
I have a text area that I will paste some data in for example like so
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
And when I click submit all the text inside the text box to give an output below something like this
06/01/2019 <!-- dd/mm/yyyy -->
07/01/2019
08/01/2019
08/01/2019
10/01/2019
I have managed to this on python using this code
filepath = ('date.txt')
f = open("newdate.txt", "w+")
new = []
with open(filepath) as fp:
for line in fp:
line = line.strip('\n')
new = line.split("-")
f.write(new[1] + "/" + new[2] + "/" + new[0] + "\n")
print(new[1] + "/" + new[2] + "/" + new[0] + "\n")
f.close()
I am new to JavaScript and jQuery so wondering how can i achieve that in jQuery
You can register an onsubmit listener on your form and then in the handler, perform your logic of parsing the text area's value.
The following snippet is an example of how to do that:
// Register 'submit' event listener
document.querySelector('#form')
.addEventListener('submit', e => {
// Prevent default action so that page doesn't refresh
e.preventDefault();
// Get the text from the textarea
let text = document.querySelector('#text').value;
// Split the lines
let converted = text.split('\n')
// Convert each line
.map(str => {
// Extract the date parts
let [mm, dd, yyyy] = str.split('-');
// Return the desired format by joining the date parts with /
return [dd, mm, yyyy].join('/');
});
// Print result to console
console.log(converted);
});
<form id="form">
<textarea id="text"></textarea>
<button type="submit">submit</button>
</form>
use following regexp-replace for textarea value
value.replace(/(-)(?=\d)/g,'/')
The (-)(?=\d) will find all dashes '-' preceding the number
function submit() {
let r=data.value.replace(/(-)(?=\d)/g,'/');
console.log(r);
}
textarea { width: 200px; height: 100px; }
button { display: block }
<textarea id="data">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>
<button onclick=submit()>Submit</button>
You don't really need any jQuery for this just a little regex should work.
const datesArr = [
'01-06-2019',
'01-07-2019',
'01-08-2019',
'01-09-2019',
'01-10-2019',
]
const newDates = []
const regex = /(\d\d)-(\d\d)-(\d{4})/
for (let date of datesArr) {
newDates.push(date.replace(regex, '$2/$1/$3'))
}
console.log(newDates)
function convertToFormat(data) {
var _dataSplit = data.split('\r\n');
var _length = _dataSplit.length;
var _finalData = '';
for (var i=0;i<_length;i++) {
var _dataDSplit = _dataSplit[i].split('-');
_finalData += _dataDSplit[1]+'/'+_dataDSplit[0]+'/'+_dataDSplit[2]+'\r\n';
}
return _finalData;
}
You can get the text area value on clicking submit like the below snippet. You can do your date manipulation (Learn some string manipulation to do the formatting. Refer - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
function formatText() {
var textAreaValue = $('#my-text').val();
// Do the necessary formatting here
var formattedText = 'test';
$('#my-text').val(formattedText);
}
.btn {
display: block;
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<textarea id="my-text"></textarea>
<button class="btn" onClick="formatText()">Submit</button>
</div>
Try using regex replace.
Regex demo here
let dates = document.getElementById('dates');
console.log(dates.value.replace(/(\d{2})-(\d{2})-(\d{4})/g, '$2/$1/$3'))
<textarea id="dates" rows="6" cols="30">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>
Right now I am trying to figure out how to append CREATED text to a CREATED p element depending on what a user enters into an input text field.
If I set the text after the createTextElement method, it displays just fine when I click the button. BUT what I want is: the user enters text in the input field and then upon clicking the button, the text get's added to the end of the div tag with the id of "mydiv". Any help is appreciated.
HTML:
<body>
<div id="mydiv">
<p>Hi There</p>
<p>How are you?</p>
<p>
<input type="text" id="myresponse">
<br>
<input type="button" id="showresponse" value="Show Response">
</p>
<hr>
</div>
</body>
JAVASCRIPT:
var $ = function(id) {
return document.getElementById(id)
}
var feelings = function()
{
$("myresponse").focus();
var mypara = document.createElement("p");
var myparent = $("mydiv");
myparent.appendChild(mypara);
var myText = document.createTextNode($("myresponse").value);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
$("displayedresponse").appendChild(myText);
}
window.onload = function() {
$("showresponse").onclick = feelings;
}
You need to apply an argument to createTextNode function
You need to read the value of the input field so you can see the text.
Since you will reference mydiv on every click, i think moving mydiv variable to parent scope will suit you better
var $ = function (id) {
return document.getElementById(id)
}
let mydiv = $('mydiv');
$("showresponse").addEventListener('click', feelings);
function feelings() {
let textInput = $('myresponse').value;
var mypara = document.createElement("p");
var myText = document.createTextNode(textInput);
mypara.setAttribute("id", "displayedresponse");
mypara.appendChild(myText);
mydiv.appendChild(mypara);
$("displayedresponse").appendChild(myText);
}
I'm trying to create <div> elements with child <p> elements; the <div> elements are being assigned a class of "clock" + a number (increments). While the elements themselves seem to be created, adding text (in my case a moment object) to the <p> element doesn't work.
HTML:
<body>
<select class="tz_list" name="timezones">
<option value="default">Please Select a Timezone</option>
</select>
<input type="button" name="addClock" value="Add Clock" class="button">
</body>
JS:
$(document).ready(function () {
var now = moment();
console.log(now);
//var repeat = setInterval(displayTime, 200);
var tzones = moment.tz.names();
tzones.forEach(function(key,value){
$('<option/>').val(key).html(key).appendTo('.tz_list');
});
var repeat;
var clock_count = 1;
var timezone ="";
function displayTime(timezone, clock_number) {
console.log(timezone);
var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
console.log(location);
//$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
var selector = '.clock '+clock_number.toString() + ' p';
console.log(selector);
//$('.clock '+clock_number.toString()).css({"height":"100px", "width":"500px"});
$(selector).text(location.toString());
};
$('.button').on('click', function(e){
console.log(e.target.value);
var div = '<div class="clock '+clock_count.toString()+'"><p></p></div>';
$(div).insertAfter('.button');
clock_count+=1;
displayTime(timezone, clock_count-1);
});
$('.tz_list').on('change', function(event){
console.log(event.target.value);
timezone = event.target.value;
});
});
What am I missing?
Here is a JSFiddle
Instead creating class "clock " try to create with out giving space. It will work.
function displayTime(timezone, clock_number) {
console.log(timezone);
var location = moment().tz(timezone).format("ddd, MMMM Do YYYY, HH:mm:ss");
console.log(location);
//$('.clock '+clock_number)[0].childNodes[0].nodeValue = timezone;
var selector = '.clock'+clock_number.toString() + ' p';
console.log(selector);
//$('.clock'+clock_number.toString()).css({"height":"100px", "width":"500px"});
$('.clock'+clock_number.toString()).text(timezone);
$(selector).text(location.toString());
};
$('.button').on('click', function(e){
console.log(e.target.value);
var div = '<div class="clock'+clock_count.toString()+'"><p></p></div>';
$(div).insertAfter('.button');
clock_count+=1;
displayTime(timezone, clock_count-1);
});
Change this line:
$('.clock.'+clock_number.toString()).text(timezone);
add the "." after clock but is not a god practice add number as class, instead use something like clock_1 (or clock1 like the answer below)
how can I get the contents of span ?
I'm looking for a way for all of this to be vanilla, not jQuery
javascript (and a little jQuery)
var swear_words_arr=new Array("bad","evil","freak");
var regex = new RegExp('\\b(' + swear_words_arr.join('|') + ')\\b', 'i' );
function validate_user_text() {
var text = document.getElementById('myInput');
text.text();
if(regex.test(text)) {
window.location="http://www.newlocation.com";
return false;
}
}
var myVar=setInterval(function(){validate_user_text()},1000);change
here's my html
<div id="textArea">
<span id="myInput" contenteditable="true">kfjdkfj</span>
</div>
<br />
<form name="form1" method="post" action="">
<textarea rows="3" cols="40" name="user_text" style="border:2 solid #808080; font-family:verdana,arial,helvetica; font-weight:normal; font-size:10pt" onclick="select_area()"></textarea>
<br />
<input type="button" value="Submit" onclick="return validate_user_text();"></form>
Thank You
Give this a shot:
var input = document.getElementById("myInput");
var text = input.innerHTML;
You can use textContent
Taken from MDN:
// Given the following HTML fragment:
// <div id="divA">This is <span>some</span> text</div>
// Get the text content:
var text = document.getElementById("divA").textContent;
// |text| is set to "This is some text".
// Set the text content:
document.getElementById("divA").textContent = "This is some text";
// The HTML for divA is now:
// <div id="divA">This is some text</div>
There is an issue here:
var text = document.getElementById('myInput');
text.text();
You never assigned the text of the input to any variable.
Following your pattern above, you could do:
var txt = document.getElementById('myInput'),
txt = text.text();
The second variable updates the previous variable 'txt' to hold the text of the original 'txt' variable, which was a selector.
You could do this as well (vanilla javascript, jsfiddle):
var txt = document.getElementById('myInput').innerHTML;
//or
var txt = document.getElementById('myInput').textContent;
Instead of using...
text.text();
Try using...
text.innerHTML;
I've only found .text() to work when you're using a jQuery selector.
$('#myInput').text();
var text = (document.getElementById("myInput")).innerHTML
or the abridged form:
var text = $('#myInput').text()
What I want to do is whenever I type a value in the text field, the value typed will be displayed right away.
How do I do it exactly? Is there anyway I could put the value in a variable and use it right away without using onClick?
Here is how I would do it:
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()">
<div id="div1"></div>
I don't think you can do it without any events.
Maybe you can do it with HTML5's <output> tag. I don't know it very well, but try some research.
W3Schools have some good examples.
Hope this can help you
Without using the change event? Why on earth would you want this? The only alternative I can think of would be polling at an interval. Something like:
var theValue = "";
var theTextBox = document.getElementById('myTextBox');
// Run 10 times per second (every 100ms)
setInterval(function() {
// Check if the value has changed
if(theTextBox.value != theValue)
{
theValue = theTextBox.value;
}
}, 100);
<script>
function change(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
function changenew(){
var el1 = document.getElementById("div1");
var el2 = document.getElementById("text");
el1.innerHTML = el2.value;
}
</script>
<input type="text" id="text" onkeypress="change()" onchange="changenew()">
is it Possible
you can check to see if your input field is in focus, then listen for any key input events and update your display field with the appropriate characters.
html:
<input type="text" id="myText"/>
<span id="output"></span>
js:
var myText = document.getElementById("myText");
myText.onkeyup = function(){
var output = document.getElementById("output");
output.innerHTML = this.value;
}
demo : http://jsfiddle.net/seUBJ/