Can't get the value of input element - javascript

I'm trying to format the value from an input field but I cant get the value
following is the HTML:
<div class="container">
<input type="text" id="search" />
<button id="btn" onclick="search()">Search</button>
</div>
And here is JS code:
var searchValue = document.querySelector('#search').value;
function search() {
console.log(searchValue);
}
Running that code logs empty value but if I remove the .value from querySelector line and use it as
console.log(searchValue.value);
then it works
What is the problem here!?

This is normal you set you variable searchValue outside of your function search() called on click.
Set your variable inside your function called on click.
If you get the value at a moment it has no value it is normal you get no value.
So if you get the value outside of your click function you won't have it. You must use .value at the moment you have a value.
function search() {
var searchValue = document.getElementById('search').value;
console.log(searchValue);
}
<div class="container">
<input type="text" id="search" />
<button id="btn" onclick="search()">Search</button>
</div>
Here as you can see we can read the value, because it has one at the time I am asking for. Above you set the value "in theory" after you clicked.
var searchValue = document.getElementById('search').value;
console.log(searchValue);
function search() {
console.log(searchValue);
}
<div class="container">
<input type="text" id="search" value="TEST"/>
<button id="btn" onclick="search()">Search</button>
</div>

You only update searchValue once when the page is loaded. At this time your text field still contains nothing (strictly an empty string) which is loaded into searchValue.
I assume you want to load it each time your button is clicked, so you need to do this inside search as demonstrated in the example.
function search() {
//Load the value from the text field each time we need it
let searchValue = document.getElementById("search").value;
//Log the value in console
console.log(searchValue);
}
<div class="container">
<input type="text" id="search" />
<button id="btn" onclick="search()">Search</button>
</div>

That should work:
function find()
{
serchValue = document.getElementById("search").value;
console.log(searchValue);
}

Related

JavaScript, get the value of input field on entry

I have a HTML page with an input field that the user enters a value into. The HTML code looks like this:
<div class="d-flex mg-b-0 mb-3" id="cbWrapper2">
<input type="number" name="message_average" class="form-control" id="id_message_average">
</div>
I'm trying to use JavaScript to get the value entered by the user so that I can then compare it against another value and write out the result, but I'm not sure how I collect the initial value being entered. What I have so far:
<script>
var value = document.getElementById("id_message_average").value;
console.log(value);
</script>
I'm just trying to write the value out for now so that I can tell it's working. Do I need to put it into some kind of event listener maybe when the user clicks onto another input field, or is there a way to have the script fire when a character is added?
There are indeed events to use to listen to changes in the input. One of them is called input, and you can use it like below.
The input event fires when the value of an <input>, <select>, or <textarea> element has been changed. More on MDN's doc.
var input = document.getElementById("id_message_average");
input.addEventListener("input", ()=>{
console.log(input.value)
});
<div class="d-flex mg-b-0 mb-3" id="cbWrapper2">
<input type="number" name="message_average" class="form-control" id="id_message_average">
</div>
For that you have add event listener.
let userInput = document.getElementById("id_message_average");
userInput.addEventListener("input", (e)=> {
console.log(e.target.value)
})'
You can use onClick function. If you choose onClick then you must need a button. Here is the example,
<form>
<div class="d-flex mg-b-0 mb-3" id="cbWrapper2">
<input type="number" name="message_average" class="form-control" id="id_message_average">
</div>
<button type='button' onclick="getInputValue()">Click me</button>
</form>
<script>
function getInputValue() {
var value = document.getElementById("id_message_average").value;
console.log(value);
}
</script>

Why can not input value be written outside of the function while h3 tag has no problem?

var aranan = document.getElementById("myInput")
var h3 = document.getElementsByTagName("h3")
var filter = aranan.value
function myFunction() {
console.log(filter)
console.log(h3[0])
}
<body>
<div class="container">
<h1 class="word">our store</h1>
<label for="">
Search
<input type="text" placeholder="Ara..." onkeyup="myFunction()" id="myInput">
</label>
<div class="menu" id="burasıda-id" data-name="yerel" data-surname="12.05.2020">
<h2>all</h2>
<h2>cakes</h2>
<h2>cupcakes</h2>
<h2>sweets</h2>
<h2>dougnuts</h2>
</div>
<section>
<h3 class="first">cake</h3>
<h3 class="second">cupcake</h3>
<h3 class="third">sweet</h3>
<h3 class="fourth">dougnut</h3>
</section>
</div>
<script src="app.js"></script>
</body>
Why does console.log(h3[0]) work but console.log(filter) does not?
When I put the var filter into the function it works too.
But what can be the reason? Is it about input value should be in the function?
Because this code executes immediately when the page loads:
var aranan = document.getElementById("myInput")
var h3 = document.getElementsByTagName("h3")
var filter = aranan.value
And when the page first loads, the element has no value:
<input type="text" placeholder="Ara..." onkeyup="myFunction()" id="myInput">
So filter will be empty. And since nothing ever changes that variable, it will always be empty.
In order to capture the value after the user has entered it, you need to read the .value property after it's been entered. Inside myFunction seems like a good place to do that:
function myFunction() {
console.log(aranan.value)
console.log(h3[0])
}
The key difference here is that aranan and h3 are holding references to page elements which do exist at the time those variables are set. But filter is holding a literal value, and at the time you set that variable no value is in that input.

Temperature Converter is giving me NaN

I need to make a temperature converter using forms and it has to have the ok button display the information and a clear button to clear all information.
This is what I have tried to do but it gives me NaN
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
Ok now my issue is that I need everything cleared even the Celsius data but I can't find a way for it to work
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(this.value)">
<input id= "reset1" type= "reset" value= "Clear" onclick="temperatureConverter">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Your code is not working because in your #button1 you wrote:
onclick="temperatureConverter(this.value)"
where this is not #inputFahrenheit but #button1. Therefore this.value actually equals to "OK".
To fix your problem, you need to change your temperatureConverter function to get value of #inputFahrenheit instead of using onclick="temperatureConverter(this.value)".
Similar situation happens in your #reset1, therefore your reset input will not work as well. You need to apply the same concept into your reset function, which I suggest to create a new function dedicated just for that.
Generally, it is not encouraged to use the same function to perform completely different actions.
function temperatureConverter(){
var input = document.getElementById('inputFahrenheit');
var value = input.value;
value = parseFloat(value);
var output = document.getElementById('outputCelcius');
output.innerHTML = (value - 32)/1.8;
}
function resetTemperature(){
/* clear the temperature */
console.log('clear');
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter()">
<input id= "reset1" type= "reset" value= "Clear" onclick="resetTemperature()">
</p>
<p>Celcius: <span id="outputCelcius"></span></p>
Here is the basics needed to get your code working. Basically it is simply just changing what value is passed to the temperatureConverter function. Before you were passing it the value of the button that was being clicked, not the value of the input element you were trying to read. Also, I'm unsure on this one as I didn't look it up, but the reset element wasn't working for me until I put your items inside of a <form> element.
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
<h2>Temperature Converter</h2>
<p>Type a value in the Fahrenheit field to convert te value to Celsius:</p>
<form>
<p>
<label>Fahrenheit</label>
<input id="inputFahrenheit" type="text" placeholder="Fahrenheit">
<input id= "button1" type= "button" value= "OK" onclick="temperatureConverter(document.querySelector('#inputFahrenheit').value)">
<input id= "reset1" type= "reset" value= "Clear">
</p>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
Please note that most of the time, people don't like putting the event listener in the on[event] attributes, and many developers will prefer that you do something more like this:
// () => {} is something called Arrow function notation, if you didn't know it already.
document.addEventListener('DOMContentLoaded', () => {
function updateOutput(value) {
// make sure you do some checking to avoid XSS attacks.
document.querySelector('#output').innerHTML = value;
}
// keeps the form from submitting since we don't have an actual form handler and this is all front-end
document.querySelector('#converterForm').addEventListener('submit',(e)=>{
e.preventDefault();
});
document.querySelector('#convert').addEventListener('click', () => {
updateOutput(convertToCelsius(document.querySelector('#fahrenheit').value));
});
});
function convertToCelsius(f) {
if(typeof f == 'string') f = parseFloat(f, 10);
if(isNaN(f)) {
throw new Error('Invalid parameter passed to function convertToCelsius');
}
return (f-32) * 5 / 9;
}
<form id="converterForm" action="/">
<input type="number" id="fahrenheit" placeholder="Fahrenheit value">
<input type="button" id="convert" value="Convert to Celsius">
<input type="reset" value="Clear">
<div id="output">
</div>
</form>
Other than that, a good way to check why a function isn't working is to use console.log in your code and then check the Javascript browser (in Chrome you can get to it by hitting ctrl+shift+j, in Firefox I believe it's ctrl+shift+i).
can't see you using any form.
your function,
function temperatureConverter(valNum) {
valNum = parseFloat(valNum);
document.getElementById("outputCelcius").innerHTML=(valNum-32)/1.8;
}
then,
<form id="tempConverter">
Convert: <input type="text" id="unit" name="converter" />
<input
type="button"
value="Submit"
onclick="temperatureConverter(document.getElementById('unit').value);"
/>
</form>
<p>Celcius: <span id="outputCelcius"></span></p>
apparently, if you console the value, you were obviously sending "OK" as param to the function(not the value of input field) which is NAN.

Restoring placeholder value to a search box after reset has been clicked

I am editing some javascript that has a search box with a variable as follows
var secondSearchTerm = $('#2nd-search').val();
In the HTML code '2nd-search' has a placeholder 'Enter search term'
I also have a reset button that clears the search as follows:
$("#2nd-reset-btn").on("click", function () {
return myNetwork.resetSecondSearch();
})
What I would like to do is to get the search box to re-populate with the placeholder when reset is clicked. Right now the last entered term remains in the search box.
Any ideas on how I can edit the code to do this?
Many thanks!
hi refer this link https://plnkr.co/edit/EtLmby5BdD5Yn70EIBRD?p=preview
js
// Add your javascript here
$(function(){
$("#reset").on("click", function () {
return $('#username').val('');
});
});
html
<input type="text" name="name" id = "username" placeholder="uname"/>
<button id="reset">Reset </button>
All you need to do is set the value to blank & take the focus away from the input(As some browsers hide placeholder on focus). The placeholder will be visible again. Try the following:
$("#2nd-reset-btn").on("click", function () {
secondSearchTerm.blur();
return secondSearchTerm.val('');
})
You can do it with pure JS only
Given the initial value
function reset() {
var initialValue = 'Enter your search term.';
var query = document.getElementById('myquery');
query.value = initialValue;
}
<input type="text" id="myquery" />
<input type="button" id="reset" onclick="reset()" value="Reset" />
Given the placeholder
function reset() {
var query = document.getElementById('myquery');
query.value = '';
}
HTML
<input type="text" id="myquery" />
<input type="button" id="reset" onclick="reset()" value="Reset" />

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

Categories