I want to take the value on an input field and display what the user has entered using JQuery on clicking a submit button. The problem is that when I click the button the console.log is blank without the user text and this is driving me crazy because I can't figure out why, here is my html:
const userLocation = $('#location').val();
$('#submit').on('click', getInfo);
function getInfo() {
console.log(userLocation)
}
#content {
width: 400px;
}
#request {
text-align: center;
}
.bl {
width: 300px;
}
#current {
text-align: center;
font-size: 2em;
}
#upcoming {
text-align: center;
}
.condition {
text-align: left;
display: inline-block;
}
.symbol {
font-size: 4em;
display: inline-block;
}
.forecast-data {
display: block;
}
.upcoming {
display: inline-block;
margin: 1.5em;
}
.label {
margin-top: 1em;
font-size: 1.5em;
background-color: aquamarine;
font-weight: 400;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forecatser</title>
</head>
<body>
<div id="content">
<div id="request">
<input id="location" class='bl' type="text">
<input id="submit" class="bl" type="button" value="Get Weather">
</div>
<div id="forecast" style="display:none">
<div id="current">
<div class="label">Current conditions</div>
</div>
<div id="upcoming">
<div class="label">Three-day forecast</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="./weather.js"></script>
</body>
</html>
Why does the console print blank lines with no value, what am I doing wrong?
You're reading only the initial value of the input, not after it has been clicked. You should read the value inside of your callback, to get it's value at the time of clicking:
$('#submit').on('click', getInfo);
function getInfo() {
const userLocation = $('#location').val();
console.log(userLocation)
}
Here is working sample with small change of your code
$('#submit').on('click', function(){
getInfo();
});
function getInfo() {
const userLocation = $('#location').val();
console.log(userLocation)
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Forecatser</title>
<style>
#content { width: 400px; }
#request { text-align: center; }
.bl { width: 300px; }
#current { text-align: center; font-size: 2em; }
#upcoming { text-align: center; }
.condition { text-align: left; display: inline-block; }
.symbol { font-size: 4em; display: inline-block; }
.forecast-data { display: block; }
.upcoming { display: inline-block; margin: 1.5em; }
.label { margin-top: 1em; font-size: 1.5em; background-color: aquamarine; font-weight: 400; }
</style>
</head>
<body>
<div id="content">
<div id="request">
<input id="location" class='bl' type="text">
<input id="submit" class="bl" type="button" value="Get Weather">
</div>
<div id="forecast" style="display:none">
<div id="current">
<div class="label">Current conditions</div>
</div>
<div id="upcoming">
<div class="label">Three-day forecast</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="./weather.js"></script>
</body>
</html>
Please check the working demo
https://jsfiddle.net/o2gxgz9r/73662/
$(document).ready(function() {
$('#submit').on('click', getInfo);
function getInfo() {
const userLocation = $('#location').val();
alert(userLocation);
}
});
Related
can i ask a question. I try to make a reading GPS ( the Latitude and Longitude ), i follow this link https://www.itilog.com/ but it just using innerHTMl or sthing. the idea is how to sending data ( the Latitude and Longitude ) into the input tag so that i can have the data the user who enter these data. Here are the code i follow W3school:
<!DOCTYPE html>
<html>
<body>
<p>Displaying location using Latitude and Longitude</p>
<button class="geeks" onclick="getlocation()">
Click Me
</button>
<input type="text" id="demo1" onkeyup="showLoc()"></input>
<script>
var variable1 = document.getElementById("demo1");
function getlocation() {
navigator.geolocation.getCurrentPosition(showLoc);
}
function showLoc(pos) {
variable1.innerInput =
"Latitude: " +
pos.coords.latitude +
"<br>Longitude: " +
pos.coords.longitude;
}
</script>
</body>
</html>
I have the code in html and css:
#NOTE: U need to using responsive to see the code files
this is html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="generateqr.css">
</head>
<body>
<div class="container">
<h3>Course's name</h3>
<div class="body">
<div class="small_container">
<button>Generate QR</button>
</div>
<div class="small_container">
<button>Your Files</button>
</div>
<div class="info">
<div class="title1">
<p>Longitude:</p>
<input placeholder="type here...">
</div>
<div class="title2">
<p>Latitude:</p>
<input placeholder="type here...">
</div>
</div>
<div class="location">
<a id="check" href="https://www.itilog.com/">check here if you don't know your location</a>
</div>
</div>
</div>
<div class="footer">
Back
</div>
</body>
</html>
and CSS file:
* {
background-color: #7879f1;
position: relative;
}
h3 {
text-align: center;
}
.body{
width: 110%;
height: 500px;
margin-left: -10px;
background-color: white;
position: absolute;
}
.small_container{
background-color: white;
margin-left: 10%;
margin-top: 20%;
display: inline-block;
}
.footer{
margin-top: 515px;
background-color: white;
width: 110%;
margin-left: -10px;
margin-bottom: -20px;
padding-bottom: 20px;
}
button{
height: 50px;
width: 100px;
margin-left: 20px;
}
a{
background-color: white;
margin-left: 50px;
padding-bottom: 20px;
}
.info{
width: 100%;
height: 20%;
margin-left: 10%;
background-color: white;
margin-top: 10%;
}
.input{
background-color: white;
}
input {
background-color: white;
}
p {
background-color: white;
display: inline-block;
padding-left: 10%;
}
.location {
margin-top: 20%;
background-color: white;
}
.title1{
background-color: white;
}
.title2{
background-color: white;
}
i hope that we can send the data to the input ( i already have 2 input tag for the Latitude and Longitude )
You can change inputs like that :
var input = document.getElementById("input");
input.value = 'value';
For your context i made a jsfidle for you understand how to do it :
<!DOCTYPE html>
<html>
<body>
<p>Displaying location using Latitude and Longitude</p>
<button id="_button">
Click Me
</button>
<input type="text" id="latitudeInput" value=""></input>
<input type="text" id="longitudeInput" value=""></input>
<script>
var button = document.getElementById('_button');
var latitudeInput = document.getElementById("latitudeInput");
var longitudeInput = document.getElementById("longitudeInput");
button.addEventListener('click', function(){
getlocation();
});
function getlocation() {
// Callbacks
const successCallback = (position) => {
// Set inputs values
latitudeInput.value = position.coords.latitude;
longitudeInput.value = position.coords.longitude;
};
// Manage error messages
const errorCallback = (error) => {
alert(error.code+' : '+error.message);
};
// Call
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
}
</script>
</body>
</html>
jsfiddle.net/EdvaldoFilho/ermup5a9/4/
Hope it helps you !
I am trying to make a to-do list by myself and it's going pretty well, but I can't remove the correct div. It always removes the first one in the pile. I am not creating new divs, I am basically cloning a template that I've made and setting the display as none.
let d = document.getElementById('botao')
d.addEventListener('click', addTarefa())
function addTarefa() {
let divtarefa = document.getElementById('TarefaEscondida')
clone = divtarefa.cloneNode(true)
clone.id = 'tarefa'
clone.class = "tarefa"
container.appendChild(clone)
clone.setAttribute('display', 'flex')
clone.setAttribute('class', 'tarefa')
clone.setAttribute('id', 'tarefa')
}
function suma() {
let father = document.getElementById('container')
let son = document.getElementById('tarefa')
let apaga = father.removeChild(son)
}
* {
margin: 0;
box-sizing: border-box;
}
body {
background-color: aqua;
}
header {
text-align: center;
background-color: rgb(255, 208, 0);
}
#container {
display: flex;
background-color: beige;
margin-top: 15px;
margin-left: 15%;
margin-right: 15%;
height: 90vh;
align-items: stretch;
padding-top: 8px;
flex-direction: column;
flex-wrap: nowrap;
gap: 8px;
}
.tarefa {
padding: 5px;
background-color: brown;
margin-left: 8px;
margin-right: 8px;
display: flex;
}
.texto {
border: none;
margin-left: 8px;
background-color: brown;
color: white;
width: 90%;
padding: 8px;
}
::placeholder {
color: white;
opacity: 1;
}
.remove {
float: right;
height: 40px;
width: 40px;
color: #333;
cursor: pointer;
}
#botao {
position: fixed;
background-color: brown;
height: 80px;
width: 80px;
border-radius: 50%;
bottom: .8%;
left: 1.5%;
text-align: center;
color: white;
font-weight: 900;
font-size: 4.5rem;
}
#TarefaEscondida {
padding: 5px;
background-color: brown;
/* margin-top: 8px; */
margin-left: 8px;
margin-right: 8px;
display: none;
}
#TextoEscondido {
border: none;
margin-left: 8px;
background-color: brown;
color: white;
width: 90%;
padding: 8px;
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>My To Do list</title>
</head>
<body>
<header id="header">
<h1>My To do list</h1>
</header>
<main id="container">
<div id="TarefaEscondida">
<input type="button" value="Feito" class="remove" onclick="suma()">
<input type="text" placeholder="Escreva aqui..." id="TextoEscondido">
</div>
<div id='tarefa' class="tarefa">
<input type="button" value="Feito" class="remove" onclick="suma()">
<input type="text" placeholder="Escreva aqui..." class="texto">
</div>
</main>
<div id="botao" onclick="addTarefa()">
<P>+ </P>
</div>
<script src="main.js"></script>
</body>
</html>
You don't need to bother with element IDs. DOM navigation will allow you to find the parent of the clicked element, and remove it:
<main id="container">
<div id="TarefaEscondida">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." id="TextoEscondido">
</div>
<div id='tarefa' class="tarefa">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." class="texto">
</div>
</main>
(Notice how I've changed the onclick so it passes this element)
And then your remove function can simply locate the parent of the clicked element and remove it.
function suma(element) {
element.parentNode.remove();
}
Also, please note: In your function that adds a new element, you should be aware of duplicating element IDs. That will create invalid HTML because IDs must be unique.
Here is a Fiddle example.
let d = document.getElementById('botao')
d.addEventListener('click', addTarefa())
function addTarefa() {
let divtarefa = document.getElementById('TarefaEscondida')
clone = divtarefa.cloneNode(true)
clone.id = 'tarefa'
clone.class = "tarefa"
container.appendChild(clone)
clone.setAttribute('display', 'flex')
clone.setAttribute('class', 'tarefa')
clone.setAttribute('id', 'tarefa')
}
function suma(element) {
element.parentNode.remove();
}
<main id="container">
<div id="TarefaEscondida">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." id="TextoEscondido">
</div>
<div id='tarefa' class="tarefa">
<input type="button" value="Feito" class="remove" onclick="suma(this)">
<input type="text" placeholder="Escreva aqui..." class="texto">
</div>
</main>
<div id="botao" onclick="addTarefa()">
<P>+ </P>
</div>
In .addEventListener you put function but don't call it.
d.addEventListener('click',addTarefa)
I made a form for an event. When I click the first radio button, then submit. The warning message disappears, however, if I click the second radio button, the warning does not. My question is the some function not suitable for this case? How do I revise it? What kind of case do we use some function? Thank you!
const form = document.querySelector('.apply__form');
function createWarning(node) {
// if there is no warning msg, then create one
if (!node.querySelectorAll('.warning__style').length) {
const warning__msg = document.createElement('p');
warning__msg.innerHTML = 'Please fill in';
warning__msg.classList.add('warning__style');
node.appendChild(warning__msg);
}
}
form.addEventListener('submit', e => {
e.preventDefault();
let result = [];
// Check the required answer for name, phone, email, resource
const reqAns = document.querySelectorAll('.required .answer');
const reqAnsArray = [...reqAns];
reqAnsArray.map(element => {
if (element.value === "") {
createWarning(element.parentElement);
}
if (element.value && element.parentElement.querySelectorAll('.warning__style').length) {
element.parentElement.lastChild.classList.add('warning__disappear')
}
result.push(element.value)
})
// Check the required answer for the type of applying event
const reqChoice = document.querySelectorAll('.required input[type=radio]');
const reqChoiceArray = [...reqChoice];
reqChoiceArray.some(element => {
if (!element.checked) {
createWarning(element.parentElement.parentElement);
}
if (element.checked && element.parentElement.parentElement.querySelectorAll('.warning__style').length) {
element.parentElement.parentElement.lastChild.classList.add('warning__disappear')
}
})
})
body, html {
box-sizing: border-box;
font-size: 16px;
}
.wrapper {
width: 100%;
background:#f0f0f0;
padding: 30px 0;
}
.apply__form {
border-top: 8px solid #f00;
margin: 0 auto;
max-width: 645px;
background: #fff;
padding: 50px;
}
.form__title {
font: normal normal bold 1.8rem "Microsoft JhengHei";
}
.event__info {
margin: 2rem 0;
font: normal normal normal 0.9rem "Microsoft JhengHei";
}
.event__info .event__place {
margin-top: 0.5rem;
}
.notice {
color: #e74149;
font: normal normal normal 1rem "Microsoft JhengHei";
}
.notice::before {
content: "*";
padding-right: 5px;
}
.questions {
width: 100%;
}
.question {
font: normal normal normal 1rem "Microsoft JhengHei";
margin-top: 50px;
}
.question .question__title {
margin-bottom: 20px;
}
.question .question__title::after {
content: "*";
color: #e74149;
padding-left: 5px;
}
.question:nth-child(4) .type1 {
margin-bottom: 23px;
}
.question:nth-child(6) .question__title::after {
content: none;
}
.sub__title{
margin-bottom: 30px;
}
.question .answer {
width: 250px;
padding: 5px;
}
.button__section {
margin-top: 55px;
font: normal normal normal 1rem "Microsoft JhengHei";
}
.submit__btn {
background: #fad312;
border-radius: 3px;
outline: none;
border: none;
padding: 1rem 2rem;
margin-bottom: 20px;
cursor: pointer;
}
.warning {
font-size: 14px;
}
.copy__right {
height: 30px;
background: #000;
color: #999;
text-align: center;
padding: 15px 0;
line-height: 30px;
font-family: "Microsoft JhengHei";
}
.warning__style {
color: #e74149;
font-size: 14px;
position: absolute;
}
.warning__disappear {
display: none;
}
.wrong__format {
border: 1px solid #f00;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="style.css">
<title>Lazy-Form</title>
</head>
<body>
<div class="wrapper">
<form class="apply__form">
<h1 class="form__title">ABC FORM</h1>
<div class="event__info">
<p class="event__time">Event time</p>
<p class="event__place">Event location</p>
</div>
<h3 class="notice">Must</h3>
<div class="questions">
<div class="question required">
<p class="question__title">Nick name</p>
<input type="text" placeholder="Answer" class="answer">
</div>
<div class="question required">
<p class="question__title">Email</p>
<input type="email" placeholder="Answer" class="answer">
</div>
<div class="question required">
<p class="question__title">Phone</p>
<input type="text" placeholder="Answer" class="answer" id="number">
</div>
<div class="question required">
<p class="question__title">type</p>
<div class="type1 radioType">
<input type="radio" name="type" id="bed">
<label for="bed">Bed</label>
</div>
<div class="type2 radioType">
<input type="radio" name="type" id="phone">
<label for="phone">Phone</label>
</div>
</div>
<div class="question required">
<p class="question__title">How do you know this?</p>
<input type="text" placeholder="Answer" class="answer">
</div>
<div class="question">
<p class="question__title">Other</p>
<input type="text" placeholder="Answer" class="answer">
</div>
</div>
<div class="button__section">
<input type="submit" class="submit__btn" value="Submit">
</div>
</form>
</div>
<script src="app.js"></script>
</body>
</html>
I see two potential issues here. You are using querySelectorAll, which returns a static nodeList. But this shouldn't be the issue here, just something you need to be aware of.
You are using the some method in a wrong way.
You need to give it a function which checks each element and returns true or false.
If any of the element matches, the some method returns true as a whole.
So, it should look more like. (element down there is not correct, but I hope you get the idea.)
var response = reqChoiceArray.some(element => {
if (!element.checked) {
return false;
}
if (element.checked && element.parentElement.parentElement.querySelectorAll('.warning__style').length) {
return true;
}
})
if(!!response){
element.parentElement.parentElement.lastChild.classList.add('warning__disappear');
}else{
createWarning(element.parentElement.parentElement);
}
Firstly i'll need to apologize as I'm very new to coding and this might be very easy to be solved
I need to get the name of the file and display it within the blue box. My js script's last part does not work:
var filename = e.target.value.split('\\').pop();
$("#label_span").text(filename);
The message below was displayed when I tried it using the codesnippet
{
"message": "Uncaught ReferenceError: e is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 109,
"colno": 19
}
Thanks in advance!
$(document).ready(function() {
$("#file").on("change", function() {
var files = $(this)[0].files;
if (files.length >= 2) {
$("#label_span").text(files.length + " files ready to upload");
} else {
var filename = e.target.value.split('\\').pop();
$("#label_span").text(filename);
}
});
});
body {
font-family: 'Varela Round', sans-serif;
font-family: 16px;
}
h1 {
color: #3c4954;
text-align: center;
margin-top: 100px;
font-size: 36px;
}
p {
color: #a4b0b9;
line-height: 200%;
}
* {
box-sizing: border-box;
}
footer {
position: absolute;
width: 100%;
bottom: 20px;
}
.form-div {
margin-top: 100px;
}
.input-label {
background: #009688;
color: #fff;
padding: 30px;
cursor: pointer;
}
.input-label:hover {
background: #26a69a;
cursor: white;
cursor: pointer;
padding: 30px;
transition: .2s;
}
.fa {
margin-right: 10px;
}
#file {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<html>
<head>
<title>Custom Input</title>
<link href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="Test_Impor.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body align="center">
<header>
<h1>Custom Input</h1>
</header>
<div class="form-div">
<form>
<label for="file" class="input-label">
<i class = "fa fa-upload"></i>
<span id = "label_span">Select files to upload</span>
</label>
<input id="file" type="file" multiple="true" />
</form>
</div>
<script src="Test_Import.js"></script>
</body>
</html>
Each element of the files array is an object with a name property. So just access the first element of the array and get its name.
You don't need to use split(), as it just contains the name, not the full path.
And instead of $(this)[0] you can just use this.
$(document).ready(function() {
$("#file").on("change", function() {
var files = this.files;
if (files.length >= 2) {
$("#label_span").text(files.length + " files ready to upload");
} else if (files.length == 1) {
var filename = files[0].name;
$("#label_span").text(filename);
} else {
$("#label_span").text("Select files to upload");
}
});
});
body {
font-family: 'Varela Round', sans-serif;
font-family: 16px;
}
h1 {
color: #3c4954;
text-align: center;
margin-top: 100px;
font-size: 36px;
}
p {
color: #a4b0b9;
line-height: 200%;
}
* {
box-sizing: border-box;
}
footer {
position: absolute;
width: 100%;
bottom: 20px;
}
.form-div {
margin-top: 100px;
}
.input-label {
background: #009688;
color: #fff;
padding: 30px;
cursor: pointer;
}
.input-label:hover {
background: #26a69a;
cursor: white;
cursor: pointer;
padding: 30px;
transition: .2s;
}
.fa {
margin-right: 10px;
}
#file {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<html>
<head>
<title>Custom Input</title>
<link href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="Test_Impor.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body align="center">
<header>
<h1>Custom Input</h1>
</header>
<div class="form-div">
<form>
<label for="file" class="input-label">
<i class = "fa fa-upload"></i>
<span id = "label_span">Select files to upload</span>
</label>
<input id="file" type="file" multiple="true" />
</form>
</div>
<script src="Test_Import.js"></script>
</body>
</html>
You need to provide e to your event callback function
$("#file").on("change", function(e) {...}
I'm trying to change colour of a button to show which images is displayed with JavaScript. Something similar to :Active in CSS. I've been looking for hours, I've managed to change just about every other element on the page except for the one I actually want to change, all I need is to change the background color of the clicked button and then revert back to original color a different button is clicked. Any help would be much appreciated.
<! doctype html>
<html>
<head>
<title>Task 2</title>
<!--styles-->
<style>
body {
margin: 0;
background-color: mediumpurple;
}
header {
margin: auto;
width: 90%;
background-color: orangered;
height: 50px;
text-align: center;
}
#content {
width: 80%;
background-color: green;
margin: auto;
}
nav {
float: left;
background-color: greenyellow;
width: 30%;
height: 750px;
text-align: center;
}
#pictureFrame {
float: left;
width: 70%;
height: 750px;
background-color: deeppink;
}
footer {
margin: auto;
width: 90%;
background-color: orangered;
height: 50px;
text-align: center;
clear: both;
}
.button {
margin-top: 100px;
background-color: white;
border-radius: 20px;
width: 70%;
height: 75px;
}
#img {
margin-top: 19%;
margin-left: 35%;
width: 300px;
height: 300px;
}
</style>
<script type="text/javascript">
function pic1() {
document.getElementById("img").src = "images/starbucks.png";
}
function pic2() {
document.getElementById("img").src = "images/muffin.png";
}
function pic3() {
document.getElementById("img").src = "images/costa.png";
}
</script>
</head>
<body>
<header>
<h1>Coffee</h1>
</header>
<section id="content">
<div id="pictureFrame">
<img src="" id="img" />
</div>
<nav>
<button id="button1" class="button" onclick="pic1()">Starbucks</button>
<br/>
<br/>
<button id="button2" class="button" onclick="pic2()">Muffin Break</button>
<br/>
<br/>
<button id="button3" class="button" onclick="pic3()">Costa</button>
</nav>
</section>
<footer>
<h1>This is a footer</h1>
</footer>
</body>
</html>
By clicking on each button simply change the background of that button with style.background='color'. Also reset the color of other two buttons. Simply create a function to reset the background color.
<script type="text/javascript">
function reset(){
document.getElementById("button1").style.background='white';
document.getElementById("button2").style.background='white';
document.getElementById("button3").style.background='white';
}
function pic1() {
document.getElementById("img").src = "images/starbucks.png";
reset();
document.getElementById("button1").style.background='red';
}
function pic2() {
document.getElementById("img").src = "images/muffin.png";
reset();
document.getElementById("button2").style.background='red';
}
function pic3() {
document.getElementById("img").src = "images/costa.png";
reset();
document.getElementById("button3").style.background='red';
}
</script>
Fiddle : https://jsfiddle.net/tintucraju/6dkt0bs2/