value of textarea returned empty - javascript

I have a HTML form that contains a textarea and submit button. and a JS script that takes the value of the textarea.
The issue I'm facing is when I type text into the textarea and hit submit, the textarea value is empty. HOWEVER, if I hard code text into the textarea the hardcoded value is returned. If I erase the hardcoded value and delete the hardcoded value and type in my own, the hardcoded vale is still returned.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="js/jquery/jquery-1.9.1.min.js"></script>
<script src="contentForm.js"></script>
</head>
<body>
<form method="post" >
<textarea name ="editor" id="editBox" rows="5" cols="2">type</textarea>
<p><input type="submit" id="submit" value="Submit"></p>
</form>
</body>
</html>
JS
function add() {
$("#submit").click(function() {
var message = "start js";
console.log(message);
var contents = $("textarea").val();
if(contents === undefined) {
console.log("contents undefined");
}
console.log(contents);
var item = {"id":"12", "content": contents};
var obj = JSON.stringify(item);
var obj2 = JSON.parse(obj);
console.log(obj2.id);
console.log(obj2.content);
});
}
$(document).ready(function () {
add();
});
Notice how the textarea above has "type" preloaded. That's the returned value. If I leave it empty, type in my own text in the form and hit submit, the console log shows empty for the value of contents.
I've tried this as well (using textarea id)
var contents = $("#editBox").val();
I'm assuming the issue lies with POST. Because when I hit enter, the text I entered is replaced with "type" (pre-loaded text).
Can POST interfere with it? How else can I go about retrieving the value?

I am not sure of the actual problem, but something strange I have noticed in past few days. console.log() does not work in chrome in few cases like this one. May be it is a firebug bug? Anyways, replaced console.log() with alert and removed the default value from textarea.
Updated fiddle: http://jsfiddle.net/eVmQ9/2/
This seems to work on chrome and firefox.

Related

Missing eye icon in a password field when using template tag

I understand, why I see no eye icon in a input field with type "password", when I use the template tag.
For this example, I create a simple single HTML file:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Sample</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
document.addEventListener('click', () => {
/* It's not ok. (Second) */
const templateNode = document.getElementById('testTemplate');
const cloneNode = templateNode.content.cloneNode(true);
document.body.insertBefore(cloneNode, null);
/* It's ok. (Third) */
const form = document.createElement('form');
const input = document.createElement('input');
input.type = 'password';
form.appendChild(input);
document.body.appendChild(form);
}, { 'once': true });
</script>
</head>
<body>
<!-- Second //-->
<template id="testTemplate">
<form>
<input type="password">
</form>
</template>
<!-- First //-->
<form>
<input type="password">
</form>
</body>
</html>
You can run this local or on a server. I try it with Edge or Chrome. It's the same effect. After you click in the document, two input fields as type "password" added. The first input field shows the eye icon. The second (from template) has no eye. The third input field (created with the method createElement) has the eye, again.
I know, how I can toggle this with javascript, but I am trying to understand, where the error is. I don't think, it's a bug. I have the same result, when I split the files (html, javascript).
Thanks for your clarification.
You can't see current html element because it is used as a holder of an html, this element is not rendered by html but can be used by JavaScript (example: copying items), you could use an "iframe" as tag by setting up scr="" option with url (ex. scr="https://stackoverflow.com", the page should be on your server, it wouldn't load from any other sources) to html page if you want item to appear.
some documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template
Thanks for the answer.
I was firmly convinced that this eye icon is now displayed by default. But with Chrome, Firefox and Edge only Edge shows this eye....
Now about the problem in Edge. The link to the template tag was helpful, even if I already knew it. The content of the template tag is only parsed. If this is then added to the DOM with cloneNode, then it is rendered (as I understand it).
What was the solution now? In the german version of this article importNode is used instead of cloneNode. I'm from German.
I changed these lines:
const templateNode = document.getElementById('testTemplate');
const cloneNode = document.importNode(templateNode.content, true);
document.body.insertBefore(cloneNode, null);
https://developer.mozilla.org/de/docs/Web/HTML/Element/template
So the Edge shows this eye icon after adding it. Where the exact difference between cloneNode and importNode lies, I don't know yet. There I have to read again.

Javascript: Taking in User-Input

I have explicitly defined a Javascript file for my HTML document. In my HTML, I have created a text box where the user can type in their name, then click a button called "submit."
In JS, as soon as they click "submit," I want to store what they have entered as their name in a variable (I'm using eventListener to know when they click "submit"). My question is, how would I be able to do this without using onclick in my HTML doc? Here is my following code at the moment:
my_button.addEventListener('click', my_function);
function my_function(){
alert("Hello world!");
}
One way would be to use oninput event and every time the user types in something update the variable in which you want to store the input. The input tag would look like this: <input type="text" oninput="myFunction()"> and in the function that is declared as the handler you can take the input and store wherever you want.
You can have the code separate. All you'd have to do in the HTML document is to load the javascript file.
Here's a snippet. First the content of the javascript file, and below the simplified HTML document.
let myButton = document.getElementById("theButton");
myButton.addEventListener('click', my_function);
function my_function(){
alert("Hello world!");
}
<button id="theButton">Test</button>
to add a separate javascript file do this anywhere in your html
<script type='text/javascript' src = 'path/filename' > </script>
to get the value of the input yoy need to slect it first. then you get the value via the value property.
see this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id="my_input" type="text">
<button id="my_btn">click</button>
</body>
</html>
then you can use the following javascript.
var my_button = document.querySelector('#my_btn');
var my_input = document.querySelector('#my_input');
var value;
my_button.addEventListener('click',function () {
value = my_input.value;
alert(value);
})
hope this helps!

Wrong getting value when key is pressed

I try to get value from text input when key is down.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" onkeydown="console.log(this.value)">
</body>
</html>
Code demo: http://jsbin.com/funexipure/1/edit?html,console,output
Trouble description:
When I write 1 I have "" as value in console.
When I write 2 after this I have "1" as value in console, and so on
So, How I can get actual current value when key is down? Thank you very much.
You can use onkeyupto get what desire output is
<input type="text" onkeyup="console.log(this.value)">
Keyup function is quite good but it doesn't work if you paste the value with mouse click.
Try this
$('input').on('input propertychange', function(){
console.log($(this).val());
})
This will work in keyboard typing also when you paste with mouse click.
Reason
keyup check when you press the key from keyboard but propertychange work when you change any property anyway.

getElementByID.innerHTML is failing to change text

I am new to HTML and Javascript and I decided to try write a basic shopping cart.
I have a problem though. Why doesent this:
if(totalItems == 0)
{
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!";
}
Change this:
<b id = "yourCartContains">0</b>
To say "your cart contains no items" instead of 0?
The function definitely works, because I have tried switching the function to show an alert and it does this without any problems - so function works, but for some reason the function does not change the text.
Here is the function with the alert (I even changed totalItems to 0 to prove function is being called):
var totalItems = 0;
if(totalItems == 0)
{
alert("Random Alert is called upon function being executed");
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!"; <!-- But this isnt -->
}
I am debugging in chrome.
document.getElementByID().innerHTML definitely works.
Make sure:
document refers to the same document the element is in (you're not working with an iframe or such).
you call the function when the element is attached to the DOM.
This doesn't work:
<script>document.getElementById('foo').innerHTML = 'bar';</script>
<b id="foo"></b>
This works:
<b id="foo"></b>
<script>document.getElementById('foo').innerHTML = 'bar';</script>
your html is valid. It could be that invalid markup doesn't let your browser find the correct element.
Anyway, if you're working in chrome, you really should debug with the console and not with "alerts". Press F12 (on Windows / Linux) or Cmd + Opt + I on Mac. If there are any errors, you should see them in red in the console tab.
If there are no errors, do this:
if(totalItems == 0)
{
console.log('el: ', document.getElementById('yourCartContains'));
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!"; <!-- But this isnt -->
}
and see what your console tells you. (There probably will be an el: undefined)
This works for me. Have you loaded your script after your html?
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><b id = "yourCartContains">0</b></div>
<script>
var totalItems = 0;
if(totalItems == 0)
{
alert("Random Alert is called upon function being executed");
document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!"; <!-- But this isnt -->
}
</script>
</body>
</html>
<script type="text/javascript">
var totalItems = 0;
if(totalItems == 0)
{document.getElementById('yourCartContains').innerHTML = "Your cart contains no items!";}
</script>
<span id="yourCartContains" style="font-weight:bold"></span>
I have very painful experience using text to innerHTML.
Since my text contains a lot of dynamic element (select2 for searching option list) and I forgot to put ending quote . The text looks fine, in some cases, however, the innerHTML truncate the "submit" button is missing.
The text assigned to innerHTML is translate to other strange result automatically. if HTML syntax is not correct, it produces very weird string in innerHTML. the problem is intermittent, some case is fine, some are not good. Since project is big, I wasted whole night effort to fight to bug.
I finally figure a way to debug the dynamic element by using W3 validator (https://validator.w3.org/nu). copy and paste into a file and check the dynamic element syntax. There are some online HTML checker (https://www.freeformatter.com/html-validator.html).

Not setting focus to text field in Firefox

I faced a very interesting issue.
I'm trying to set the focus on a input field using Javascript (no jQuery, I tried that also but not worked) using window.onLoad.
Just take a look at this fiddle : setFocusOnLoad
It's working fine in chrome browser but not in Firefox. Is there any issue in Firefox? How can I resolve it.
Edited:
Here is the code I copied in html file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function onloadFocus(){
var name = document.getElementById('name');
// name.value='window.onload called';
name.focus();
}
window.onload=onloadFocus();
</script>
</head>
<body>
<div><input type='text' value='' id='name' name='name'></div>
</body>
</html>
Try adding a slight delay:
function onloadFocus(){
setTimeout(function() {
document.getElementById('name').focus()
}, 10);
}
Update jsFiddle
You must wrap the function-call into a function, otherwise it will be called immediately, not onLoad(the input is still unknown at this time):
window.onload=function(){onloadFocus();}
you should use window.onload=onloadFocus; instead of window.onload=onloadFocus(); because in case of window.onload=onloadFocus(); onloadFocus will run immediately and at that time input field may not be available.
jsfiddle
I got the solution for it. If you want to focus in Firefox. Write the focus function at the starting of the script tag.
<script type="text/javascript">
document.getElementById('name').focus();
// rest of the code here.
</script>
Hope this will help you.

Categories

Resources