Get Value of Week Input - javascript

I want to save the value of a week Input in a Variable.
Additionally, I want to output it in a span.
I tried this:
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
var kw = document.getElementById("week-selector").value;
document.getElementById("kalenderwoche").innerHTML = kw;

Your code works. You just need an event handler
Here I made one that can be reused on load in case the selector has a value already
window.addEventListener("DOMContentLoaded", () => { // when page has loaded
const kw = document.getElementById("kalenderwoche");
const ws = document.getElementById("week-selector");
let kwValue; // you wanted to save it for later?
const setValue = () => kwValue = kw.textContent = ws.value || "";
ws.addEventListener("input", setValue)
setValue(); // initialise
console.log(kwValue); // saved value
});
<input type="week" name="week" id="week-selector" value="2022-W50" />
<span id="kalenderwoche"></span>

you have to add eventListener to week input
var kw = document.getElementById("week-selector")
kw.addEventListener('change', (e) => {
console.log("e=>>>>", e.target)
document.getElementById("kalenderwoche").innerHTML = e.target.value;
})
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>

<!DOCTYPE html>
<html>
<body>
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
<script>
document.getElementById("week-selector").addEventListener('change', function() {
document.getElementById("kalenderwoche").innerHTML = this.value
})
</script>
</body>
</html>

Related

From element to element script

how to pass from a function to another function? (script>script) <= element
how do I pass the value of the field validator into the second function?
<script>
$('#card_number').validateCreditCard(function(result) {
if (result.valid) {
const infosuccess = result.card_type == null ? '-' : result.card_type.name
const valid = result.valid
const validlunn = result.luhn_valid
const validlenght = result.length_valid
console.log(infosuccess);
} else {
// $(this)
// const inforeject = result.valid
// console.log(result);
}
});
</script>
<script>
$('#nextaction').click(function(e) {
e.preventDefault();
// my code...
})
</script>
You cannot pass arguments directly in to event handlers. However, there are other approaches you can use.
In this case you can set the 'Next' button to be disabled when the page loads. You can then enable/disable it depending on the result of the credit card validation.
To retrieve the entered card number you can simply read the value from the input when the button is clicked, like this:
const $cardInput = $('#card_number');
const $validateBtn = $('#validate_card');
const $nextBtn = $('#next-action');
$cardInput.validateCreditCard(function(result) {
$nextBtn.prop('disabled', !result.valid); // enable/disable 'next' button
if (result.valid) {
// update the UI to show card details if necessary here...
} else {
console.log('enter a valid credit card number...');
}
});
$nextBtn.on('click', function(e) {
e.preventDefault();
const cardNumber = $cardInput.val();
console.log(cardNumber);
console.log('move to next action here...');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-creditcardvalidator/1.0.0/jquery.creditCardValidator.min.js" integrity="sha512-7omJBgl5QF4QuC3Ge745IO3rDZVMrZWIGK8lSs5lQIFxbWt4d2c7YQg3ZcnonFyRuQslrJ1Ai33Zj/rnXC15+Q==" crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
<p>
Test Card number: 5404000000000084
</p>
<label>
Credit card number:
<input type="text" id="card_number" />
<button type="button" id="validate_card">Validate</button>
</label>
<button type="button" id="next-action" disabled>Next...</button>

calculating from an input

I'm starting studying the DOM in javascript and I'd like to create a program which makes the sum of two numbers given on input and show it.
I'd like to know what functions should I use, and what functions it is better I didn't.
This is my (very simple) html code:
let warp = document.getElementById('warp');
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
let res = document.getElementById('res');
//res.addEventListener('click', calcul);
//res.onclick(calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul(first, second) {
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>
let answerElemenet = document.createElement("h1");
// You can create a h1 element to display your answer after calculating it
document.body.appendChild(answerElemenet);
// Inside the calculate Function you get the values of input one and two
// and then you store the sum value in a variable and just change your
// answerElement to have the innerHTML value of the finalSum Variable
function calculate(){
let valueOne = parseFloat(document.getElementById('first').value);
let valueTwo = parseFloat(document.getElementById('second').value);
let finalSum = valueOne + valueTwo;
answerElemenet.innerHTML = finalSum;
}
Welcome to Stackoverflow!
I copied your answer and made some small changes. Here comes a brief description and explanation of what you could do better:
If you don't plan to change these references use const instead of let. Also try to keep input elements separated from their values. The reference to the input probably won't change but their value most certainly will.
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
When calculating input values, you usually want them as fresh as possible so instead of saving input values right at the beginning of the script, you get them when you need them, in the calcul() function.
You will also need some kind of validation. Here we try to convert the input to a number and set to zero if not possible:
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
The preferred way of adding event handlers to DOM elements is using the event API. So to call the calcul()function you use the line you had commented:
res.addEventListener('click', calcul);
This also means you should remove the onClick attribute from the DOM. Also, input cannot have children:
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
All together looks like this:
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
res.addEventListener('click', calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
</form>
<div>
</body>
Keep up the good job and never stop asking questions!
This will work. You just need to call the values based on their id in the calcul() function itself.
let warp = document.getElementById('warp');
let res = document.getElementById('res');
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul() {
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
if(isNaN(one) || isNaN(two)){
event.preventDefault();
return
}
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>

How to clear localStorage on button click

I followed a tutorial on Youtube about localStorage and everything went fine. After that I tried to mess around with the concepts and wanted to add a button to remove the localStorage (id ="btnClear").
Now I've tried everything but it doesnt let me remove the storage. I think its because I declared the constants inside the function and I might have to store them somewhere outside and stringify the input. But can I clear the localStorage somehow even in this scenario?
<body>
<content>
<fieldset>
<legend>Insert Data</legend>
<input type="text" id="inpKey" placeholder="Insert Key.." />
<input type="text" id="inpValue" placeholder="Insert Value.." />
<button type="button" id="btnInsert">Insert</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<div id="lsOutput"></div>
<br />
<button type="button" id="btnClear">Clear</button>
</fieldset>
</content>
</body>
<script type="text/javascript">
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const lsOutput = document.getElementById("lsOutput");
const btnClear = document.getElementById("btnClear");
btnInsert.onclick = function () {
const key = inpKey.value;
const value = inpValue.value;
if (key && value) {
localStorage.setItem(key, value);
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
lsOutput.innerHTML += `${key}: ${value}`;
}
//BUTTON CLEAR
btnClear.onclick = function () {
localStorage.clear();
};
</script>
Check your local storage in the browser. Your code actually does clear the localStorage. What you are missing is to update your UI. Replace your Button clear code with that:
btnClear.onclick = function () {
localStorage.clear();
if(localStorage.length === 0)
lsOutput.innerHTML = "";
};
Here is a tutorial how you check your local storage in chrome for example: How to view or edit localStorage
Have a look here, I have update all you code from HTML to JS.
You can test it on jsfiddle as stackoverflow will throw this error:
{
"message": "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.",
"filename": "https://stacksnippets.net/js",
"lineno": 37,
"colno": 33
}
Also, It is better to use document.addEventListener with most of your events (as they provide you with reacher experience)
See more on events here
A quote from this URL:
The significant drawback with inline events is that unlike event
listeners described above, you may only have one inline event
assigned. Inline events are stored as an attribute/property of the
element[doc],
meaning that it can be overwritten.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to clear localStorage on button click</title>
</head>
<body>
<content>
<fieldset>
<legend>Insert Data</legend>
<input type="text" id="inpKey" placeholder="Insert Key.." />
<input type="text" id="inpValue" placeholder="Insert Value.." />
<button type="button" id="btnInsert">Insert</button>
</fieldset>
<fieldset>
<legend>Local Storage</legend>
<ul id="outputList"></ul>
<br />
<button type="button" id="btnClear">Clear</button>
</fieldset>
</content>
<script type="text/javascript">
const printLSContent = function (el) {
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key);
let li = document.createElement('li');
li.innerHTML = `K: ${key}; V: ${value}`;
el.appendChild(li);
}
}
document.addEventListener("DOMContentLoaded", function (event) {
const inpKey = document.getElementById("inpKey");
const inpValue = document.getElementById("inpValue");
const btnInsert = document.getElementById("btnInsert");
const outputList = document.getElementById("outputList");
const btnClear = document.getElementById("btnClear");
// element.addEventListener(event, handler[, options]); // type - event type; listener - event handler; options -
btnInsert.addEventListener('click', function () {
const key = inpKey.value;
const value = inpValue.value;
localStorage.setItem(key, value);
location.reload();
}, false);
printLSContent(outputList);
// //BUTTON CLEAR
btnClear.addEventListener('click', function () {
localStorage.clear();
location.reload();
}, false);
});
</script>
</body>
</html>

Not able to get the value from script in paragraph(<p></p>)

<p><input type="text" name="adcode" id="cityName"
style="border:none;color:green;"/></p>
<script>
window.onload = function() {
document.getElementById('cityName').value = GetDivElement();
}
</script>
The above code, I am not able to call the "GetDivElement" in paragraph
<p id="cityName"></p>
How to pass the GetElementId in p id??
If you want to get the GetDivElement() method's return value to the paragraph, you can do it like below:
window.onload = function() {
let getDivElement = () => {
return 'Div element data';
};
let inputbox = document.getElementById('cityInput');
let cityParagraph = document.getElementById('cityValue');
inputbox.value = cityParagraph.innerHTML = getDivElement();
}
<div>
<input id="cityInput" />
<p id="cityValue"></p>
</div>
As I understood from your later comment, if you want to get the paragraph value if the id='coimbatore' which you get from the GetDivElement() method you can do the following:
window.onload = function() {
let getDivElement = () => {
return 'coimbatore';
};
let paraId = getDivElement();
let textboxId = `${paraId}CityInput`;
let inputbox = document.getElementById(textboxId);
let cityParagraph = document.getElementById(paraId);
console.log(`Text field value is : ${inputbox.value}`);
console.log(`Paragraph value is : ${cityParagraph.innerHTML}`);
}
<div>
<input id="delhiCityInput" value="delhi input"/>
<p id="delhi">
Delhi city data
</p>
</div>
<div>
<input id="mumbaiCityInput" value="mumbai input"/>
<p id="mumbai">
Mumbai city data
</p>
</div>
<div>
<input id="coimbatoreCityInput" value="coimbatore input"/>
<p id="coimbatore">
Coimbatore city data
</p>
</div>
Couple of things you need to understand here is,
You can't set the same id for multiple html elements
If you want to get the value from a paragraph you should use innerHTML
Hope this helps.

whatever the number , i enter in form field, i want that to be stored in a variable.

(web designing) whatever the number , i enter in form field, i want that to be stored in a variable. When the user changes the value in the form field , value stored in the variable needs to be updated. How to do that ?
Try this:
<input type = "text" id = "id1">
<script>
$("#id1").change(function(){
var a = $("#id1").val();
alert(a);
});
</script>
there is a jsbin that demonstrates required functionality
jsbin
or
<form>
<input id="input" type="number">
</form>
<button id="button">Log Value</button>
<script>
var input = document.getElementById('input');
var button = document.getElementById('button');
var val;
input.addEventListener('change', function (event) {
val = +event.target.value;
});
button.addEventListener('click', function () {
console.log('Value:', val);
});
</script>
<form>
<input type="text" id="inputid" value="test"/>
<button type="submit">submit</button>
</form>
<script>
$( document ).ready(function() {
var input =$('#inputid');
var saveVar;
// input.change(function(){
// console.log(input.val());
// });
input.on('keyup', function(ev){
saveVar=input.val();
console.log(saveVar);
});
});
</script>

Categories