In code.org, I'm trying to gather data from text boxes where they can enter numbers. I want to assign the numbers entered into the text boxes into different variables.
Right now, I am individually grabbing each variable by itself.
I am currently creating variables at the beginning of my code like this.
var player1 = "player1";
var player2 = "player2";
var player3 = "player3";
var player4 = "player4";
var player5 = "player5";
Then after I used the onEvent handler function, I grab each of the numbers individually using the getText function.
onEvent("team2Button", "click", function () {
player1 = getText("player1");
player2 = getText("player2");
player3 = getText("player3");
player4 = getText("player4");
player5 = getText("player5");
});
Since I have many around 30 sets of data to collect, is there a quicker way to assign these values into a variable?
You can use an Object:
const players = {};
for(let i = 1; i <= 30; i++) {
players[`player${i}`] = `player${i}`
}
onEvent('button', 'click', function(){
for(let key in players){
players[key] = getText(key)
}
})
You could use the "design" tab to create a text input, and then write some code to add a new entry to a list every time you type something in and press enter:
var players = [];
onEvent("text_input1", "change", function(event) {
var name = getText("text_input1");
appendItem(players, name);
setText("text_input1", '');
console.log("added player: " + name);
});
If you want to keep this text input separate from the rest of your app, you could put it on a different screen. For example: https://studio.code.org/projects/applab/3vINC-jX6LHkiARJCoCmUQ
Related
Have an array which is being compiled based on user input selection (checkbox and radio buttons)
This is being compiled using an input on change function.
The array is then used to check if values in the array match data attributes referenced within each card, and those which match, show the respective card.
This is working fine.
I am now trying to get the same functionality, but instead of being based on user input, the result is being compiled based on user query string (string is also compiled from the user input - effectively saving a query for using to return to page with results without having to enter the checkbox values again). This function has a lot of if true, push which I would like to re-use instead of re-write. I have simplified here.
Problem I am having is using the same function I built for show/hide the card based on user input with the query string.
// Set Globals:
var arr = []
function buildResults() {
// Build query based on input values and push into array:
$("input").on("change", function() {
var arr = [];
$(":checkbox").each(function() {
if ($(this).is(":checked")) {
arr.push($(this).val());
}
});
$(":radio").each(function() {
if ($(this).is(":checked")) {
arr.push($(this).val());
}
});
console.log(arr);
// Join array using unique string
var vals = arr.join("--");
// Set URL to pin query to and begin pushing values to string:
var urlBegin = "https://thisisatest/?results=";
var str = vals;
$("#val").text(urlBegin + vals);
$("#query").text(vals);
$("#copyTarget").val(urlBegin + vals);
userSelection = arr;
resRec();
});
}
buildResults();
function resRec() {
// Show div based on user checkbox values:
var user = userSelection;
var dataRec = [];
var recordResultCount = 0;
console.log(user);
var first = user.includes("123");
if (first == true) {
dataRec.push(123456);
}
var recordResults = [...new Set(dataRec)];
recordResultCount = recordResults.length;
console.log(recordResultCount);
// Show only the records needed:
$(".card").each(function() {
var recordFound = $.inArray($(this).data("recordid"), dataRec);
if (recordFound === -1) {
$(this).parent().addClass("destroy");
} else {
$(this).removeClass("destroy");
}
});
}
function resQuery() {
var urlQuery = window.location.href.match(/results=(.+)/)[1];
console.log(urlQuery);
user = urlQuery;
}
// If user enters page via unique query only, and not from page start:
$(function() {
if (window.location.pathname == "https://thisisatest/?results=") {
// reuse resRec() here, but using urlQuery and not userSelection;
var user = resQuery();
resRec();
// and show only the cards which match the results built from query
}
});
resQuery();
Function reuse is still new to me, and while I think my logic is on the correct path, I am still getting resRec() not defined.
Thank you.
I am trying to create a form which will generate different levels of forms based on the user input.
An example of this is
"How many levels are there?" -User input 3-
Three separate levels will be generated each with the same questions. In this there will be a question asking "How many objects are there?" the same will happen here in that multiple options will be generated.
Rough sketch of how the form would be displayed
The problem I've been having with this is allocating ids and then being able to fetch them after so that they can be referenced for use and MySQL later down the line.
function generateForm(){
var number = document.getElementById('number_of_levels').value;
var div = document.getElementById('levels');
// div.innerHTML += " " +number;
var heading = document.createElement("P");
heading.innerHTML = "Level " + number;
document.getElementById('levels').appendChild(heading);
var objects = document.createElement("P");
objects.innerHTML = "How many objects is the badge comprised of?";
document.getElementById('levels').appendChild(objects);
var num_objects_input = document.createElement("input");
num_objects_input.type = "number";
num_objects_input.id = "number_objects" +number;
document.getElementById('levels').appendChild(num_objects_input);
//num_objects.onchange = function(){addObject(num_objects.id)};
//div for the following levels
var ind_levels_div = document.createElement("div");
ind_levels_div.id = "level_" +number;
document.getElementById('levels').appendChild(ind_levels_div);
num_objects_input.onchange = function(){additionalObject()};
}
function additionalObject(){
var number = document.getElementById("number_objects" +number).value;
var objects_number = document.createElement("P");
objects_number.innerHTML = "Object " + number;
document.getElementById("level_" +number).appendChild(objects_number);
}
The result I'm getting is the form won't generate any Object form elements but will make the Levels.
Store all of the form objects in an array then convert the array to a more readable format..
var objectArray = [];
function createObject() {
var obj = document.createElement('div');
objectArray.push(obj);
obj.id = objectArray.length;
number = objectArray.length;
/* put your code here to append obj to the proper level etc*/
}
Now you can just convert the array when you want to send it to mysql
var sqlArray = JSON.Stringify(objectArray);
So, i have this code, it works:
var curp = document.getElementById("id_sc_field_curp_id_1");
var getcurp = curp.options[curp.selectedIndex].text;
var rfc = getcurp.substr(0, 10);
document.getElementById("id_sc_field_virtual_rfc_1").value = rfc;
It copy the text inside the field (td - CURP) "id_sc_field_curp_id_1", and trim it to put the result in another field (RFC) "id_sc_field_virtual_rfc_1"
Example img
JSFIDDLE: https://jsfiddle.net/90yzgcqe/1/
I want to adapt the code to work with the other rows, witch have an incremental id...
id_sc_field_curp_id_1,id_sc_field_curp_id_2,id_sc_field_curp_id_3, d_sc_field_virtual_rfc_1, d_sc_field_virtual_rfc_2, d_sc_field_virtual_rfc_3...etc
Im making this function, but... i dont know how to make it work...
function rfc() {
for (var i = 0; i <= 19; i++) {
var curp = document.getElementById("id_sc_field_curp_id_" + i);
var getcurp = curp.options[curp.selectedIndex].text;
var rfc = getcurp.substr(0, 10);
document.getElementById("id_sc_field_virtual_rfc_" + i).value = rfc;
}
}
What is wrong?
Some jQuery gets us there fairly easily, first get the matching dropdowns and then interact with them.
$(function() {
//get the list of dropdowns that start with all but the numeral
var lst = $("[id^='id_sc_field_curp_id_']");
$.each(lst, function(idx, elem) {
//lets store the dropdown for use in the loop
let $field = $(elem);
//for example lets print the selected text
console.log($field.find("option:selected").text());
});
});
There are a couple of options from there, you can use the dropdown to create the rfc's id, or use the jQuery function closest() to get it. Once you have the associated rfc's input it should be trivial to get set the value.
EDITED:1
More specific javascript, and a link to a modified jsFiddle
$(function() {
//get the list of dropdowns that start with all but the numeral
var lst = $("[id^='id_sc_field_curp_id_']");
$.each(lst, function(idx, elem) {
//lets store the dropdown for use in the loop
let $field = $(elem);
//for example lets alert the selected text
alert($field.find("option:selected").text().substr(0,10));
$field.closest("[id^='idVertRow']")
.find("[id^='id_sc_field_virtual_rfc_']")
.val($field.find("option:selected").text().substr(0,10));
});
});
I have a table in my database that I would like to be able to change some of the sections and keep the other functions as they were however it is updating the table so that the two are changed but the other 3 become empty. is there any way to change this?
$(function Tuesday(){
// CREATE A REFERENCE TO FIREBASE
var dateTuesdayRef = new Firebase('https://shiftsapp.firebaseio.com/roster');
// REGISTER DOM ELEMENTS
var date2Field = $('#date2Input');
var emp1put2Field = $('#emp1Input2');
var emp2put2Field = $('#emp2Input2');
var emp3put2Field = $('#emp3Input2');
var emp4put2Field = $('#emp4Input2');
var emp5put2Field = $('#emp5Input2');
var enter2Field = $('#enter2');
// LISTEN FOR KEYPRESS EVENT
enter2Field.keypress(function (e) {
if (e.keyCode == 13) {
//FIELD VALUES
var dateTuesday = date2Field.val();
var emp1put2 = emp1put2Field.val();
var emp2put2 = emp2put2Field.val();
var emp3put2 = emp3put2Field.val();
var emp4put2 = emp4put2Field.val();
var emp5put2 = emp5put2Field.val();
var enter2 = enter2Field.val();
//SAVE DATA TO FIREBASE AND EMPTY FIELD
var obj2 = {};
obj2[dateTuesday] = {
emp1:emp1put2,
emp2:emp2put2,
emp3:emp3put2,
emp4:emp4put2,
emp5:emp5put2
}
dateTuesdayRef.child(dateTuesday).set({emp1:emp1put2,
emp2:emp2put2,
emp3:emp3put2,
emp4:emp4put2,
emp5:emp5put2});
enter2Field.val('');
}
});
});
Get the values for the things you want to stay the same from your server, and feed them back when you set the object. You could also use a custom function to autofill undefined values like I have suggested.
From the table at the top of the Firebase guide on saving data:
set( ): Write or replace data to a defined path, like messages/users/
update( ): Update some of the keys for a defined path without replacing all of the data
So if you call update() instead of replace, it will only change the values of the properties you pass in and leave other values unmodified.
I am experementing with javascript objects for the first time and need some help. I want to store generated user input in objects, push them into an array and later on reuse them. So far I have come to this:
function changeColors() {
//get the numbers from the html
var rd = parseInt(document.getElementById("red").value);
var gr = parseInt(document.getElementById("green").value);
var bl = parseInt(document.getElementById("blue").value);
var op = parseFloat(document.getElementById("opacity").value);
//convert the decimal into hexadecimal
var rdhex = (rd < 16) ? "0" + rd.toString(16) : rd.toString(16);
var grhex = (gr < 16) ? "0" + gr.toString(16) : gr.toString(16);
var blhex = (bl < 16) ? "0" + bl.toString(16) : bl.toString(16);
//concatenate all hex to generate a color
var hexcode = "#" + rdhex + grhex + blhex;
//view the change in the browser
document.getElementById("div").style.backgroundColor = hexcode;
document.getElementById("colordisplay").innerHTML = hexcode;
//change opacity
document.getElementById("div").style.opacity = op;
Here I get all the input that I need to store and in the next function I am trying to store it in an object and array:
function Save(){
var colors = {};
var nextColor = []
colors.nextColor = nextColor;
console.log(colors);
var rgb = document.getElementById("colordisplay").innerHTML;
var opacity = document.getElementById("div").style.opacity;
var name = document.getElementById("name").value;
var nextColor = {
"name": name,
"rgb": rgb,
"opacity": opacity
}
colors.nextColor.push(nextColor);
console.log(colors);
}
My question is: is how wrong is that and how it can be corrected?
Thank you!
I am unsure what your question exactly is, but looking at your code for Save I assume you're inquiring how to best store data in the context of an application. Looking at the Save-method body:
var colors = {};
var nextColor = [];
These variables are only available in the scope of the Save function. As such the "colors"-Object will only ever contain one single color Object, i.e. the "nextColor" Object created in the Save function. On top of this, the "colors"-Object is not accessible outside of the Save function, rendering it... well, useless.
Ideally you hold the contents of the "colors"-Object in a global variable (or reference it in another Object available to your application, i.e. a "Model") and fill the colors Object with the return of the Save-method, i.e.:
function Save() {
var rgb = document.getElementById("colordisplay").innerHTML;
var opacity = document.getElementById("div").style.opacity;
var name = document.getElementById("name").value;
var nextColor = {
"name": name,
"rgb": rgb,
"opacity": opacity
};
return nextColor;
}
// assume an event handler invoked after a form is submitted, this
// creates a nextColor and pushes it into the existing colors Object
function someEventHandler( e ) {
colors.nextColor.push( Save() );
}
This implies that the Save-methods sole function is to gather the values entered in the HTML document, and translate it into a new value Object. The Save-method now has no business knowing about any remaining data belonging to your application. (i.e. the creation of the "colors" Object and its "nextColor"-Array should be left to another function, ideally executed when your application launches).
I guess what I'm saying is you're on the right track, but you can get a lot of mileage by investing some time into creating separate functions to handle your data layer. After all, that's all JSON is, data.
If for instance you want to enter validation in your Save()-method (let's say to make sure that the "name" Input element actually contains a valid String), you just modify it there in that one function. If you additionally wish to make sure that the same color isn't added to the "nextColor"-Array twice, you can make another function that checks whether a color with the same values is already present in the data Object and either removes it or prevents pushing the duplicate value into the Array. This is logic that shouldn't be in the Save()-method, as such you can structure your program to organize your data neatly.
I hope this is the answer you were looking for.
Try this:
var colors = {
"nextColor": []
};
function Save() {
colors.nextColor.push({
"name": document.getElementById("name").value,
"rgb": document.getElementById("colordisplay").innerHTML,
"opacity": document.getElementById("div").style.opacity
});
console.log(colors);
}
Notice that the colors variable should be outside the scope of the function in order to retain the variable beyond individual runs of the Save() function.
I've also simplified the code quite a bit.