In this Favourite place Dynamic Web Application achieving the design with HTML, CSS, and functionality with JS. I had not getting to do the functionality with JS, I'm facing problem as
When the Submit button is clicked
Text content in the HTML paragraph element should contain the value
of the checked HTML radio input element.
Below is the image of expected output:-
Favourite Place output image:
Note :-
The HTML radio input element with value Agra, should have checked atrribute by default.
You can use HTML form element.
Here is the code I tried
let questionsFormElement = document.getElementById("questionsForm");
let inputElement = document.getElementById("favouritePlace");
let input1Element = document.getElementById("favouritePlace1");
let input2Element = document.getElementById("favouritePlace2");
let label1Element = document.getElementById("label1");
let label2Element = document.getElementById("label2");
let label3Element = document.getElementById("label3");
let submitBtnElement = document.getElementById("submitBtn");
let textParagraphElement = document.getElementById("textParagraph");
submitBtnElement.addEventListener("click", function(){
inputElement.textContent = "Your favourite place is:" + label1Element.textContent;
});
#import url("https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap");
.heading {
font-family: "Roboto";
font-size: 30px;
}
.label-element {
font-family: "Roboto";
font-size: 14px;
}
.button {
height: 30px;
width: 65px;
font-size: 15px;
margin-top: 10px;
margin-left: 10px;
color: white;
background-color: #327fa8;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1 class="heading">Select Your Favourite Place</h1>
<form id="questionsForm" class="p-4 questions-form">
<input type="radio" id="favouritePlace" value="Lucknow" name="Lucknow" />
<label for="favouritePlace" id="label1" class="label-element">Lucknow</label>
<br/>
<input type="radio" id="favouritePlace1" value="Agra" name="Agra" checked />
<label for="favouritePlace1" id="label2" class="label-element">Agra</label>
<br/>
<input type="radio" id="favouritePlace2" value="Varanasi" name="Varanasi" />
<label for="favouritePlace1" id="label3" class="label-element">Varanasi</label>
<br/>
<button class="button" id="submitBtn">Submit</button>
<p id="textParagraph"></p>
</form>
</body>
</html>
For the radio buttons, you have to give the same name for all the input tags which you want to group in one tag. And you have used form so when you press submit button it will send a request and the page will reload. solution for that is to use e.preventDefault().
And also you need to add final text into the p tag :
textParagraphElement.textContent
let submitBtnElement = document.getElementById("submitBtn");
let textParagraphElement = document.getElementById("textParagraph");
submitBtnElement.addEventListener("click", function(e){
e.preventDefault()
textParagraphElement.textContent = "Your favourite place is:" + document.querySelector('input[name="location"]:checked').value;
});
#import url("https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap");
.heading {
font-family: "Roboto";
font-size: 30px;
}
.label-element {
font-family: "Roboto";
font-size: 14px;
}
.button {
height: 30px;
width: 65px;
font-size: 15px;
margin-top: 10px;
margin-left: 10px;
color: white;
background-color: #327fa8;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1 class="heading">Select Your Favourite Place</h1>
<form id="questionsForm" class="p-4 questions-form">
<input type="radio" id="favouritePlace" value="Lucknow" name="location" />
<label for="favouritePlace" id="label1" class="label-element">Lucknow</label>
<br/>
<input type="radio" id="favouritePlace1" value="Agra" name="location" checked />
<label for="favouritePlace1" id="label2" class="label-element">Agra</label>
<br/>
<input type="radio" id="favouritePlace2" value="Varanasi" name="location" />
<label for="favouritePlace2" id="label3" class="label-element">Varanasi</label>
<br/>
<button class="button" id="submitBtn">Submit</button>
<p id="textParagraph"></p>
</form>
</body>
</html>
You are missing several things:
Prevent default on your submit function so the page does not refresh after clicking the submit button.
For radios to work as a group you need to give them the same name (see "myRadio" on my snippet)
You are missing a way to know which radio was checked, see my callback function where I get radio and iterate over the values to see which one was checked, this can be done in many different ways, this is just one approach.
EDIT: Jay Patel suggested a better approach to get the value directly.
let questionsFormElement = document.getElementById("questionsForm");
let inputElement = document.getElementById("favouritePlace");
let input1Element = document.getElementById("favouritePlace1");
let input2Element = document.getElementById("favouritePlace2");
let label1Element = document.getElementById("label1");
let label2Element = document.getElementById("label2");
let label3Element = document.getElementById("label3");
let submitBtnElement = document.getElementById("submitBtn");
let textParagraphElement = document.getElementById("textParagraph");
submitBtnElement.addEventListener("click", function(e) {
e.preventDefault();
const radio = document.querySelector('input[name="myRadio"]:checked').value
textParagraphElement.innerHTML = 'Your favorite place is: ' + radio;
});
#import url("https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap");
.heading {
font-family: "Roboto";
font-size: 30px;
}
.label-element {
font-family: "Roboto";
font-size: 14px;
}
.button {
height: 30px;
width: 65px;
font-size: 15px;
margin-top: 10px;
margin-left: 10px;
color: white;
background-color: #327fa8;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1 class="heading">Select Your Favourite Place</h1>
<form id="questionsForm" class="p-4 questions-form">
<input type="radio" id="favouritePlace" value="Lucknow" name="myRadio" />
<label for="favouritePlace" id="label1" class="label-element">Lucknow</label>
<br/>
<input type="radio" id="favouritePlace1" value="Agra" name="myRadio" checked />
<label for="favouritePlace1" id="label2" class="label-element">Agra</label>
<br/>
<input type="radio" id="favouritePlace2" value="Varanasi" name="myRadio" />
<label for="favouritePlace2" id="label3" class="label-element">Varanasi</label>
<br/>
<button class="button" id="submitBtn">Submit</button>
<p id="textParagraph"></p>
</form>
</body>
</html>
Related
I want to put the table row in an array than use the loop to iterate the array for comparing two rows but i don't know how this sort method of array works is it going to compare from S.No column than initials column and so on.
how to use the array method to sort()- ascending order and descending order by reverse().
I don't want to use code from google want to make my own logic just help me where i am lacking.
<!DOCTYPE html>
<html>
<head>
<style>
.tab,
.tab th,
.tab tr,
.tab td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
}
.circle {
background-color: yellow;
border-radius: 50%;
margin: 2px 22px 2px;
line-height: 10px;
padding: 12px;
text-align: center;
vertical-align: middle;
display: inline-block;
}
</style>
</head>
<body>
<h2><u>CONTACT MANAGEMENT </u></h2></br></br>
<form>
<label>First Name</label>
<input type="text" id="fname" style="text-transform: capitalize;" />
<label>Last Name</label>
<input type="text" id="lname" style="text-transform: capitalize;" /></br></br>
<label>Number</label>
<input type="text" id="phone" pattern="[1-9]{1}[0-9]{9}" maxlength="10" /></br></br>
<input type="hidden" id="hdn" value="1">
<button type="button" onclick="dataSave()">save</button></br></br>
</form>
</br></br>
<div class="div1">
<table class="tab" id="table">
<th>S.No</th>
<th>Initals</th>
<th>FullName</th>
<th>PhoneNo.</th>
<tbody id="table_row">
</tbody>
</table>
</div>
<button type="button" id="asort_btn" class="sort" onclick="asec_sort()">Asec</button>
<button type="button" id="dsort_btn" class="sort" onclick="desc_sort()">Desc</button>
<script>
function dataSave()
{
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var phone = document.getElementById('phone').value;
var firstNameArr = new Array();
var lastNameArr = new Array();
var phoneNoArr = new Array();
firstNameArr.push(first);
lastNameArr.push(last);
phoneNoArr.push(phone);
var num = parseInt(document.getElementById("hdn").value);
for(i=0;i<firstNameArr.length;i++)
{
var preFirstName = firstNameArr[i].slice(0,1);
var preLastName = lastNameArr[i].slice(0,1);
document.getElementById('table_row').innerHTML += `<tr><td>${num}</td>
<td class="circle">${preFirstName}${preLastName}</td>
<td>${firstNameArr[i]} ${lastNameArr[i]}</td>
<td>${phoneNoArr[i]}</td></tr>`;
}
num = num+1;
document.getElementById('hdn').value=num;
document.getElementById('fname').value="";
document.getElementById('lname').value="";
document.getElementById('phone').value="";
}
function asec_sort()
{
alert('hi');
var tableRowArr = new Array();
tableRowArr = document.getElementById('table_row').innerHTML;
console.log(tableRowArr);
console.log(tableRowArr.sort());
}
</script>
</body>
</html>
What I want to try to do is kind of tricky so I will list the steps and my code below.
When the page opens the user is presented two options via checkboxes. On load neither are defaulted as checked. If the user checks the top one and decides they dont want that one the other should be cleared.
Whatever ends up being selected and they press Submit, I would like that array to populate the screen. Right now its just dummy names but will change. If after loading the array and they want to change to the other check box, the array on the screen needs to be cleared and the other one loaded with breaks between them. That holds true for either one they choose.
Ive posted my code so far below. The html renders correctly. What I dont know how to do is load the arrays. Just learning JS but this was presented to me to get done.
<script>
var cash = ["Susan", "Billy", "Jennifer"];
document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
document.write(cust[0]);
</script>
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" id="Cash Applications" name="Cash Applications" value="Cash Apps">
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" id="Customer Service" name="Customer Service" value="Customer Service">
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
</body>
</html>
Checkboxes usually let the user select more than one. Your restriction of only allowing one to be selected is kind of nonstandard so I've changed them to radio buttons.
You've also got an action on your form, which will cause it to load another page. I added an onclick handler which stops it from submitting.
var cash = ["Susan", "Billy", "Jennifer"];
//document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
//document.write(cust[0]);
function do_submit() {
// Decide which list to use:
var list = null;
if ( document.getElementById('Cash Applications').checked ) {
list = cash;
}
if ( document.getElementById('Customer Service').checked ) {
list = cust;
}
if ( list == null ) {
alert( 'Please select a list.' );
} else {
Put the list items on the page in the 'list' div:
let listElement = document.getElementById( 'list' );
listElement.innerHTML = '';
list.forEach( function( name ) {
listElement.innerHTML += name + '<br>';
});
}
return false;
}
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php" onsubmit="return do_submit();">
<input type="radio" id="Cash Applications" name="name" value="Cash Apps">
<label for="CashApplications"> Cash Applications</label><br>
<br>
<input type="radio" id="Customer Service" name="name" value="Customer Service">
<label for="Customer Service"> Customer Service</label><br>
<br>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
<div id="list">names will appear here</div>
</body>
</html>
So, your current scripts just directly append with document.writes. You need to define some elements to hold the info you want to display/update. I defined a div named "displaySelected". It starts out empty.
To handle the toggle of checkboxes you need some onclick functions for each checkbox... I defined a single one named selectBox and passed in a string to tell the function which checkbox was checked. In that function if cash was clicked then I clear cust and if cust was checked then I clear cash.
To handle displaying the selection you need an onclick function for the submit button. I created one named selectArray(). It clears out the contents of the displaySelected div and then creates an unordered list element then loops through whichever array was selected and creates list item elements and populates their text with the item from the array. Use the appendChild() function to add the li to the ul and the ul to the div
To handle clearing the selection you need an onclick function for the clear button. I created one named clearSelection(). It unchecks both boxes and then clears out the contents of the displaySelected div by setting its innerHTML to ''
var cash = ["Susan", "Billy", "Jennifer"];
var cust = ["David", "Larry", "Melissa"];
var cashBox = document.getElementById("Cash Applications");
var custBox = document.getElementById("Customer Service");
var displayDiv = document.getElementById("displaySelected");
function selectBox(box) {
switch (box) {
case 'cash':
custBox.checked = false;
break;
case 'cust':
cashBox.checked = false;
break;
default:
break;
}
}
function selectArray() {
displayDiv.innerHTML = '';
var uList = document.createElement("ul");
if (cashBox.checked) {
for (var cashIndex = 0; cashIndex < cash.length; cashIndex++) {
var cashEle = document.createElement("li");
cashEle.innerText = cash[cashIndex];
uList.appendChild(cashEle);
}
} else if (custBox.checked) {
for (var custIndex = 0; custIndex < cust.length; custIndex++) {
var custEle = document.createElement("li");
custEle.innerText = cust[custIndex];
uList.appendChild(custEle);
}
}
displayDiv.appendChild(uList);
}
function clearSelection() {
cashBox.checked = false;
custBox.checked = false;
displayDiv.innerHTML = '';
}
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<center>
<img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" id="Cash Applications" name="Cash Applications" value="Cash Apps" onclick="selectBox('cash')">
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" id="Customer Service" name="Customer Service" value="Customer Service" onclick="selectBox('cust')">
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<br>
<input type="submit" value="Select" onclick="selectArray()">
<button type="Clear Selection" id="button1" onclick="clearSelection()">Clear</button>
</form>
<br><br>
<div id="displaySelected">
</div>
</center>
</body>
</html>
This is not as elaborate as the previous answer, but it still works.
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
</head>
<script>
var cash = ["Susan", "Billy", "Jennifer"];
document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
document.write(cust[0]);
function doChkClick(e) {
//get references to elements
spn = document.getElementById('spnout');
chkcash = document.getElementById('chkCash');
chkcust = document.getElementById('chkCust');
// reverse other checkbox
if (e === chkcash && e.checked) chkcust.checked = false
if (e === chkcust && e.checked) chkcash.checked = false
// show array
if (chkcash.checked) spn.innerHTML = cash.join(' ')
if (chkcust.checked) spn.innerHTML = cust.join(' ')
// if nothing checked
if (!chkcash.checked && !chkcust.checked)
spn.innerHTML = '[Empty]'
}
</script>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" name="Cash Applications" value="Cash Apps" id="chkCash" onclick=doChkClick(this)>
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" name="Customer Service" value="Customer Service" id="chkCust" onclick=doChkClick(this)>
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<b><span id="spnout">[Empty]</span></b>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
</body>
</html>
If you prefer to have the script separate from the html, you can use these files:
main.js
var cash = ["Susan", "Billy", "Jennifer"];
document.write(cash[0]);
var cust = ["David", "Larry", "Melissa"];
document.write(cust[0]);
function doChkClick(e) {
//get references to elements
spn = document.getElementById('spnout');
chkcash = document.getElementById('chkCash');
chkcust = document.getElementById('chkCust');
// reverse other checkbox
if (e === chkcash && e.checked) chkcust.checked = false
if (e === chkcust && e.checked) chkcash.checked = false
// show array
if (chkcash.checked) spn.innerHTML = cash.join(' ')
if (chkcust.checked) spn.innerHTML = cust.join(' ')
// if nothing checked
if (!chkcash.checked && !chkcust.checked)
spn.innerHTML = '[Empty]'
}
main.htm
<DOCTYPE = html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 100%;
}
label {
color: blue;
font-family: verdana;
font-size: 100%;
}
.wrapper {
text-align: center;
display: inline-block;
position: absolute;
top: 50%;
left: 50%;
}
</style>
<script src="main.js"></script>
</head>
<body>
<center>
<p><img src="C:\Users\hac532\Desktop\Logos\CO-BT.JPG" alt="CO Logo" style="width:231px;height:212px;margin-left:15px;">
<h1>Select the department you want comments for from the list below by checking the box next to it</h1>
<br>
<br>
<form action="/action_page.php">
<input type="checkbox" name="Cash Applications" value="Cash Apps" id="chkCash" onclick=doChkClick(this)>
<label for="Cash Applications"> Cash Applications</label><br>
<br>
<input type="checkbox" name="Customer Service" value="Customer Service" id="chkCust" onclick=doChkClick(this)>
<label for="vehicle2"> Customer Service</label><br>
<br>
<br>
<b><span id="spnout">[Empty]</span></b>
<br>
<br>
<input type="submit" value="Select">
<button type="Clear Selection" id="button1" >Clear</button>
</center>
</body>
</html>
novice here.
Trying to find a way to get the value of the checked radio button (formatted as a Hex Code) to be the background-color of a specific class. Basically, I have a box that I'd like the user to be able to customize and setting the color of elements based on radio selection is crucial to making it work. Here's what I have so far:
<form id="2019-Holiday" name="2019-Holiday" data-name="2019 Holiday" class="form">
<input type="radio" name="box-color" value="#177262" data-name="box-color" id="177262">
<input type="radio" name="box-color" value="#80a44a" data-name="box-color" id="80a44a">
</form>
<div class=box-color" id="box-color">
<div class="box-background-color" id="box-wall1"></div>
<div class="box-background-color" id="box-wall2"></div>
</div>
<script>
document.getElementById("box-color").onclick = function() {
boxBackgroundColor();
};
function boxBackgroundColor() {
var ele = document.getElementsByName("box-color");
var elements = document.getElementsByClassName("box-background-color"); // get all elements
for (var i = 0; i < elements.length; i++)
for (i = 0; i < ele.length; i++) {
if (ele[i].checked)
elements[i].style.backgroundColor = ele[i].value;
}
}
</script>
I know that the checked radio bit is working, but the background color of the class part seems to break it. Any help would be appreciated!
Edited to add form/html elements.
Instead of adding a onClick-handler to a specific div, I would rather set an onChange-handler for the form itself and get the selected value whenever a radiobutton has changed.
Also, the ID 2019-Holiday is not valid, as IDs cant start with a number.
document.querySelector('#Holiday-2019').onchange = function(e) {
var selectedColor = e.target.value;
boxBackgroundColor(selectedColor);
};
function boxBackgroundColor(selectedColor) {
var elements = document.getElementsByClassName("box-background-color"); // get all elements
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = selectedColor;
}
}
form {
padding: 10px 0;
}
#box-color {
width: 400px;
height: 200px;
background: gray;
}
.box-background-color {
width: 100%;
height: 49%;
margin-bottom: 2%;
align-items: center;
display: flex;
justify-content: center;
}
<form id="Holiday-2019" class="form">
<input type="radio" name="box-color" value="#177262" id="177262"> Dark green
<input type="radio" name="box-color" value="#80a44a" id="80a44a">Light green
</form>
<div id="box-color">
<div class="box-background-color" id="box-wall1">Boxwall1</div>
<div class="box-background-color" id="box-wall2">Boxwall2</div>
</div>
How I code this ( if it help ?)
const myForm = document.querySelector('#my-form')
myForm.onchange=_=>
{
document.body.style.background = myForm['box-color'].value;
}
body { background-color: white; }
label { display: block; width:200px; background-color: grey; margin: 0.5em;}
<form action="xxx" id="my-form">
<label><input type="radio" name="box-color" value="white" checked > white</label>
<label><input type="radio" name="box-color" value="blue" > blue</label>
<label><input type="radio" name="box-color" value="red" > red</label>
<label><input type="radio" name="box-color" value="green" > green</label>
</form>
And to style a specific class: ( just 4 lines of code )
const Root = document.documentElement
, myForm = document.querySelector('#my-form')
myForm.onchange=_=>
{
Root.style.setProperty('--bg-color', myForm['box-color'].value)
}
:root {
--bg-color : blue;
}
.myDivClass{
background-color: var(--bg-color);
display : inline-block;
margin : 1em;
width : 100px;
height : 100px;
}
label {
display : inline-block;
width : 5.5em;
background-color: lightgrey;
margin : 0.3em;
padding : .5em .2em;
border : 1px solid black;
border-radius : .5em;
text-transform : capitalize;
line-height : 1em;
}
<div class="myDivClass"></div>
<div class="myDivClass"></div>
<div class="myDivClass"></div>
<div class="myDivClass"></div>
<form action="xxx" id="my-form">
<label><input type="radio" name="box-color" value="blue" checked> blue </label>
<label><input type="radio" name="box-color" value="red" > red </label>
<label><input type="radio" name="box-color" value="green"> green </label>
</form>
function changeColor(e) {
// by ID
document.getElementById("box").style.backgroundColor = e.value;
// by className
let element = document.getElementsByClassName("box");
Array.prototype.forEach.call(element, function (el) {
el.style.backgroundColor = e.value;
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<input type="radio" name="color" class="radio" value="#FF0000" id="" onchange="changeColor(this)">red
<input type="radio" name="color" class="radio" value="yellow" id="" onchange="changeColor(this)">yellow
<input type="radio" name="color" class="radio" value="green" id="" onchange="changeColor(this)">green
</div>
<div id="box" class="box" style="height:100px;width:100px;background-color: black;">
</div>
</body>
</html>
I've been researching for a few days methods of controlling UI with checkboxes and with the help of some members on Stack' I've come really quite far. But my balding doesn't quite stop yet. I've been trying to further tweak my code snippet, by including a numeric value alongside my UI controller. (This value will be of use later inside the web-java applet.)
For example, when a checkbox is checked var total is ammended from 0 to 30. If a Checkbox is unchecked the value returns to '0'.
(Main Build JS Fiddle),
(Checkbox Example).
The second fiddle allows the use of data attributes, however these will need to be injected into the HTML via, JS. As like before I have 'NO' access to the CSS or HTML source files.
(Original Post)
- This post is a follow on from another question asked here on stack, due to the nature of the question changing, and the comments getting fairly confusing I was asked to open a new thread.
Below I'll post two snippets, one is of the original build, built with the aid of user #acontell. The other is an example of the type of result I am after, built with the aid of, user #Rajesh. Link to (Example Source).
The Base Build
// Control UI...
(function(domElements, cbState) {
// Number increment
var total = 0 + ' mm';
document.getElementById('adjvar').value = total;
function clickCallback() {
toggleElements(this.className);
}
function toggleElements(className, initialShow) {
var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;
division.style.display = isShown ? 'block' : 'none';
checkBox.checked = isShown;
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// increment count...
var val = 30;
total += (+val * (checkBox.checked ? 1 : -1));
document.getElementById('adjvar').value = total + ' mm';
document.getElementsByClassName('adjvar').value = checkBox.checked ? val : 0 + ' mm';
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
}
domElements
.filter(function(el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function(el, index) {
el.addEventListener('click', clickCallback, false);
toggleElements(el.className, cbState[index]);
});
})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
// inject style
function ctSe() {
var css = "input[type='checkbox'] { float:left; margin-right: 1em !important;}",
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
console.log(head)
console.log(style)
console.log(css)
};
ctSe();
.editoraccvar {
width: 300px;
background: #f0f;
padding: .5em;
}
.editoropt {
width: 300px;
background: #0f0;
padding: .5em;
}
.editoraccvar1 {
width: 300px;
background: #0ff;
padding: .5em;
}
.editoropt1 {
width: 300px;
background: #ff0;
padding: .5em;
}
textarea {
display: block;
width: 95%;
resize: none;
padding: .5em;
}
<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field field-summernote editoraccvar ">
<label for="accvar1">Ground Floor Info</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<!-- Secondary Division -->
<div class="seq-box-form-field field-summernote editoraccvar1 ">
<label for="accvar1">First Floor</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Secondary Checkbox -->
<div class="seq-box-form-field editoropt1 ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">First Floor </span>
<input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<input name="adjvar" id="adjvar" readonly>
The Example
(function() {
var total = 0;
function calculate(index) {
var el = document.getElementsByClassName('checkbox-input')[index];
var val = el.getAttribute("data-value");
total += (+val * (el.checked ? 1 : -1));
document.getElementById('pnvar').value = total;
document.getElementsByClassName('pnvar')[index].value = el.checked ? val : 0;
}
function registerEvents() {
var cbs = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(cbs, function(cb, i) {
cb.addEventListener("click", function() {
calculate(i);
});
});
document.getElementById('pnvar').addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
})
}
window.addEventListener('load', function() {
registerEvents();
calculate(0)
})
})()
.editoropt {
font-family: Calibri, sans-serif;
width: 160px;
background: #f8f8ff;
padding: .5em;
border: solid 1px #ddd;
}
#checkboxopt {
float: left;
margin-right: 1em;
margin-top: 4px;
}
#checkboxopt1 {
float: left;
margin-right: 1em;
margin-top: 4px;
}
.pnvar {
width: 95%;
}
input:-moz-read-only {
/* For Firefox */
background-color: transparent;
border: none;
border-width: 0px;
}
input:read-only {
background-color: transparent;
border: none;
border-width: 0px;
}
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Default 80mm </span>
<input type="checkbox" class="checkbox-input" data-value="80" name="checkboxopt" id="checkboxopt" value="true" checked />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Add 30mm </span>
<input type="checkbox" class="checkbox-input" name="checkboxopt1" data-value="30" id="checkboxopt1" value="true" />
<input type="hidden" name="opt2" id="opt2" value="true" />
</label>
</div>
<div class="editoropt">
<input id="pnvar" name="pnvar" placeholder="Null" onkeydown="" value="" class="required" type="text">
<input name="adjvar" class="pnvar" id="adjvar" readonly value="0">
<input name="adjvar" class="pnvar" id="adjvar2" readonly value="0">
</div>
As I mentioned in my previous post, I'm not a JS Whizz and I'm just finding my feet, however I am abitious to learn and further my knowledge. Any assistance would be greatly appreciated.
Note : All tags, classes and names, must remain the same for consistancy with another application.
I might be mistaken but I think that this two lines of code:
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
Could be avoided if you passed [true, false] as the initial states of the checkboxes:
([].slice.call(document.querySelectorAll('.seq-box-form-field')), [true, false]);
I might be wrong, you might be doing something else or the state of the page could require that click, I don't know.
Going back to the issue, if you want to increase/decrease by 30 when the checkbox is checked/unchecked, you could do as follows:
Create a function that retrieves the value of the input an updates it with a quantity added to it. The value of the input is a string of the form 'x mm' so a bit of tinkering is necessary to get the integer part of the value.
function updateInputValue(n) {
var actual = +document.getElementById('adjvar').value.split(' mm')[0] || 0;
document.getElementById('adjvar').value = (actual + n) + ' mm';
}
Inside toggleElement call this function in order to update the input value.
var increment = isShown ? 30 : -30;
updateInputValue(initialShow === undefined ? increment : +initialShow * 30);
It gets a bit complicated because you have to control the initial state of the inputs, but it's not that hard: if it's the initial state, initialShow is different from undefined so we transform the value (it's a boolean) into a number a multiply it by 30 (when it's checked, it'd be 1 * 30, when it's unchecked it'd be 0 * 30). When it's not the initial state, we increment/decrement depending on whether it's checked or not.
And here's the fiddle (I also commented out the part that clicked the checkbox). Hope it helps.
I'm making text editor for my project , i need to use this editor for forum , i'm making simple texteditor using javascript everything working fine . Problem is that i can't use <b></b> or <i></i> <u></u> because of htmlentities. My question is that how to bold text using [b][/b] instead of <b></b> or [i][/i] instead of <i></i> , i needed this very much. I need your help guys , Thanks.
Below Is My Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#my_textarea{
width: 320px;
height: 150px;
border: thin solid #000;
color: #000;
padding: 10px;
min-height: 150px;
min-width: 320px;
max-height: 150px;
max-width: 320px;
}
#preview{
width: 320px;
height: 150px;
border: thin solid #000;
color: #000;
padding: 10px;
}
</style>
<script type="text/javascript">
function formatText(tag) {
var myTextArea = document.getElementById('my_textarea');
var myTextAreaValue = myTextArea.value;
var selected_txt = myTextAreaValue.substring(myTextArea.selectionStart, myTextArea.selectionEnd);
var before_txt = myTextAreaValue.substring(0, myTextArea.selectionStart);
var after_txt = myTextAreaValue.substring(myTextArea.selectionEnd, myTextAreaValue.length);
myTextArea.value = before_txt + '<' + tag + '>' + selected_txt + '</' + tag + '>' + after_txt;
}
function preview() {
var textbox , view ;
textbox = document.getElementById('my_textarea');
view = document.getElementById("preview");
view.innerHTML = textbox.value
}
</script>
</head>
<body><br>
<form>
<input name="title" id="title" type="text" size="80" maxlength="80" /><br><br>
<input type="button" value="Bold" onClick="formatText ('b');" />
<input type="button" value="Italic" onClick="formatText ('i');" />
<input type="button" value="Underline" onClick="formatText ('u');" />
<input type="button" value="Unordered List" onClick="olist ('ul');" /><br><br>
<textarea name="my_textarea" id="my_textarea" style="width:300px;"></textarea><br>
<input type="submit" value="Submit" name="submit" id="submit" /><br><br>
</form>
<div id="preview"></div><br>
<button id="btn" onClick="preview();">Preview</button>
</body>
Demo : http://jsfiddle.net/aMR4M/
I'm not sure if this is what you want, but you can use [ and ] and replace them with < and > when setting the innerHtml of your preview area.
view.innerHTML = textbox.value.replace(/\[/g, '<').replace(/\]/g, '>');
See http://jsfiddle.net/aMR4M/1/