Multiple arrays, checkboxes - javascript

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>

Related

Sort table row using javascript's array method- sort( ) & reverse( )

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>

Favourite Place Javascript web application

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>

Use Radio value to set class background color?

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>

Replicating entries and XML with JavaScript

I'm building a user-submission system where a user can input data and an XML will be exported (which can be read by a different software down the line) but I'm coming across a problem where when I replicate the form for the user to input info, the XML is only taking information from the first.
Any suggestions on how do this?
Personal test code:
HTML:
$(function () {
$('#SubmitButton').click(update);
});
var added = [
'\t\t
<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>
'
].join('\r\n');
var adding = [
'\t\t
<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>
'
].join('\r\n');
function update() {
var variables = {
'channeldescription': $('#channeldescription').val(),
'channelrecordnumber': $('#channelrecordnumber').val(),
'channelhexcolor': $('#channelhexcolor').val(),
'channelbamlink': $('#channelbamlink').val()
};
var newXml = added.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
var finalXML = newXml;
$('#ResultXml').val(finalXML);
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(finalXML))
.attr('download', 'bamdata.xml');
$('#generated').show();
}
$(function () {
$("#CloneForm").click(CloneSection);
});
function CloneSection() {
added = added + '\n' + adding;
$("body").append($("#Entries:first").clone(true));
}
<!DOCTYPE html>
<html>
<head>
<script src="cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<body>
<div id="Entries" name="Entries">
<legend class="leftmargin"> Entry </legend>
<form class="form">
<fieldset>
<div class="forminput">
<label for="channel-description" class="formtextarea">Description</label>
<textarea id="channeldescription" name="channeldescription" type="text"></textarea>
</div>
<div class="forminput">
<label for="channel-record_number">Record number</label>
<input id="channelrecordnumber" name="channelrecordnumber"/>
</div>
<div class="forminput">
<label for="channel-hex_color">Hex color</label>
<input id="channelhexcolor" name="channelhexcolor"/>
</div>
<div class="forminput">
<label for="channel-bam_link">RNA-Seq Data/BAM file Repsitory Link</label>
<input id="channelbamlink" name="channelbamlink" type="text" data-help-text="bam_link"/>
</div>
</fieldset>
</form>
</div>
</body>
<div id="Cloning" class="button_fixed">
<p>
<button id="CloneForm">Add another entry</button>
<button id="SubmitButton">Generate XM</button>
</p>
</div>
<div id="generated" style="display:none">
<h2>bamdata.xml</h2>
Download XML
<textarea id="ResultXml" style="width: 100%; height: 30em" readonly></textarea>
</div>
</div>
</html>
http://www.w3schools.com/code/tryit.asp?filename=F0TWR6VRQZ3J
Change your ids to classes use a loop to get all the entries
<!DOCTYPE html>
<html>
<head>
<script src="cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
.leftmargin {
margin-left: 2%;
}
.form {
background-color: #CBE8BA;
border-radius: 25px;
margin-left: 2%;
margin-right: 2%;
padding-top: 1%;
padding-bottom: 1%;
}
.forminput {
padding-left: 1.5%;
padding-top: 0.5%;
display: flex;
}
.button_fixed {
position: fixed;
margin-left: 2%;
bottom: 1%;
}
</script>
<script>
$(function () {
$('#SubmitButton').click(function(){
var finalXML = '';
$(".Entries").each(function(i,v) {finalXML +=update(finalXML,v)
$('#ResultXml').val(finalXML);
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(finalXML))
.attr('download', 'bamdata.xml');
$('#generated').show();
});
});
});
var added = [
'\t\t<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>'
].join('\r\n');
var adding = [
'\t\t<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>'
].join('\r\n');
function update(finalXML,v) {
var variables = {
'channeldescription': $(v).find('.channeldescription').val(),
'channelrecordnumber': $(v).find('.channelrecordnumber').val(),
'channelhexcolor': $(v).find('.channelhexcolor').val(),
'channelbamlink': $(v).find('.channelbamlink').val()
};
var newXml = added.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
return newXml;
}
$(function () {
$("#CloneForm").click(CloneSection);
});
function CloneSection() {
$("body").append($(".Entries:first").clone(true));
}
</script>
<body>
<div class="Entries" name="Entries">
<legend class="leftmargin"> Entry </legend>
<form class="form">
<fieldset>
<div class="forminput">
<label for="channel-description" class="formtextarea">Description</label>
<textarea class="channeldescription" name="channeldescription" type="text"></textarea>
</div>
<div class="forminput">
<label for="channel-record_number">Record number</label>
<input class="channelrecordnumber" name="channelrecordnumber"/>
</div>
<div class="forminput">
<label for="channel-hex_color">Hex color</label>
<input class="channelhexcolor" name="channelhexcolor"/>
</div>
<div class="forminput">
<label for="channel-bam_link">BAM file Repsitory Link</label>
<input class="channelbamlink" name="channelbamlink" type="text" data-help-text="bam_link"/>
</div>
</fieldset>
</form>
</div>
</body>
<div id="Cloning" class="button_fixed">
<p>
<button id="CloneForm">Add another entry</button>
<button id="SubmitButton">Generate XM</button>
</p>
</div>
<div id="generated" style="display:none">
<h2>bamdata.xml</h2>
Download XML
<textarea id="ResultXml" style="width: 100%; height: 30em" readonly="readonly"></textarea>
</div>
</div>
</html>
demo:http://www.w3schools.com/code/tryit.asp?filename=F0TXIUR1CYE4

Jquery multidimensional arrays

I'm making an application where the user fills out all the information for a logo and adds it to a list where he can then add more logos or delete them.
Imagine I add a logo to the list with the following information:
Name: Pepsi
Location: Front, Back
Dimensions: 90mm, 60mm
Colors: Red, Blue, White
Options: Whitebg
Comment: This is a cool logo.
The array would be:
logos[logo[name, loc[], dim[], col[], opt[], com]]
Now I can do this to retrieve some info:
logos[0][0] //Prints "Pepsi"
logos[0][1][0] //Prints "Front"
logos[0][2][1] //Prints "60mm"
Now comes the problem. Whenever the user completes all the info and adds the logo the list I want to empty all the arrays except the main "logos" one so the user can add another logo to the list.
I tried to empty the "logo" array at the end of the "add" button function:
logo.length = 0;
But now the main array "logos" contains one "logo" array witch is empty. I want to keep that information there.
I think you could look at this differently.
I think you should just have a main logos array. And a Logo Object.
The Logo Object.
function Logo(name,loc, dim, col, opt, com){
return {
name:name,
loc:loc,
dim:dim,
col:col,
opt:opt,
com:com
}
}
var logos = [];
logos.push(Logo("blah",somthing[],else[]....);
Then reference by:
logos[0].name;
logos[0].dimensions[0];
....
you can add another...
logos.push(Logo("another",....));
Another Option
Same thing as before.
But instead of a Logos[]
Use a Logos = {} object.
You can dynamically add properties by given input like this.
Logos["First"] = Logo(loc,dim,col,opt,com);
Logos["Second"] = Logo(loc2,dim2,col2,opt2,com2);
If the user inputs that they want the "First" logo.
You can use
var firstlogo = Logos["first"];
firstlogo.loc[0] etc.
Play around with it, using objects provides a better understanding of the data you are dealing with, esp when multidimensional arrays are not "required"
I think you want do this :
var tempLogo = new Array();
tempLogo[0] = logos[0]; // or the logo you have choose
// Clear the logo
logos.clear();
// Set the logos with the tempLogo value
logos = tempLogo;
Finally I used objects instead of arrays as "Bodman" suggested. Works much better and is simpler.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
<meta charset="utf-8" />
<link href="css/reset.css" rel="stylesheet" type="text/css"/>
<link href="css/master.css" rel="stylesheet" type="text/css" media="screen"/>
</head>
<body>
<form action="/" method="post" id="form">
<p><label for="">Name:</label><input type="text" id="name"/></p>
<p><label for="">Location:</label><input type="checkbox" name="loc" value="Front"/> Front <input type="checkbox" name="loc" value="Back"/> Back <input type="checkbox" name="loc" value="Right"/> Right <input type="checkbox" name="loc" value="Left"/> Left</p>
<p><label for="">Dimensions:</label>H: <input type="text" size="4" id="dimH"/> W: <input type="text" size="4" id="dimW"/></p>
<p><label for="">Colors:</label><input type="text" size="4" id="col1" /> <input type="text" size="4" id="col2" /> <input type="text" size="4" id="col3" /> <input type="text" size="4" id="col4" /></p>
<p><label for="">Comments:</label><textarea id="com" cols="30" rows="2"></textarea></p>
<p><label for=""> </label><input type="button" id="add" value="Add" /> <input type="button" id="del" value="Del" /></p>
</form>
<ul id="results"></ul>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
</body>
</html>
CSS:
body { padding: 50px; }
p { margin: 10px 0; }
label { float: left; width: 100px; }
input { margin: 0 }
ul input[type="checkbox"]{ float:left; }
ul { list-style: none;}
li { margin: 10px 0; }
li div { margin-left: 20px; }
h2 { font: bold 14px Arial; margin-bottom: 5px; }
jQuery:
$(function(){
function logo(name, loc){
var locSize = loc.length;
return {
name: name,
loc: loc,
locSize: locSize
}
}
var logos = [];
$("#add").click(function(){
var name = $("#name").val();
var loc = [];
$("input[name='loc']:checked").each(function(){
loc.push($(this).val());
});
logos.push(logo(name, loc));
$("#results").children().remove();
$.each(logos, function(n){
$("#results").append("<li><input type='checkbox'/><div><h2>" + logos[n].name + "<h2/> Locations(" + logos[n].locSize + "): " + logos[n].loc.join(", ") + "<div/></li>");
});
});
$("#del").click(function(){
$("#results input[type='checkbox']:checked").each(function(){
var index = $(this).closest("li").index();
logos.splice(index, 1);
$(this).closest("li").remove();
});
});

Categories

Resources