color changing button onclick - javascript

Okay so so far I have this page with a few buttons in it, whenever you click the button it turns red now i want to add that whenever you click it more times the color changes.
so for example: first the button is green, on the first click it turns red, on the third click it turns pink and so on.
I tried to do this with the set_onclick function I made and then multiple this code:
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
but i dont get it to work
page();
function onbuttonclicked(a) {
document.getElementById("button" + a).classList.remove("button")
document.getElementById("button" + a).classList.add("clickedbutton")
}
function set_onclick(amount) {
for (var a = 1; a < (amount + 1); a++) {
document.getElementById("button" + a).setAttribute("onclick", "onbuttonclicked(" + a + ")");
}
}
function page() {
document.body.style.backgroundColor = "grey";
//style page
createButtons(30);
}
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
set_onclick(amount);
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>buttons</title>
<link rel="stylesheet" type="text/css" href="buttons.css">
</head>
<body>
<div id="container"></div>
<script src="buttons.js"></script>
</body>
</html>

As you said the color of the button is dependent on how many times you clicked the button, and you will have to manage a local state for each button since there are many buttons
I think the the first thing you need is an object that will change the color like this, where the key is count and value is color
const obj = {
1 : "red",
2 : "blue"
3 : "pink"
4 : "skyblue"
...
...
...
}
and then change the color according to it
var colorMap = {
1 : "red",
2 : "blue",
3 : "pink",
4 : "hotpink",
5 : "brown",
6 : "yellow",
7 : "black"
}
page();
function page() {
document.body.style.backgroundColor = "grey";
createButtons(30);
}
document.body.addEventListener("click", (e)=>{
if(e.target.classList.contains("button")){
let currentbtnCount = parseInt(e.target.getAttribute("data-current-count")) + 1;
e.target.style.backgroundColor = colorMap[currentbtnCount] ? colorMap[currentbtnCount] : "black";
e.target.setAttribute("data-current-count", currentbtnCount);
}
})
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.setAttribute("data-current-count", "0")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>buttons</title>
<link rel="stylesheet" type="text/css" href="buttons.css">
</head>
<body>
<div id="container"></div>
<script src="buttons.js"></script>
</body>
</html>
And if you want complete random colors then here is another one
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
page();
function page() {
document.body.style.backgroundColor = "grey";
createButtons(30);
}
document.body.addEventListener("click", (e)=>{
if(e.target.classList.contains("button")){
e.target.style.backgroundColor = random_rgba();
}
})
function createButtons(amount){
for (var a = 1;a <(amount + 1); a++) {
var button = document.createElement("button");
button.classList.add("button")
button.setAttribute("data-current-count", "0")
button.id = "button" + a;
button.innerHTML = "button " + a;
container.appendChild(button);
}
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
body{
background-color: white;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 800px;
height: 350px;
background-color: grey;
position: relative;
}
#buttons{
margin-bottom: 30px;
}
button{
background-color: #4CAF50;
border: 1px solid black;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
width: 140px;
height: 50px;
}
.clickedbutton {
background-color: red;
}
.button {
background-color: green;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>buttons</title>
<link rel="stylesheet" type="text/css" href="buttons.css">
</head>
<body>
<div id="container"></div>
<script src="buttons.js"></script>
</body>
</html>

Make a function that will count clicks and change the color of the button depending on the amount of the clicks.
You can just change a class like this:
document.querySelector(".MyElement").className = "MyClass";
hope You know that when searching for a class with querySelector You need to use '.' in front of the name of the class. If You try to find by ID either use querySelector with '#' in front of an ID or use getElementById:
document.getElementById("MyElement").className = "MyClass";
Example:
let counter = 0
document.getElemenetById('button').onclick = function(){
counter += 1
}
if (counter = 0) {
document.getElementById('button').className = 'red'
} else if (counter = 1) {
document.getElementById('button').className = 'blue'
}
or
let counter = 0
document.getElementById("button").addEventListener("click", counter += 1);
if (counter = 0) {
document.getElementById('button').className = 'red'
} else if (counter = 1) {
document.getElementById('button').className = 'blue'
}
or
let counter = 0
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
counter += 1
}
if (counter = 0) {
document.getElementById('button').className = 'red'
} else if (counter = 1) {
document.getElementById('button').className = 'blue'
}
</script>

Related

Javascript - How do I change attribute of each generated textbox?

I Am currently working on a small project but tried everything and can't come up with a solution to my problem. I'm working on a to do list and using javascript to generate textboxes with a button that stores its value. The Button generates a textbox and 3 additional buttons (1 delete task button (red), 1 change its value button (yellow) and 1 completed button (green) which moves the task to a new list and generates 2 additional buttons delete task and the yellow button which does the same as preview). The problem is that when generating x amount of textboxes only the first textbox will work when changing its value (clicking on yellow button), how can I make it so each button works individually for respective textbox.
The same problem remains when clicking on the green button (completed button) in which only the first textbox in the list will display its value.
const syssla = document.querySelector("#min-syssla");
let firstbutton = document.querySelector(".firstbutton");
const ullist = document.querySelector(".unorderedlist");
const listdone = document.querySelector(".list-done");
firstbutton.addEventListener("click", task);
function task(event) {
const tododiv = document.createElement("div");
tododiv.classList.add("todo");
const list = document.createElement('li');
list.classList.add('todo-item');
tododiv.appendChild(list);
const completedButton = document.createElement('button');
completedButton.innerText = "Färdig";
completedButton.classList.add("complete_btn");
list.appendChild(completedButton);
const editButton = document.createElement('button');
editButton.innerText = "Ändra";
editButton.classList.add("edit_btn");
list.appendChild(editButton);
const eraseButton = document.createElement('button');
eraseButton.innerText = "Radera";
eraseButton.classList.add("erase_btn");
list.appendChild(eraseButton);
var textinput = document.createElement("input");
textinput.type = "text";
textinput.setAttribute('disabled', 'disabled');
textinput.classList.add("newbox");
list.appendChild(textinput);
textinput.value = syssla.value;
ullist.appendChild(tododiv);
firstbutton.value = "";
event.preventDefault();
}
ullist.addEventListener('click', deletecheckbox);
function deletecheckbox(e) {
let item = e.target;
if (item.classList[0] === 'erase_btn') {
const make = item.parentElement;
make.remove();
}
if (item.classList[0] === 'complete_btn') {
const radera1 = item.parentElement;
let completedButton = document.querySelector(".complete_btn");
const tododiv2 = document.createElement("div");
tododiv2.classList.add("todo2");
const list2 = document.createElement('li');
list2.classList.add('todo-item2');
tododiv2.appendChild(list2);
const editButton1 = document.createElement('button');
editButton1.innerText = "Ändra";
editButton1.classList.add("edit_btn1");
list2.appendChild(editButton1);
const eraseButton1 = document.createElement('button');
eraseButton1.innerText = "Radera";
eraseButton1.classList.add("erase_btn1");
list2.appendChild(eraseButton1);
let textinput2 = document.createElement("input");
textinput2.type = "text";
textinput2.setAttribute('disabled', 'disabled');
textinput2.classList.add("newbox2");
list2.appendChild(textinput2);
listdone.appendChild(tododiv2);
textinput = document.querySelector(".newbox");
textinput2.value = textinput.value;
radera1.remove();
}
editButton = document.querySelector(".edit_btn");
editButton.addEventListener('click', change());
function change() {
textinput = document.querySelector(".newbox");
if (item.classList[0] === "edit_btn") {
if (textinput.disabled === true) {
textinput.removeAttribute('disabled', 'disabled');
} else if (textinput.disabled === false) {
textinput.setAttribute('disabled', 'disabled');
}
}
}
}
listdone.addEventListener('click', donebox);
function donebox(ev) {
let item1 = ev.target;
if (item1.classList[0] === 'erase_btn1') {
const eraser = item1.parentElement;
eraser.remove();
}
if (item1.classList[0] === 'edit_btn1') {
textinput2 = document.querySelector(".newbox2");
if (textinput2.disabled === true) {
textinput2.removeAttribute('disabled', 'disabled');
} else if (textinput2.disabled === false) {
textinput2.setAttribute('disabled', 'disabled');
}
}
}
body {
margin: 0;
padding: 0;
background-size: cover;
}
h1 {
text-align: center;
font-size: 60px;
margin: 0 auto;
padding: 25px;
-webkit-text-stroke: 1.5px white;
background-color: rgb(48, 49, 51, 0.7);
opacity: 1;
}
#min-syssla {
position: relative;
left: 70px;
top: 50px;
border: 2px solid blue;
height: 25px;
width: 170px;
}
#wrapper-box {
border: 1px black;
position: relative;
top: 35px;
display: block;
width: 450px;
height: 700px;
background-image: linear-gradient(180deg, lightblue, blue 90%);
border: 3px outset blue;
border-top-left-radius: 5%;
border-top-right-radius: 5%;
z-index: 1;
padding: 10px;
margin-left: 37.5%;
margin-right: 40%;
}
.firstbutton {
position: relative;
left: 270px;
bottom: 18px;
border: 1px ridge blue;
border-radius: 5px;
padding: 3px;
width: 80px;
height: 30px;
}
h2 {
margin: 30px;
}
.todo-item {
margin-top: 20px;
}
.complete_btn {
margin-left: 20px;
float: right;
padding: 6px;
color: white;
border: 1.5px solid black;
background-color: green;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.complete_btn:hover {
background-color: rgb(86, 234, 7, 0.9);
}
.erase_btn {
float: right;
margin-left: 22px;
padding: 6px;
color: white;
border: 1.5px solid black;
background-color: red;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.erase_btn:hover {
background-color: rgb(255, 84, 84, 0.9);
}
.edit_btn {
float: right;
margin-left: 20px;
padding: 6px;
color: black;
border: 1.5px solid black;
background-color: yellow;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.edit_btn:hover {
background-color: rgb(213, 219, 46, 0.9);
}
.newbox {
border-radius: 5px;
border: 2px ridge darkorange;
padding: 5px;
}
.erase_btn1 {
float: right;
margin-right: 25px;
padding: 6px;
color: white;
border: 1.5px solid black;
background-color: red;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.erase_btn1:hover {
background-color: rgb(255, 84, 84, 0.9);
}
.edit_btn1 {
margin-right: 75px;
float: right;
padding: 6px;
color: black;
border: 1.5px solid black;
background-color: yellow;
border-radius: 5px;
font-family: arial;
font-weight: bold;
}
.edit_btn1:hover {
background-color: rgb(213, 219, 46, 0.9);
}
.newbox2 {
border-radius: 5px;
padding: 5px;
border: 2px ridge greenyellow;
}
.todo-item2 {
margin-top: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Kunskapskontroll</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<link rel=stylesheet href="css/style.css">
</head>
<body>
<h1>Mina Sysslor</h1>
<div id="wrapper-box">
<input type="text" id="min-syssla" placeholder="Min syssla" name="min-syssla"><br><br><br>
<button class="firstbutton" type="submit">Lägg till</button>
<div class="syssla-container">
<h2>Att göra</h2>
<ul class="unorderedlist"></ul>
<h2>Färdiga</h2>
<ul class="list-done"></ul>
</div>
I haven't tried much because I have no clue of how to manage to change the attribute for every new textbox.

Why won't these for loops work? To-Do list app [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Event binding on dynamically created elements?
(23 answers)
Closed last year.
I can't figure out why the for loops won't iterate. I had them working at one point inside of the printInput function, but not outside. BTW, I'm still working on the code portion of the for both loops. One is supposed to close the object by removing it. The other is supposed to make the html element editable.
// close button
var closes = document.getElementsByClassName("closes");
for (var i = 0; i < closes.length; i++){
closes[i].onclick = function (){
var l = closes[i];
l.remove();
}
}
// edit button
var edit = document.getElementsByClassName("edit");
for(var i = 0; i < edit.length; i++){
edit[i].onclick = function (){
var x = this.parentElement;
x.contentEditable = true;
}
}
// Submits input by hitting enter
document.addEventListener("keyup", function(e) {
if (e.keyCode === 13) {
printInput();
}
});
// Toggles checked class for finished chores
let selection = document.querySelector('ul');
selection.addEventListener("click", function(event) {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('checked');
}
}, false);
// This creates a new list object.
function printInput() {
let input = document.getElementById('todotext').value;
if (input === "" || null){
alert("You haven't written anything!");
} else {
const newItem = document.createElement('li');
const newNode = document.createTextNode(input);
newItem.className = "closes";
newItem.appendChild(newNode);
document.getElementById("list").appendChild(newItem);
const img = document.createElement("img");
img.src = 'edit.png';
img.className = "edit";
const newSpan = document.createElement("span");
const xBtn = document.createTextNode("x");
newSpan.className = "close";
newSpan.appendChild(xBtn);
newItem.appendChild(img);
newItem.appendChild(newSpan);
document.getElementById("todotext").value = "";
}
}
body {
min-width: 850px;
font-family: sans-serif;
background-color: #ece0d9;
}
h1.title {
width: auto;
margin: auto;
padding: 25px;
text-align: center;
-webkit-text-stroke: 1px #460a1e; /* width and color */
font-family: sans-serif; color: white;
}
div.form {
display: flex;
padding: 10px;
width: 50%;
margin: auto;
}
input {
width: 75%;
padding: 10px 14px 11px 14px;
margin: 0;
border-radius: 0;
border-width: thin;
font-size: inherit;
}
input:focus {
border-radius: 0;
outline: none;
}
span.addTo {
width: 25%;
padding: 8px 14px 10px 14px;
margin: 0;
border-style: solid;
border-width: thin;
border-color: black;
border-left: none;
text-align: center;
background-color: rgb(236, 235, 235);
}
span.addTo:hover {
background-color: #e0e0e0;
cursor: pointer;
}
ul.list{
width: 50%;
display: table;
text-align: left;
padding: 0;
margin: auto;
}
ul.list li{
padding: 10px 10px;
background-color: snow;
clear: right;
margin: 0;
position: relative;
cursor: pointer;
}
ul.list li:nth-child(2n){
background-color: rgb(240, 239, 239);
}
ul.list li.checked:nth-child(2n){
text-decoration: line-through;
background-color: rgb(170, 168, 168);
}
ul li.checked {
text-decoration: line-through;
background-color: rgb(170, 168, 168);
}
img.edit {
position: absolute;
right: 40px;
top: 0;
padding: 1px;
width: 34px;
height: 36.4px;
cursor: pointer;
background-color: transparent;
color: rgb(75, 71, 71);
}
img.edit:hover {
padding: 0;
width: 34px;
height: 36.4px;
transition-property: background-color;
transition-duration: .3s;
border-style: ridge;
border-color: black;
border-width: 1px;
}
span.close {
position: absolute;
right: 0;
top: 0;
padding: 10px 14px 10px 14px;
cursor: pointer;
background-color: transparent;
color: rgb(75, 71, 71);
}
span.close:hover {
color: black;
padding: 9px 13px 9px 13px;
transition-property: background-color;
transition-duration: .3s;
border-style: ridge;
border-color: black;
border-width: 1px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<meta charset="en">
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1 class="title">To-Do List</h1>
<div class="form">
<input type="text" id="todotext">
<span onclick="printInput()" id="addTo" class="addTo">Add</span>
</div>
<ul style="list-style-type:none;" class="list" id="list">
<li hidden id="close">Clean room<img src="edit.png" class="edit"><span class="close">x</span></li>
</ul>
<script src="main.js">
</script>
</body>
</html>

Allow div to be clicked with 'onblur' event on input text

After 500 milliseconds from the text inserted into the input text, I'm opening a div under the input text which contains a div with the inserted text on it. When inserted text is clicked it should console.log the text, but it is not able to do so because the onblur event occurs before the click. I want to keep my onblur event. But with the onblur event I can't make the div clickable. Please help
index.html:
var input_timeout = undefined;
document.getElementById("navigation").querySelector("INPUT").onkeyup = function () {
clearTimeout(input_timeout);
var val = this.value;
input_timeout = setTimeout(function () {
var to_add_to = document.querySelector("#navigation div");
to_add_to.innerHTML = "";
to_add_to.style.visibility = "visible";
var div_to_put = document.createElement("div");
div_to_put.style.visibility = "visible";
div_to_put.id = val;
div_to_put.innerHTML += "<font>" + val + "</font";
div_to_put.onclick = function () {
console.log(this.id);
}
to_add_to.appendChild(div_to_put);
}, 500);
}
document.getElementById("navigation").querySelector("INPUT").onblur = function () {
this.value = "";
document.querySelector("#navigation div").style.visibility = "hidden";
document.querySelector("#navigation div").innerHTML = "";
}
body {
margin: 0;
}
#navigation {
min-width: 620px;
background-color: silver;
width: 100%;
height: 50px;
position: fixed;
top: 0;
}
#navigation input {
height: 30px;
width: 200px;
font-size: 15px;
color: orange;
border: 1px solid orange;
border-radius: 5px;
display: block;
margin: 10px 5% 0% auto;
padding: 0px 28px 0px 5px;
float: right;
}
#navigation div {
width: 200px;
height: 50px;
position: absolute;
top: 41px;
right: 5%;
color: orange;
background-color: white;
border: 1px solid orange;
border-radius: 5px;
visibility: hidden;
}
#navigation div div {
width: 100%;
height: 30px;
text-align: center;
font-size: 25px;
color: orange;
border: 1px solid orange;
border-radius: 5px;
overflow: hidden;
position: absolute;
top: 0;
right: 0;
}
<html>
<head>
<meta charset="utf-8" />
<title>Page Title</title>
</head>
<body>
<div id="navigation">
<input type="text" name="Search">
<div></div>
</div>
</body>
</html>
Unlike the onclick event, the onmousedown event is fired before the onblur event:
var input_timeout = undefined;
document.getElementById("navigation").querySelector("INPUT").onkeyup = function () {
clearTimeout(input_timeout);
var val = this.value;
input_timeout = setTimeout(function () {
var to_add_to = document.querySelector("#navigation div");
to_add_to.innerHTML = "";
to_add_to.style.visibility = "visible";
var div_to_put = document.createElement("div");
div_to_put.style.visibility = "visible";
div_to_put.id = val;
div_to_put.innerHTML += "<font>" + val + "</font";
div_to_put.onmousedown = function () {
console.log(this.id);
}
to_add_to.appendChild(div_to_put);
}, 500);
}
document.getElementById("navigation").querySelector("INPUT").onblur = function () {
this.value = "";
document.querySelector("#navigation div").style.visibility = "hidden";
document.querySelector("#navigation div").innerHTML = "";
}
body {
margin: 0;
}
#navigation {
min-width: 620px;
background-color: silver;
width: 100%;
height: 50px;
position: fixed;
top: 0;
}
#navigation input {
height: 30px;
width: 200px;
font-size: 15px;
color: orange;
border: 1px solid orange;
border-radius: 5px;
display: block;
margin: 10px 5% 0% auto;
padding: 0px 28px 0px 5px;
float: right;
}
#navigation div {
width: 200px;
height: 50px;
position: absolute;
top: 41px;
right: 5%;
color: orange;
background-color: white;
border: 1px solid orange;
border-radius: 5px;
visibility: hidden;
}
#navigation div div {
width: 100%;
height: 30px;
text-align: center;
font-size: 25px;
color: orange;
border: 1px solid orange;
border-radius: 5px;
overflow: hidden;
position: absolute;
top: 0;
right: 0;
}
<html>
<head>
<meta charset="utf-8" />
<title>Page Title</title>
</head>
<body>
<div id="navigation">
<input type="text" name="Search">
<div></div>
</div>
</body>
</html>

Custom Javascript Prompt Dialog Box (how to retrieve value and store it as var)

I frantically need your help,
The variable "x" can normally be set using the following method (default)
var x = prompt("Please enter your name:","John Smith")
I'd very much similarly like to mimic the same idea and writting it such that it will work with my existing dynamic/custom dialog/prompt box. To this end, I am very not much familiar with asynchronous javascript and have little experience in that impossible department.
Expected result:
var x = alertBox('Enter your firstname','prompt','John Smith')
Here is the HTML/CSS and Javascript Markup:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function testit() {
var x = alertBox('Enter your firstname','prompt','John Smith')
alert(x)
}
function alertBox(text, type, ptext) {
var button = '<div id="alertBox_button_div" ><input id="alertBox_button" class="button" style="margin: 7px;" type="button" value="Close" onclick="alertBox_hide()"></div>'
var field = '<div><input id="ptext" class="field" type="text"></div>'
if (type == "err") {
document.getElementById('alertBox_text').innerHTML = text + button
document.getElementById('alertBox_text').style.color = "#FF0000"
document.getElementById('alertBox_text').style.top = "50%"
}
else if (type == "ok") {
document.getElementById('alertBox_text').innerHTML = text + button
document.getElementById('alertBox_text').style.top = "50%"
}
else if (type == "prompt") {
document.getElementById('alertBox_text').innerHTML = text + field + button
document.getElementById('alertBox_text').style.top = "25%"
document.getElementById('alertBox_button').value = "OK"
if (ptext) { document.getElementById('ptext').value = ptext }
}
else {
document.getElementById('alertBox_text').innerHTML = text
}
document.getElementById('alertBox_container').style.visibility = 'visible'
}//end function
function alertBox_hide() {
document.getElementById('alertBox_container').style.visibility = 'hidden'
}
</script>
<style type="text/css">
.field {
border: 1px solid #808080;
width: 475px;
font-family: Arial;
font-size: 9pt;
padding-left: 3px;
font-weight: bold;
margin: 1px;
}
#alertBox {
height: 100px;
width: 500px;
bottom: 50%;
right: 50%;
position: absolute;
font-family: Arial;
font-size: 9pt;
visibility: hidden;
}
#alertBox_container {
border: 1px solid #808080;
left: 50%;
padding: 10px;
top: 50%;
margin: 0;
padding: 0;
height: 100%;
border: 1px solid rgb(128,128,128);
height: 100%;
position: relative;
color: rgb(11,63,113);
}
#alertBox_titlebar {
cursor: pointer;
height: 22px;
width: 100%;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff", endColorstr="#cdcdcd");
line-height:22px;
font-weight: bold;
}
#alertBox_close {
line-height: 10px;
width: 17px;
margin-top: 2px;
margin-right: 2px;
padding: 1px;
position:absolute;
top:0;
right:0;
font-size: 10px;
font-family: tahoma;
font-weight: bold;
color: #464646;
border: 1px solid;
border-color: #999 #666 #666 #999;
background-color:#ccc;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E7E7E7');
}
#alertBox_close:hover {
background-color: #ddd;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#fafafa', EndColorStr='#dddddd');
color: #000000;
}
#alertBox_text {
position: absolute;
width: 100%;
height: auto;
top: 50%;
text-align: center;
}
.button {
color: #464646;
font-family: Arial;
font-size: 9pt;
height: 23px;
border: 1px solid;
border-color: #999 #666 #666 #999;
background-color: #ccc;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E7E7E7');
width: 67px;
}
}
.button:hover {
background-color: #ddd;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#fafafa', EndColorStr='#dddddd');
color: #000000;
}
</style>
</head>
<body>
<input type="button" value="testme" onclick="testit()">
<br>
<div id="alertBox">
<div id="alertBox_container">
<div id="alertBox_titlebar"><span style="padding-left: 3px;">IMTS</span></div>
<div><input id="alertBox_close" type="button" value="X" onclick="alertBox_hide()"></div>
<div id="alertBox_text"></div>
</div>
</div>
</body>
</html>
add a return value to your alertBox() function.
function alertBox(arg1,arg2,arg3)
{
// do your stuff here
var ishallreturn = document.getElementById("ptext").value;
return ishallreturn;
}

Cannot call back text field value in a custom prompt box

I need your help.
Normally one can use the:
var x = prompt("Please enter your name:","John Smith")
alert(x)
I'd similarly like to mimic the code above with my existing custom dialog/prompt box, but I cannot seem to get it to work and retrieve the value of x:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function testit() {
var x = alertBox('Enter your firstname','prompt','John Smith')
alert(x)
}
function alertBox(text, type, ptext) {
var button = '<div id="alertBox_button_div" ><input id="alertBox_button" class="button" style="margin: 7px;" type="button" value="Close" onclick="alertBox_hide()"></div>'
var field = '<div><input id="ptext" class="field" type="text"></div>'
if (type == "err") {
document.getElementById('alertBox_text').innerHTML = text + button
document.getElementById('alertBox_text').style.color = "#FF0000"
document.getElementById('alertBox_text').style.top = "50%"
}
else if (type == "ok") {
document.getElementById('alertBox_text').innerHTML = text + button
document.getElementById('alertBox_text').style.top = "50%"
}
else if (type == "prompt") {
document.getElementById('alertBox_text').innerHTML = text + field + button
document.getElementById('alertBox_text').style.top = "25%"
document.getElementById('alertBox_button').value = "OK"
if (ptext) { document.getElementById('ptext').value = ptext }
}
else {
document.getElementById('alertBox_text').innerHTML = text
}
document.getElementById('alertBox_container').style.visibility = 'visible'
}//end function
function alertBox_hide() {
document.getElementById('alertBox_container').style.visibility = 'hidden'
}
</script>
<style type="text/css">
.field {
border: 1px solid #808080;
width: 475px;
font-family: Arial;
font-size: 9pt;
padding-left: 3px;
font-weight: bold;
margin: 1px;
}
#alertBox {
height: 100px;
width: 500px;
bottom: 50%;
right: 50%;
position: absolute;
font-family: Arial;
font-size: 9pt;
visibility: hidden;
}
#alertBox_container {
border: 1px solid #808080;
left: 50%;
padding: 10px;
top: 50%;
margin: 0;
padding: 0;
height: 100%;
border: 1px solid rgb(128,128,128);
height: 100%;
position: relative;
color: rgb(11,63,113);
}
#alertBox_titlebar {
cursor: pointer;
height: 22px;
width: 100%;
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff", endColorstr="#cdcdcd");
line-height:22px;
font-weight: bold;
}
#alertBox_close {
line-height: 10px;
width: 17px;
margin-top: 2px;
margin-right: 2px;
padding: 1px;
position:absolute;
top:0;
right:0;
font-size: 10px;
font-family: tahoma;
font-weight: bold;
color: #464646;
border: 1px solid;
border-color: #999 #666 #666 #999;
background-color:#ccc;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E7E7E7');
}
#alertBox_close:hover {
background-color: #ddd;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#fafafa', EndColorStr='#dddddd');
color: #000000;
}
#alertBox_text {
position: absolute;
width: 100%;
height: auto;
top: 50%;
text-align: center;
}
.button {
color: #464646;
font-family: Arial;
font-size: 9pt;
height: 23px;
border: 1px solid;
border-color: #999 #666 #666 #999;
background-color: #ccc;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#ffffff', EndColorStr='#E7E7E7');
width: 67px;
}
}
.button:hover {
background-color: #ddd;
filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#fafafa', EndColorStr='#dddddd');
color: #000000;
}
</style>
</head>
<body>
<input type="button" value="testme" onclick="testit()">
<br>
<div id="alertBox">
<div id="alertBox_container">
<div id="alertBox_titlebar"><span style="padding-left: 3px;">IMTS</span></div>
<div><input id="alertBox_close" type="button" value="X" onclick="alertBox_hide()"></div>
<div id="alertBox_text"></div>
</div>
</div>
</body>
</html>
Since the value of x is not known until a future event, you need an async callback. So instead of this:
var x = alertBox('Enter your firstname','prompt','John Smith');
alert(x);
You need something like this instead:
alertBox('Enter your firstname','prompt','John Smith', function(x) {
alert(x);
// call other code here, pass "x" as parameter
});
The alertBox function should have one extra parameter callback, which you invoke when the value is ready, for example:
function alertBox(text, type, ptext, callback) {
// ...
document.getElementById('alertBox_button').addEventListener("click", function() {
callback(document.getElementById('ptext').value);
});
}
Here is a Fiddle demo.

Categories