Why does 'this.value' work but e.value doesn't? - javascript

I'm new. I've read a lot on stackoverflow, but this is my first question. Hopefully it's not a silly one. I know the crowd can be harsh at times, and often deservingly so. :)
In the following code, when you enter text in the first input box, the alert does not show what you input. However in the 2nd box, when you key something in, the alert shows it.
The difference is in the use of 'this.value' vs 'e.value'.
I'm thinking that they should both work since 'e.value' references an element and I thought 'this.value' does also, but obviously am missing something since it does not do the same thing.
Thanks in advance.
<!DOCTYPE html>
<html>
<head><script>
window.onload = function () {var e;
e = document.getElementById('eInput');
if (!e.onkeyup) {e.onkeyup = function () {alert (e.value); }; }
e = document.getElementById('thisInput');
if (!e.onkeyup) {e.onkeyup = function () {alert (this.value); }; }
}
</script></head>
<body>
<input type="text" id='eInput'></input><br><br>
<input type="text" id='thisInput'></input>
</body>
</html>

The e in the function should refer to the element that triggered the event. You should alter it to function (e) {alert (e.target.value); }; }
Now the e is the event that triggerd the onkeyup function and you can access the target to get the value.
see http://jsfiddle.net/yAaYX/

The reason why the first input doesn't work - your e variable is getting overwritten and it points to the 2nd input, which is empty at that time.
If you remove the 2 lines of the 2nd input you'll see it works just fine with e.value-
working example
Or just give the variables different names - e1 and e2 - example

Related

Get true value of textarea

Recently I encountered an issue with the textarea. If I have a textarea likeso,
<textarea>Hello World</textarea>
And I get the contents of it with JS,
var textareaText = document.getElementsByTagName('textarea')[0].value
The variable textareaText is Hello World. But if I were to change the value of the textarea and re-run the JS. It would still result in Hello World despite the true current value being something else. I've looked this up and seen +5 answers but all of them use jQuery which is something I don't use or know (to translate) and none pure JS. If anyone could help me out it would be greatly appreciated. Also some of the answers seemed to be just for one textarea. In my project I'd have +1,000 so I'd like to avoid that.
This should work, no matter how many <textarea>'s you use, this should work:
<textarea id="textarea1">hello</textarea>
<textarea id="textarea2">goodbye</textarea>
<button id="button">button</button>
<script type="text/javascript">
var button = document.getElementById("button");
button.onclick = function() {
alert(document.getElementById("textarea1").value + "\n" + document.getElementById("textarea2").value);
};
</script>
I just tested it and it works, no matter which values I change, and even if I change both. The trick is to not store the values, as they aren't updated, so you should get the value on-the-spot.
Although it was against the questions guidelines, with "1000+" textareas, setting a JavaScript variable for each one might slow down loading times. May I suggest jQuery, with the same HTML?
<script type="text/javascript">
$("#button").on("click", function () {
alert($("#textarea1").val() + "\n" + $("#textarea2").val());
});
</script>
Of course, feel free to mix up and change up the code provided above. Hope this helps!
It works fine in my computer:
function getText(){
var textareaText = document.getElementsByTagName('textarea')[0].value;
console.log(textareaText);
};
<textarea>Hello World</textarea><br>
<button type="button" onclick="getText();">Get text</button>
May be?
<textarea id="text-area">Hello World</textarea>
var el = document.getElementById("text-area");
var textareaText;
el.addEventListener("input", function(e) {
textareaText = e.target.value;
console.log(e.target.value);
});

JavaScript and WordPress: button click not found by addEventListener

To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!

addEventListener Module Pattern

I don't know why but when I click on "button" nothing happens...
No message in console, no error. How to fix it ?
JS
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
HTML
<button id="addBird">Add Bird</button>
Just tried this example in CodePen:
http://codepen.io/JasonGraham/pen/pbowXz
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
As far as I can see, your code appears to be working as expected. In Chrome, clicking on the button causes the "addBird" message to be logged to the console each time.
Are you expecting something different?
This happens because the JavaScript loads before the DOM (basically, the HTML markup) is ready. Therefor, the button variable equals NULL.
Two ways to solve this:
Move your JavaScript at the end of the page, just before the </body> tag.
Wrap your JavaScript code with jQuery's document ready function:
$(function() {
// code here
});
Ok if I insert and outside the #birdMod It works... So it was not the .render() function. Thank you for your help. :)

Getting the contents of a span to change as I change a number input

I had a more complicated form working a couple of days ago, but suddenly it stopped working and I'm rubbish at saving versions, so I've taken it right back to basics, and I can't get it to work. What am I doing wrong? Am I using onInput incorrectly?
<input type="text" id="number-of-copies-value" onInput="quote()" value="500">
<span id="total-cost-value">0.00</span>
And here's the Javascript:
function quote() {
var totalcostvalue = document.getElementById("total-cost-value");
var numberofcopiesvalue = document.getElementById("number-of-copies-value").value;
var totalcost = (+numberofcopiesvalue);
totalcostvalue.innerHTML=totalcost.toFixed(2);
}
quote();
https://jsfiddle.net/tod0wusv/1/
Your HTML expects the quote() function to be globally available. Make sure that is the case.
If I change your fiddle to have quote() available on global window object like,
window.quote = function quote() {
// ...
};
the fiddle starts working again.
WORKING FIDDLE
If I create a local HTML file with your content, it works right away, which makes sense since quote() is defined on global scope.
Looks like JSfiddle executes the JavaScript in a function scope which breaks your quote() call.
If you care about browser compatibility I would suggest using the onkeydown event with a setTimeout function as described here Detecting "value" of input text field after a keydown event in the text field?
To make this work in JSFiddle, change the javascript "load type" setting in your JavaScript settings to one of the "no wrap" options.
HTML
<input type="text" id="number-of-copies-value" onkeydown="window.setTimeout(function() { quote(); }, 1)" value="500">
<span id="total-cost-value">0.00</span>
JavaScript:
function quote() {
var totalcostvalue = document.getElementById("total-cost-value");
var numberofcopiesvalue = document.getElementById("number-of-copies-value").value;
var totalcost = (+numberofcopiesvalue);
totalcostvalue.innerHTML = totalcost.toFixed(2);
}
quote();
I've updated your JSFiddle...
https://jsfiddle.net/tod0wusv/6/

Div does not refresh when last character is deleted from input

I'm currently making a search function using a onkeyup="Search();" like this:
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
The function for it is:
<script type="text/javascript">
function Search() {
var inputVal = $('#IDsearch').val();
$.post('searchTest.php', {postname: inputVal},
function (data) {
$('#IDsearch').val(data)
});
$('#divRefresh').load('searchTest.php');
}
</script>
Yes, I am using the same file to both put the value in a php $_SESSION['value']; AND to store the new div data. That's no problem, it works, it does fine.
But when I delete my last character from my search box, I need to press backspace twice in order for my div to update.
Say I had a textbox with "a" in it. I will press backspace to update the a, and nothing will happen. Once I press backspace again, my div will update and post all the original values again.
Am I missing something obvious?
It's supposed to work the same way http://www.datatables.net/ does.
I have asked a question about this program before, but not about this issue, I hope it's not a problem.
I would go throught $("#IDsearch").keyup(function(){});
Tried your code with the function and didn't work, even with $("#divRefresh").html(theInputOfYours); The other way I mention to you works perfectly, even with backspace.
$(document).ready(function() {
$("#IDsearch").keyup(function() {
var value = $(this).val();
var posting = $.post("your_php_file.php", {val: value})
posting.done(function( data ) {
$( "#divRefresh" ).html(data);
});
});
});
The posting is a very basic example I can give, I use to go with $.ajax() function
Unfortunately, the behavior of keyup/keypress/keydown can be finicky sometimes, especially across different browsers.
A possible solution to ensure changes are tracked would be a listener that would track changes via a setInterval function that runs at an interval you specify.

Categories