How the user can change the city name in this request - javascript

i'm starting learning JS and i don't understand how to change ( as a user ) the city name on this request .
It's working when in my request i put the city name in askWeather.open("GET", "url.../london)
but how can i give the possibilty to the user to change this value ?
Thanks a lot
askWeather.onreadystatechange = function () {
if (this.readyState = XMLHttpRequest.DONE && this.status == 200) {
var response = JSON.parse(this.responseText);
let resp = document.getElementById('result');
let ask = document.getElementById('btn');
ask.addEventListener('click', function () {
resp.innerHTML = response.current_condition.condition;
});
}
};
askWeather.open("GET", "https://www.prevision-meteo.ch/services/json/lille");
askWeather.send();

You need an event listener for the value that has been typed and also an event Listener when the request should be sent.
This is one way how you could let the user to change the city:
let city = 'london'; // The default value, if the user didn't try to set a value
document.getElementById('city').addEventListener('keyup', (e) => {
city = e.target.value;
});
document.getElementById('send').addEventListener('click', () => {
askWeather.open("GET", `url.../${city}`)
askWeather.send();
});
<input id="city" type="text">
<button id="send">Send the request</button>
But you could use a simple form as well with only 1 event listener, like:
let city = 'london';
document.getElementById('my-form').addEventListener('submit', () => {
city = document.getElementById('city').value;
askWeather.open("GET", `url.../${city}`)
askWeather.send();
});
<form id="my-form" action="">
<input id="city" type="text">
<input type="submit" id="send">
</form>

Declare a variable for the city name, you can set this value from wherever you wish, like from user input.
const city = 'lille';
askWeather.open("GET", `https://www.prevision-meteo.ch/services/json/${city}`);

Related

Getting the text within an input box

How can I get the text within an input box and go to the page ending with it? For example, if someone types "home" in an input box it directs the user to the URL https://mysitename.com/home.
You can do this using document.location.href.
let btn = document.querySelector('button');
let ipt = document.querySelector('input[type=text]');
btn.onclick = function() {
document.location.href = "https://mysitename.com/" + ipt.value;
}
<input type="text" placeholder="link name">
<button>go</button>
You can check this solution. This will append the input value to your current host name.
If you want predefined hostName then your can set the value to this variable. const hostName = "your host name here"
You can use window.location.href = yourNewUrl to redirect to new address. I've commented out the redirection line. You need to uncomment that.
const form = document.querySelector('#myForm');
const inputField = document.querySelector('#name');
form.addEventListener('submit', handleSubmit);
function handleSubmit(event) {
event.preventDefault();
const pageName = inputField.value;
inputField.value = '';
const hostName = window.location.hostname;
const url = `${hostName}/${pageName}`;
console.log(url);
// window.location.href = url;
}
<form id="myForm">
<input type="text" id="name" placeholder="type name and hit enter">
</form>
Simply type and direct to that link
by .addEventListener event change as you wish,
var mySearchInput = document.getElementById('mySearchInput');
mySearchInput.addEventListener('blur', (event) => {
document.location.href = "https://mysitename.com/" + mySearchInput.value;
})
<label>Link</label>
<input type="text" id="mytext" placeholder="Type link here..." />

Detect duplication of values of input fields

I have a big html form with multiple email fields. What I want to do is make sure the user can't enter the same email in more than one field.
I have managed to detect duplication successfully by defining an array where each email value the user inputs is pushed to the array and that's where the comparison happens.
the problem happens when after detecting duplication I delete the value from the input field but the value still exists in the array so my function still returns that there is a duplicate value.
here is my function code:
var filledEmail = [];
var allEmailFields = $("form input[type='email']");
function checkIfArrayIsUnique(myArray) {
return myArray.length === new Set(myArray).size;
}
function addToEmails() {
allEmailFields = $("form input[type='email']");
filledEmail = [];
allEmailFields.each(function(){
var currentEmail = $(this);
currentEmail.bind('change',function() {
console.log("email value changed");
filledEmail.push(currentEmail.val());
console.log(filledEmail);
if (checkIfArrayIsUnique(filledEmail) == true) {
console.log("emails unique")
}
else {
console.log("emails not unique");
}
})
});
}
Any help would be so much appreciated.
This is how you could do it:
Attach change event listeners to each of your elements and check if the entered value exists. If it does not exist add it to your filledEmail array otherwise do nothing.
You will see that if you type the same name in different input element boxes it will not be added, hence will not appear as the output in the console
var filledEmail = [];
document.querySelectorAll("input[type='email']").forEach((mailField,i) => {
mailField.addEventListener("change", e => {
const email = e.target.value;
const hasMail = filledEmail.find(x => x === email);
if (!hasMail) {
filledEmail = filledEmail.filter((x, j)=> j!==i);
filledEmail.push(email);
}
console.log('filled mails without duplicates', filledEmail)
});
});
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />

Constructor function didn't save querySelector(x).value

I am working on a small APP for calculating Budgets and i am stuck on a problem i don't understand. I used a constructor for getting the user inputs in a few input fields.
I tried to setup this part in a constructor to learn more about prototyping and constructor functions and to challenge myself. I don't get why the constructor GetInput not holding my input.values
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
const addType = document.querySelector('.add__type').value;
const description = document.querySelector('.add__description').value
const addValue = document.querySelector('.add__value').value;
// EVENTLISTENER Constructor:
function EventListner(selector, listner, fnt) {
this.selector = selector;
this.listner = listner;
this.fnt = fnt;
document.querySelector(selector).addEventListener(listner, fnt);
};
function GetInput(operator, description, value) {
this.operator = operator;
this.description = description;
this.value = value;
}
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
const clickListener = new EventListner('.add__btn', 'click', () => {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
});
const enterKeyListener = new EventListner('.add__value', 'keypress', (e) => {
if (e.keyCode == 13) {
if (description.value == '' || addValue.value == '') {
// MAKE SURE DESCRIPTION AND VALUE IS NOT EMPTY
alert('description and value can\'t be empty');
return;
}
// ON ENTER SAVE VALUES IN AN ARRAY
// IF PLUS INTO incomeArr, ON MINUS INTO expenseArr
console.log('enter pressed');
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
}
});
Output is:
GetInput {operator: "inc", description: "", value: ""}
Only works when i:
document.querySelector('.add__value').value;
directly into the console.
Your initial values are empty for the input fields. And your code is executing right away. That's why you are getting empty value for those fields.You can try adding some predefined values for those input field.
Code with predefined value for the input fields :
const addType = document.querySelector('.add__type').value;
const description = document.querySelector('.add__description').value
const addValue = document.querySelector('.add__value').value;
function GetInput(operator, description, value) {
this.operator = operator;
this.description = description;
this.value = value;
}
const inputData = new GetInput(addType, description, addValue);
console.log(inputData);
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" value="mydesc" class="add__description" placeholder="Add description">
<input type="number" value="2" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
Note : You need to add event listener to listen to any change in your input field values. If user type anything then you can proceed to instantiate your constructor function
You are getting this issue because you need to trigger an event to for calculate, and one more thing you have to use something else other then const, because you cannot reinitialize value in constant variables, Current code is execute on loading page, So the values is initialized to that will not change
const addType = document.querySelector('.add__type').value;
const description = document.querySelector('.add__description').value
const addValue = document.querySelector('.add__value').value;
So please change const with var or let, Or you can set default value to description and value

Adding dynamic <option> to select doesn't show unless I switch the field

I want to be able to add Group Members dynamically and I simply used + button for that. The problem is - it adds the input value of the prompt, but I can't see it unless I switch fields and type something else.
Here is the YouTube link for better understanding:
https://youtu.be/sA0WB2Le3Fg
<button id="add" type="button" onClick={(e)=>this.addMember(e)}>+</button>
The state :
members: [
{member:"Berin"},
{member:"Cristian"},
{member:"Raddy"},
{member:"Ventsislav"},
]
The function :
addMember = (e) => {
let input = prompt("Enter the name");
this.state.members.push({member:input});
e.preventDefault();
}
The mapping function :
let members = this.state.members.map((member,index)=>{
return <option value={member.member} key={index}>{member.member}</option>
})
The select field :
<select id="groupMember" onChange={this.changeMember} name="member" required>
<option defaultValue="" selected disabled>Select group member</option>
{members}
</select>
Try this:
addMember = (e) => {
let input = prompt("Enter the name");
let newMemberList = this.state.members;
newMemberList.push(input);
this.setState({ members: newMemberList });
e.preventDefault();
}
Recommended approach in the later React versions looks like this:
addMember = (e) => {
let input = prompt("Enter the name");
this.setState(prevState => ({
members: [...prevState.members, input]
}))
e.preventDefault();
}
Thank you ! Already found the solution :
addMember = (e) => {
let input = prompt("Enter the name");
let members = this.state.members;
members.push({member:input})
e.preventDefault();
this.setState({
...this.state,
members
})

How to save data from a form with HTML5 Local Storage?

I have a form that makes logging into a website but not in mine and I want them to be saved form data in my web with HTML5 local storage. But not how. Any idea? My form is this:
<form action="http://issuefy.ca.vu/on/login.php" class="form-login" method="post" />
<input name="email" type="email" id="email" required="" placeholder="Email" />
<input name="password" type="password" required="" placeholder="ContraseƱa" />
</form>
LocalStorage has a setItem method. You can use it like this:
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
When you want to get the value, you can do the following:
var storedValue = localStorage.getItem("email");
It is also possible to store the values on button click, like so:
<button onclick="store()" type="button">StoreEmail</button>
<script type="text/javascript">
function store(){
var inputEmail= document.getElementById("email");
localStorage.setItem("email", inputEmail.value);
}
</script>
Here's a quick function that will store the value of an <input>, <textarea> etc in local storage, and restore it on page load.
function persistInput(input)
{
var key = "input-" + input.id;
var storedValue = localStorage.getItem(key);
if (storedValue)
input.value = storedValue;
input.addEventListener('input', function ()
{
localStorage.setItem(key, input.value);
});
}
Your input element must have an id specified that is unique amongst all usages of this function. It is this id that identifies the value in local storage.
var inputElement = document.getElementById("name");
persistInput(inputElement);
Note that this method adds an event handler that is never removed. In most cases that won't be a problem, but you should consider whether it would be in your scenario.
Here,Simple solution using JQUERY is like this..
var username = $('#username').val();
var password = $('#password').val();
localStorage.setItem("username", username);
localStorage.setItem("password", password);
To save the data you have to use
localStorage.setItem method and to get the data you have to use
localStorage.getItem method.
This is my function from my CMS, that save all TEXTAREA and INPUT values on "keyup"
and place it in the right element on reload.
After the form has been submitted, only the submitted form is deleted from the local storage.
Set it to buttom of your page, thats it.
(function (mz,cms,parentKey,subKey) {
setTimeout(function() {
const storeAll = "textarea,input";
const formArray = mz.querySelectorAll(storeAll);
parentKey = window.location.href+"-";
formArray.forEach((formItem) => {
if (formItem) {
subKey = formItem.getAttribute("name");
var key = parentKey+subKey;
if (localStorage[key]) {
var _localStorage = localStorage[key] ;
formItem.value = _localStorage;
}
formItem.addEventListener("keyup", function () {
var _localStorage = formItem.value;
var T = formItem.getAttribute("type");
if (T == "password" || T == "hidden" || T == "submit" || formItem.disabled) {
//console.log("Ignore: "+formItem.getAttribute("name"));
return;
}
localStorage.setItem(key, _localStorage);
} , false);
formItem;
}
});
const submitForm = mz.querySelectorAll("form");
submitForm.forEach((submitItem) => {
if (submitItem) {
submitItem.addEventListener("submit", function (e) {
// e.preventDefault();
const formArray = submitItem.querySelectorAll("textarea,input");
formArray.forEach((formItem) => {
subKey = formItem.getAttribute("name");
localStorage.removeItem(parentKey+subKey);
} , false);
} , false);
}
});
}, 1);
}(this.document,'','',''));

Categories

Resources