I wanted to display a different message in the same <div> when the user makes a selection from a radio button. It works, but it's not as clean as I'd like. Here's the code:
<script type="text/javascript">
function showhide(t) {
var target = document.getElementById('bankingdetails');
if (target.style.display == 'none') {
var text = 'Please effect payment to the following account:<br />';
var accountnum = 'Account Number: 39485620346<br />';
var branchcode = 'Branch Code: 34985<br />';
var branchname = 'Branch: F00 Bank Whoville';
if (t == 0) {
// User opted for Online Payment
target.style.display = 'block';
target.innerHTML = 'Please click here to go to PayPal:<br />Go to PayPal';
} else {
target.style.display = 'block';
target.innerHTML = text + accountnum + branchcode + branchname;
};
} else {
target.style.display = 'none';
};
};
</script>
<input type="radio" name="radPayment" onclick="showhide(0);" />Pay Online
<input type="radio" name="radPayment" onclick="showhide(1);" />EFT
Right now, I can click either radio button to display it's message, but... I have to click it again, or click on the other one to hide the visible message.
What I'd like is to change the text that displays on the page so that if the EFT text is visible, if I click on the Pay Online button, the text will change immediately.
Thanks in advance!
If I understand you correctly, clicking multiple times causes the div to hide/show. You can solve this by checking always the given parameter t:
<script type="text/javascript">
function showhide(t) {
var target = document.getElementById('bankingdetails');
var text = 'Please effect payment to the following account:<br />';
var accountnum = 'Account Number: 39485620346<br />';
var branchcode = 'Branch Code: 34985<br />';
var branchname = 'Branch: F00 Bank Whoville';
switch(t)
{
case 0:
// User opted for Online Payment
target.style.display = 'block';
target.innerHTML = 'Please click here to go to PayPal:<br />Go to PayPal';
break;
case 1:
target.style.display = 'block';
target.innerHTML = text + accountnum + branchcode + branchname;
break;
default:
target.style.display = 'none';
}
};
</script>
Related
In the script below, I try to record in the bowser the name of the users who connect to my application. If it is the first time that a user connects, when he presses the "submit" button to connect to the application I want a message "Welcome" + name + "!
If the user has already connected (his name is already registered in the localStorage), when he presses the submit button, I want a "Welcome back" + name + "!
Thank you for the comments below, I tried to take them into account. When I run the updated code below, only welcome appear on the message. The name of the user is not included on the message. How can I modify my code to correct this problem?
Thank you in advance for your advice.
JS script:
let myButton = document.getElementById ("myButton");
let myText = document.getElementById ("username");
function store() {
let n = 0;
while (localStorage.getItem("username" + n)) {
n++;
}
localStorage.setItem("username" + n, myText.value);
}
function welcomeUsername(){
let resultMessage = "Welcome "
let n = 0;
while (n) {
let user = localStorage.getItem("username" + n);
if(myText.value != user){
resultMessage += myText.value + "!";
break;
} else {
resultMessage += "back" + myText.value + "!";n++;
}
}
alert(resultMessage);
}
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<br />
<br />
<div class ="login_card"></div>
<div class = "log_head">
<h1>Login</h1>
</div>
<div class = "log_body">
<br />
<label for="uname"><b>Please enter your username below and click on submit:</b></label> <br>
<input type="text" value = "Enter username" onfocus = 'this.value =""' id = "username"> <br>
<br> <br>
<input type="button" onClick="welcomeUsername();location.href ='/index';" value = "Submit" id = "myButton">
</div>
</div>
this part of your code has problem let value = localStorage.getItem("username"). you cant get any value from your localstorage since you set them 'username'+n, that;s why your if statement always run.
can you try this: while (n) {let user = localStorage.getItem("username" + n); if (myText.value == user) {resultMessage += myText.value; break; } else {resultMessage += "back" + myText.value + "!"; n++; }}
Try this.
const btn = document.getElementById('myButton');
// get a welcome message
const welcomeText = (name) => {
// store the name as an array type, initialize if it does not exist
let names = localStorage.getItem('usernames');
names = names == null ? [] : names;
// check if the name exists and decide the welcome message according to the result
if (names.includes(name)) {
return `Welcome back ${name}`;
} else {
// update storage information
names.push(name);
localStorage.setItem('usernames', names);
return `Welcome ${name}`;
}
};
// send name and call method
const submit = () => {
const name = document.getElementById('username').value;
alert(welcomeText(name));
};
btn.addEventListener('click', submit);
<script>
var sum = 0;
var pressYet = false;
function changeIt() {
if(pressYet == false){
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
</script>
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id = "button" >Press If you are here</button>
SO I have this sweet epic button on my website, its very cool, but I want to make it better. I was wondering how to make the variable 'sum' not reset every time I refresh my website. I know there's a term for that but for the life of me I cannot figure it out. I want it so every time someone presses the button, 'sum' gets added one to it and that number would be permanent. So over time that number gets very large.
I am very new to HTML so please be kind to me.
You can save the value to localStorage and then retrieve it from localStorage after page load. Then on the basis of the data you can adjust the page. I have slightly modified your code here
var sum = 0;
var pressYet = localStorage.getItem('pressYet');
function changeIt() {
if (pressYet == null) {
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
localStorage.setItem('pressYet', pressYet);
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
(function init() {
if (localStorage.getItem('pressYet') != null || localStorage.getItem('pressYet') != "") {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
})();
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id="button">Press If you are here</button>
You can check out the demo https://jsfiddle.net/5jyrk6s8/
I want to write a basic story where you just click next and the text changes.
I can change the text, but I don't know how to hide the button. Basically I want the onclick method to execute multiple functions, but not all at the same time, rather in a sequence
Code as below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="div1">
<p id="txt" class="txt1">OK, here wo go.</p>
</div>
<button id="btn_next" type="button">Next</button>
<script>
document.getElementById("btn_next").addEventListener("click", toggleText);
function toggleText() {
var textBox = document.getElementById("txt");
switch (textBox.className) {
case "txt1": {
textBox.innerHTML = "This is text 1";
swapClasses(textBox, "txt2");
break;
}
case "txt2": {
textBox.innerHTML = "This is text 2";
break;
}
}
}
function swapClasses(elem, targetClass) {
elem.className = targetClass;
}
</script>
</body>
</html>
If you want to hide the button when the <p> class is txt2, which means the last text is shown, a simple way to do it would be this:
case "txt2": {
textBox.innerHTML = "This is text 2"
document.getElementById("btn_next").style.display = "none";
break;
}
You could also store the button element to a variable const btnEl = document.getElementById("btn_next") so you don't get it twice.
You can hide an element by setting its display to none like:
`nextBtn.style.display = 'none';
However, instead of using a switch statement, you can use an array of text values to drive your story as in the next answer
Another approach to this is shown below.
let counter = 0;
const displayed_text = [
'Input text 1',
'Input text 2',
'Input text 3',
'Input text 4',
];
// Assign DOM elements to variables
const btn_next = document.getElementById("btn_next");
const text_display = document.getElementById("txt");
// Attach listener to button
btn_next.addEventListener("click", toggleText);
function toggleText() {
counter += 1;
if (counter <= displayed_text.length) {
// Update displayed text
text_display.innerHTML = displayed_text[counter -1];
}
if (counter === displayed_text.length) {
// Hide button
btn_next.style.display = 'none';
}
}
The main advantage of this approach is that it makes it easier to go back multiple steps if you want.
var story = [
'OK, here wo go.',
'This is text 1',
'This is text 2',
'This is text 3',
'This is text 4'
];
var nextBtn = document.getElementById("btn_next");
function changeText() {
var textBox = document.getElementById("txt");
var chapter = Number(textBox.dataset.chapter);
if (chapter < story.length - 1) {
textBox.dataset.chapter = chapter + 1;
textBox.innerHTML = story[chapter + 1];
if ((story.length - chapter) <= 2 ) {
nextBtn.style.display = 'none';
}
}
}
nextBtn.addEventListener("click", changeText);
<div id="div1">
<p id="txt" class="txt1" data-chapter="0">OK, here wo go.</p>
</div>
<button id="btn_next" type="button">Next</button>
For cases like this, it can be beneficial to store the content in an array of objects (or fetch the content as JSON etc). Then, when the event handler is fired, it can simply increment (or decrement if you wish to have forward/backward) and determine whether the button should be visible or hidden. That appears to be the direction you're heading with the above code.
Example function:
function navigatePage(el){
// Control the navigation by only allowing increment within range
if (el != null){
switch (el.target.getAttribute("id")){
case "btn_next":
if (curr_page < story.length){
curr_page++;
}
break;
case "btn_prev":
if (curr_page > 1){
curr_page--;
}
break;
default: break;
}
}
// Set the title and text to the current page contents
// Arrays are zero-indexed, so "1" is actually "0", and so on
story_title.innerHTML = story[curr_page - 1].title;
story_content.innerHTML = story[curr_page - 1].text;
// Show or hide nav buttons based on the current page
// The following syntax is basically just a fancy "if-then" done in one line
btn_prev.style.display = (curr_page > 1 ? "inline-block" : "none");
btn_next.style.display = (curr_page < story.length ? "inline-block" : "none");
// Update the page count element
page_count.innerHTML = "Page " + curr_page + " of " + story.length;
// document.getElementById("storycontent").innerHTML = curr_page + " - " + story.length;
}
Here is a working fiddle to demonstrate how it all works together:
https://jsfiddle.net/s0toz3L8/1/
I have a form, and I would like to clear the input field every time I enter the submit (plus) button.
I have tried using this, it does not work. I may be implementing it in the wrong spot.
document.getElementById('add-item').value='';
My Javascript code is below.
window.addEventListener('load', function(){
// Add event listeners
document.getElementById('add-item').addEventListener('click', addItem, false);
document.querySelector('.todo-list').addEventListener('click', toggleCompleted, false);
document.querySelector('.todo-list').addEventListener('click', removeItem, false);
function toggleCompleted(event) {
console.log('=' + event.target.className);
if(event.target.className.indexOf('todo-item') < 0) {
return;
}
console.log(event.target.className.indexOf('completed'));
if(event.target.className.indexOf('completed') > -1) {
console.log(' ' + event.target.className);
event.target.className = event.target.className.replace(' completed', '');
document.getElementById('add-item').value='';
} else {
console.log('-' + event.target.className);
event.target.className += ' completed';
}
}
function addItem() {
var list = document.querySelector('ul.todo-list');
var newItem = document.getElementById('new-item-text').value;
var newListItem = document.createElement('li');
newListItem.className = 'todo-item';
newListItem.innerHTML = newItem + '<span class="remove"></span>';
list.insertBefore(newListItem, document.querySelector('.todo-new'));
}
function removeItem(event) {
if(event.target.className.indexOf('remove') < 0) {
return;
}
var el = event.target.parentNode;
el.parentNode.removeChild(el);
}
});
This is what you need:
document.getElementById('new-item-text').value = "";
regarding your need, you will need to put it at the end of your addItem()
you can refer this simple code:
<html>
<body>
<input type="text" id="test">
<button onclick="func()">remove</button>
<br/>
Value = <span id="val"></span>
<script>
function func(){
alert("clicked");
document.getElementById('val').innerHTML = document.getElementById('test').value;
document.getElementById('test').value = '';
}
</script>
</body>
</html>
Use form reset method to clear inputs in one go.
document.getElementById("myForm").reset();
You can set your textbox value = '' in submit button.
and you can create a ClearFunction and then you can call it everytime you need it.
function cleartextbox() {
$('#name').val("").focus();
$('#selectgender').val("");
$('#telephone').val("");
}
I am having a problem setting/getting a hidden input's value with JavaScript, and can't see what I'm doing wrong.
What I am basically trying to do is maintain the state of expandable/collapsable divs on my page across form submissions. So I put a hidden input on the page to hold the state of the divs. When a div is expanded/collapsed, I change the value of the input. When the page loads, I read the value of the input and set the state of the divs.
But the value of the input is getting lost. I verify through alerts that it is being set correctly, and then when I read it on load, I verify with an alert that it is empty. Here is the pertinent code:
<input type="hidden" name="ECState" id="hdnECState" />
<script language="javascript" type="text/javascript">
<!--
var ecValue;
function ec(div, btn) {
//expands or collapses an error detail div
var e = document.getElementById(div);
var b = document.getElementById(btn);
var ecStr = div.toString() + ',' + btn.toString() + '|'
if (e.style.display == 'block') {
e.style.display = 'none';
b.src = '../../Images/plus.gif';
ecValue = ecValue.replace(ecStr, '');
}
else {
e.style.display = 'block';
b.src = '../../Images/minus.gif';
ecValue = ecValue + ecStr;
}
alert(ecValue);
document.getElementById('hdnECState').value = ecValue;
}
function reexpand() {
//restores the expanded state of the error detail divs
var pipe, comma, db, div, btn, e, b;
var n = document.getElementById('hdnECState').value;
alert('n=' + n);
if (n != '') {
pipe = n.indexOf('|');
while (pipe > 0) {
db = n.substring(0, pipe);
comma = db.indexOf(',');
if (comma > 0) {
div = db.substring(0, comma);
btn = db.substring(comma + 1);
e = document.getElementById(div);
b = document.getElementById(btn);
e.style.display = 'block';
b.src = '../../Images/minus.gif';
}
n = n.substring(pipe+1);
pipe = n.indexOf('|');
}
}
}
reexpand();
//-->
</script>
When I expand a div, I see the alert from ec() showing that ecValue is 'foo,bar|'.
But after submitting the form, I see the alert from reexpand() saying 'n='.
Anybody see what I'm missing?
You haven't posted Html part of your code. So I am a bit confused, But I think you should put some value first.
<input type="hidden" name="ECState" id="hdnECState" value="1" />
Rudu supplied the answer in a comment, but since I can't mark a comment as the answer, here it is:
I was forgetting that hidden inputs don't automatically keep their value in ViewState across form submissions. I needed to re-value the hidden input on the back end in page load and then everything worked fine.