select fields with Javascript object - javascript

I'm hoping to populate a select field with color options. So far I have this:
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
}
else if (x === "Banana") {
score = "B";
picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").image.src = picture;
}
<input type="text" id="text">
<img id="display" />
<select id="color"></color>
but I would like to populate a select field with color options, something like:
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
color = "Red" "Green" Blue";
}
Any ideas what format I need to use to add this?

Use an array of colors along with the function add:
.add(new Option(c, value));
var colors = ["Red", "Green", "Blue"];
var sel = document.getElementById('color');
colors.forEach((c, value/*This is the index of this loop*/) => sel.add(new Option(c, value)));
<select id="color"></select>

After
if(x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
colors = ["Red", "Green", Blue"];
}
use the reduce method to generate a string of options and assign it to the inner html of color select-box.
document.getElementById("color").innerHTML = color.map((color) => '<option value="' + color+ '">' +color +'</option>').join();
http://jsbin.com/kuyazekivu/edit?html,js,console,output

Related

Input value is not changed on Javascript

I make shopping Cart now with vanilla javascript, html, css.
This program is when consumer click selection tag, add new tag and change count.
To Add new Tag is already working. Change count is not work. When I clicked, selectA, selectB, selectC is changed but not working on input tag.
var selectA = 0;
var selectB = 0;
var selectC = 0;
function handleOnChange(e) {
// 선택된 데이터 가져오기
let value = e.value;
let name = e.options[e.selectedIndex].text;
let itemList = document.getElementById("addItem");
var Item = document.createElement('div');
var itemName = document.createElement('div');
var itemSumA = document.createElement('input');
var itemSumB = document.createElement('input');
var itemSumC = document.createElement('input');
itemName.innerHTML = name;
if (value === "A") {
if (selectA === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumA);
itemList.appendChild(Item);
}
itemSumA.value = selectA;
} else if (value === "B") {
console.log(selectB);
if (selectB === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumB);
itemList.appendChild(Item);
}
itemSumB.value = ++selectB;
} else {
if (selectC === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumC);
itemList.appendChild(Item);
}
itemSumC.value = ++selectC;
}
document.getElementById("Sum").innerHTML = selectA * 39800 + selectB * 49800 + selectC * 59800;
}
<li class="checked">
<button class="accordion">주문 정보</button>
<div class="panel">
<p>상품 선택</p>
<select name="tent" id="tent" onchange="handleOnChange(this)">
<option value="A">A. 스피드 원터치 팝업텐트(3~4인용)</option>
<option value="B">B. 5초 원터치 텐트(3인용) (+10,000)</option>
<option value="C">C. 5초 원터치 텐트(5인용) (+20,000)</option>
</select>
<div id="addItem"></div>
</div>
</li>
I want to know why.

Appending and removing URL parameters based on checkboxes

I have some filters that are being displayed as checkboxes on my website. Each time someone checks or unchecks one of these inputs I either want to add or remove the filter to/from the URL. I have this mostly working, but the problem comes when removing the last filter in the list.
Here's an example:
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
$(function () {
var colors = getUrlParameter('colors');
var currentUrl = location.href;
$('input[type="checkbox"]').change(function () {
var inputVal = $(this).val();
if (this.checked) {
// Add filter to URL params
colors = getUrlParameter('colors');
if (!colors) {
// No filters exist yet
currentUrl += '?colors=' + inputVal;
} else {
// At least one filter exists
currentUrl += ',' + inputVal;
}
console.log(currentUrl);
window.history.pushState("object or string", "Title", currentUrl);
} else {
// Remove filter from URL params
currentUrl = currentUrl.replace(inputVal + ',', '');
console.log(currentUrl);
window.history.pushState("object or string", "Title", currentUrl);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filters">
<label><input type="checkbox" value="blue" />Blue</label>
<label><input type="checkbox" value="red" />Red</label>
<label><input type="checkbox" value="green" />Green</label>
</div>
This works if the color is first(if there or other filters) or in the middle of the list of filters, since it matches my replace(), wondering how I can do this dynamically so that it will remove both the color and the comma if necessary or remove the colors= altogether if none are checked.
For example, if all 3 colors are checked the url would look like this:
http://example.net?colors=blue,red,green
If you then remove blue it should look like this:
http://example.net?colors=red,green
If you then remove green it would look like this:
http://example.net?colors=red
And finally, removing red would look like this:
http://example.net
You'll want to split your colors into an array and then merge it back again at the end.
$(function () {
var colors = getUrlParameter('colors');
var currentUrl = location.href;
$('input[type="checkbox"]').change(function () {
var inputVal = $(this).val();
var colorsQuery = getUrlParameter('colors') || "";
//Split into an array after each `,`
colors = colors.split(",");
if (this.checked) {
//Add to our current colors
colors.push(inputVal);
} else {
// Remove from our current colors
const index = colors.indexOf(inputValue);
colors.splice(index, 1);
}
colorString = "";
if(colors.length){
//Merge back into a string with a `,`
colorString = "?colors=" + colors.join(",")
}
window.history.pushState("object or string", "Title", currentUrl + colorString);
});
});
It's much easier to work with arrays in this instance so we just split and join to convert to and from an string to array.
For adding its easy we can just push onto our array
To remove a color we find out where it is in our colors array. Then using splice remove it from our array.
I'd seperate adding and removing objects, and the logic to get your querystring.
You'll see here two basic events:
Update an object based on the current checkbox (Binding directly to the state is even better!)
Generating the string based off of current values.
var colors = {
'red': false,
'blue': false,
'green': false
};
update = function(color) {
colors[color] = !colors[color];
}
getParams = function() {
var setQuery = false;
var expr = [];
for (var color in colors) {
if (colors[color]) {
expr.push(color);
setQuery = true;
}
}
if (setQuery) {
console.log("www.example.com" + "?colors=" + expr.join(","));
} else {
console.log("www.example.com");
}
}
<input type="checkbox" onchange="update('red')" /> Red
<input type="checkbox" onchange="update('blue')" /> Blue
<input type="checkbox" onchange="update('green')" /> green
<button type="button" onclick="getParams()">Get params</button>

Abstraction with "this" variable

I am making a crossword puzzle. Here is one example of one box of the crossword:
<div class="grid-item">M
<input id="input-item24" type = "text" size= "4">
</div>
<div class="grid-item-black"></div>
</div>
<button id='total_score'>Click to see score</button>
<div id='display_score'></div>
Here is the script for each box:
<script
src="https://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<script>
var answers = [];
answers[2]= 'M';
answers[3]= 'E';
answers[4]='A';
answers[5]= 'L';
answers[6]= 'B';
answers[7]= 'E';
answers[8]='L';
answers[9]= 'L';
answers[10]= 'A';
answers[11]= 'I';
answers[12]= 'L';
answers[13]= 'I';
answers[14]= 'A';
answers[15]= 'D';
answers[16]= 'R';
answers[17]= 'E';
answers[18]= 'T';
answers[19]= 'R';
answers[20]= 'Y';
answers[21]= 'D';
answers[22]= 'E';
answers[23]= 'E';
answers[24]= 'M';
var score = 0;
var total = 0;
I want to abstract (condense it) the calculate function by using the "THIS variable" to calculate the score. This way, I won't have to repeat this code (which works) for every box:
$('#total_score').on('click',calculate);
function calculate(){
if($('#input-item21').val()==answers[21]){total = total +1;}
$('#display_score').html(total);
};
So far I have tried this, why won't it work?
$('.grid-item').on('click',calculate);
function calculate (){
if($(this).html() == '')
{
$(this).html(answers);
if(answers == '#input-item')
{score = score + 1;};
}
$('#display_score').html(score);}
};
You should just need to reference the value and id, like this (i would also make it a blur event so that the calculation occurs after the user enters info in the square):
$('.grid-item').on('blur',calculate);
function calculate (){
let input = $(this)[0]
if(input.value || input.value !== '') {
let id = /\d+$/.match(input.id)[0];
if(id && answers[id] === input.value) {
score++;
}
$('#display_score').html(score);
}
};
You can also pass the event target to your calculate function, such as below. I would consider further simplifying things by changing the input ids to just numbers (e.g. #input_item24 to just 24) and then using that to check the answers array by passing the click target to the calculate function:
$('.grid-item').on('blur', e => { calculate(e.target) });
function calculate (input){
if(input.value || input.value !== '') {
if(answers[Number(input.id)] === input.value) {
score++;
}
$('#display_score').html(score);
}
};

Changing the color of text with Javascript

I'm trying to make a program where I use a function to change the color of pre-written text using an array and a for loop, depending on what the user inputs when prompted. Here is my code:
// <Student Name> <Student ID> comment must be here.
// This function will change the color of the text to the name of the color you give it.
function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}
// Declare, create, and put values into your color array here
var colors = new Array(5);
colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";
// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
for (var i = 1; i <= 4; i++) {
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
changeColor(colors[colNumber]);
} else {
changeColor("black");
}
}
<html>
<head>
<title>Lab 7 Task 2</title>
</head>
<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>
<h1>
</h1>
</body>
</html>
What happens is the text will only show once I've done all of the prompts. It shows the proper color and text and everything, but at the start the "The color is black." doesn't show up, and nothing does until the last prompt is answered.
Note that this is for a beginner class so anything much more advanced than what I have here won't be of much help. I did not write the function, it is there as part of the assignment. I've been at this for hours and can't figure out the issue!
Use SetInterval for this.
check the following code snippet
function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}
// Declare, create, and put values into your color array here
var colors = new Array(5);
colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";
// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
var x = 0;
var intervalId = setInterval(function() {
if (x == 4) {
clearInterval(intervalId);
}
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
setTimeout(changeColor(colors[colNumber]), 1000);
} else {
changeColor("black");
}
x++;
}, 100);
<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>
<h1>
</h1>
</body>
Hope this helps

button checking a checkbox using javascript

I am trying to make a button that will toggle between three colors: black, green, and red and will either check a certain box depending on the color. Right now I can make the color toggle but I can't make the check boxes check. I would appreciate the help. I am a beginner (obviously).
Button color green: check box 1
Button color red: check box 2
Button color black: do not check either box 1 or 2
The script looks like:
<script>
var colors = ["green", "red", "black"]
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
}
</script>
The HTML looks like:
<html>
<button onclick="setColor(this)">This is my Button</button>
<input type="checkbox" name="box1" id="box1" />
<input type="checkbox" name="box2" id="box2" />
</html>
Thanks!
I'd suggest:
var colors = ["green", "red", "black"];
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
document.getElementById('box1').checked = el.style.color == 'green';
document.getElementById('box2').checked = el.style.color == 'red';
}
JS Fiddle demo.
Do it like this:
var index = el.colorIdx++ % colors.length;
if( index == 2 ) //2 is the index of color black
{
document.getElementById("box1").checked = false;
document.getElementById("box2").checked = false;
}
else if( index == 0 )
{
document.getElementById("box1").checked = true;
}
else
{
document.getElementById("box2").checked = true;
}

Categories

Resources