I have this function which works perfectly while I enter parameters, but it's not what I need, so given the code below, how can I use a user input value instead of the parameter to search through the array and return the objects?
Please keep it as simple as possible,I'm new to javaScript.
Please include input and button as html fields as well.
carSelection = [{
manufacturer: "Fiat Automobiles S.p.A.",
type: "Fiat 500",
fuel: "Eurosuper 98",
condition: "New",
enginePower: "101kW"
},
{
manufacturer: "Kia Motors Corporation (KMC)",
type: "Kia Sportage",
fuel: "Euro Diesel",
condition: "Used",
enginePower: "185kW"
},
{
manufacturer: "BMW AG",
type: "BMW X5",
fuel: "Euro Diesel",
condition: "Used",
enginePower: "195kW"
},
{
manufacturer: "Toyota Motor Corporation ",
type: "Toyota Corolla",
fuel: "Eurosuper 95",
condition: "Used",
enginePower: "165kW"
}
];
var bmw = 'BMW X5';
// var n1 = bmw.indexOf("bmw", 0);
var toyota = 'Toyota Corolla';
var fiat = 'Fiat 500';
var kia = 'Kia Sportage';
var input = document.getElementById("input").value;
function findCar(arr, searchProp) {
var rezArr = [];
for (var i = 0; i < arr.length; i++) {
Object.keys(arr[i]).forEach(function(prop) {
if (arr[i][prop] === searchProp) {
rezArr.push(arr[i]);
}
})
}
return rezArr;
}
var item2 = findCar(carSelection, bmw);
console.log(item2);
<input id="input" type="text"/>
Your input html looks fine to me. You should add a button which would look something like <button id="button">.
Now, You'll want to add a click event listener to the button. This is basically a function that will be called whenever the button is clicked. There's a couple ways of adding the event listener but I think the best is
const button = document.getElementById('button'); //get a reference to the button element
button.addEventListener('click', handleClick) // specify a function that should be called whenever the button is clicked
function handleClick(){
var input = document.getElementById("input").value;//get the current value of the input
findCar(carSelection, input) //find the car
}
So whenever the button is clicked, we'll go get the current value of input and pass that to the function you've already written.
The reason your current code won't work is that you grab the value of input as soon as the script loads when, more than likely, the user hasn't had time to type anything into it yet. So it will always be an empty string ("").
Related
So I have a series of various JSON objects representing a college class with nested data inside each of them. Each of these objects are stored in an array called classes. Here is an example of how one of the class objects is formatted:
let class_A = {
professor: "Joey Smith",
numberStudents: 25,
courseCode: "COMS 2360",
seating: {
"FirstRow": {
0: {
firstName: "Sarah",
collegeMajor: "English",
},
1: {
firstName: "Bob",
collegeMajor: "Computer Engineering",
},
2: {
firstName: "Dylan",
collegeMajor: "Mathematics",
}
},
"SecondRow": {
3: {
firstName: "Molly",
collegeMajor: "Music"
}
}
}
};
Basically, I have a page with all students across all class objects laid out on a page with an add button next to each name, and the add button will eventually allow me to add students to certain groups for assignments, etc.
The page right now with only class_A would looks something like this:
I displayed the student names and the add button next to each student using code like this:
function loadStudents(){
let page = document.getElementById('page');
page.innerHTML = "";
for(seatRow in class.seating){
for(index in class.seating[seatRow]){
let studentName = class.seating[seatRow][index].studentName;
page.innerHTML += "<p> Name:" + studentName + " <img src='addButImg.png' id = 'addButton' onclick = 'addStudentToGroup()'></p>";
let addButton = document.getElementById("addButton");
addButton.alt = studentName;
console.log(addButton.alt);
}
}
}
function addStudentToGroup(){
let addButton = document.getElementById("addButton");
console.log(addButton.alt);
}
My page displays correctly like the picture, but I'm having trouble printing the name of the specific student I add to a group when I click on the add button next to the student's name. I assign the add button's alt value to the student's name, and tested it by doing "console.log(addButton.alt)" which prints:
Sarah
Bob
Dylan
Molly
If I click on the first add button, it should trigger the addStudentToGroup() function and print "Sarah" to the console. However, clicking on all the buttons seems to only print the last name in the list of students which is "Molly" regardless of whichever student the button is located next to. The alt seems to get saved as whatever the last student is, and I'm struggling to change the alt value based on whatever student's name I choose to click add for. Does anyone know how to fix this? Any help would be appreciated!
You are assigning the same id addButton to all images.
If you just want studentName then just pass it in onclick function.
like using template literal addStudentToGroup('${studentName}')
let class_A = {professor:"Joey Smith",numberStudents:25,courseCode:"COMS 2360",seating:{"FirstRow":{0:{firstName:"Sarah",collegeMajor:"English",},1:{firstName:"Bob",collegeMajor:"Computer Engineering",},2:{firstName:"Dylan",collegeMajor:"Mathematics",}},"SecondRow":{3:{firstName:"Molly",collegeMajor:"Music"}}}};
loadStudents();
function loadStudents(){
let page = document.getElementById('page');
page.innerHTML = "";
for(seatRow in class_A.seating){
for(index in class_A.seating[seatRow]){
//console.log(class_A.seating[seatRow][index]);
let studentName = class_A.seating[seatRow][index].firstName;
page.innerHTML += `<p> Name: ${studentName} <img src="addButImg.png" onclick = "addStudentToGroup('${studentName}')"></p>`;
//let addButton = document.getElementById("addButton");
//addButton.alt = studentName;
// console.log(addButton.alt);
}
}
}
function addStudentToGroup(sname){
console.log(sname);
}
<div id="page">
</div>
The problem is that all of the buttons have the same id "addButton", so when you try to get the button in addStudentToGroup it retrieves the last item with matching id.
Try sending a reference to the button as argument to addStudentToGroup:
onclick = 'addStudentToGroup(this)'
Try the following:
let classes = [class_A, class_B, class_C, class_D];
let classesAvailable = document.getElementById('classes');
let class = classes[classesAvailable.value];
function loadStudents(){
let page = document.getElementById('page');
page.innerHTML = "";
for(seatRow in class.seating){
for(index in class.seating[seatRow]){
let studentName = class.seating[seatRow][index].studentName;
page.innerHTML += "<p> Name:" + studentName + " <img src='addButImg.png' id = 'addButton' onclick = 'addStudentToGroup(this)'></p>";
let addButton = document.getElementById("addButton");
addButton.alt = studentName;
console.log(addButton.alt);
}
}
}
function addStudentToGroup(buttonEl){
console.log(buttonEl.alt);
}
I create a function with name and id of m Select :
function loadDataFiltrosTipoFunc(Memory) {
var statusStoreMotivo = new Memory({
data: [
{ name: "Todos", id: 0 },
{ name: "Cobrança", id: 1 },
{ name: "Aniversariantes", id: 2 }
]
});
dijit.byId("pesqFuncMotivo").store = statusStoreMotivo;
dijit.byId("pesqFuncMotivo").set("value", TODOS);
};
When call to create new register, show me the options in the form.
My Problem is when call the "Edit", I have the id save in the registry, but I can not set the value name and show the other options to change in the Edit.
I made this : (There are comments in the code with my question more detail)
function EditarMensagem(itensSelecionados) {
try {
// first i check if any iten is selected (ItensSelecionados)
// If is ckeked and no has value show message ask to select only one
// else, if is selected only one and has value continue
if (!hasValue(itensSelecionados) || itensSelecionados.length == 0)
caixaDialogo(DIALOGO_AVISO, 'Selecione um registro para Editar.', null);
else if (itensSelecionados.length > 1)
caixaDialogo(DIALOGO_ERRO, 'Selecione apenas um registro para Editar.', null);
else {
// Here i Check the value of the select and put the name
// I don´t shure if is the best way
if (itensSelecionados[0].motivo = 0) {
var motivo = "Aniversariantes";
}
if (itensSelecionados[0].motivo = 1) {
var motivo = "Cobrança";
}
// Here in 'tipoSmsCompor' is my Select.
// I try put the var motivo,
// but don´t set the name, and don´t show the other options of the list
// declared in the function loadDataFiltrosTipoFunc(Memory)
// How I can set the current value and name in the select and the other option to the user can change?
dijit.byId( 'tipoSmsCompor' ).attr( 'value', itensSelecionados[0].motivo);
dijit.byId("dc_assunto").set("value", itensSelecionados[0].mensagem);
dijit.byId("cad").show();
IncluirAlterar(0, 'divAlterarMensagem', 'divIncluirMensagem', 'divExcluirMensagem', '', 'divCancelarMensagem', 'divClearMensagem');
}
} catch (e) {
postGerarLog(e);
}
}
How I can set the current value and name in the select and the other options to the user can change?
I want set the return value and show me the other option in the funcion loadDataFiltrosTipoFunc, but with the value returned .
Thanks all.
I am creating a text box programmatically, but the problem that I am facing is that when I am inserting it in an array as an object to be vied on top of a list, the allowed type is label. Hence when the text box is displayed, the program does not allow the text box for user input. Is there a way to fix this? I have already tried to change the type to text and I get undefined.
searchArray = [];
//creating the text box and placing it in a variable
var textBox = "<input type='text' placeholder='Search Client Code'>";
searchArray.push({label: textBox });
//diaplaying the text box in a context menu sub menu
return{
"Search" : {
label : "Search",
action: true,
"submenu": searchArray,
disabled: false
}
}
*****************************************************
UPDATE
var searchArray = [];
var textBox = "<input type='text' placeholder='Search Client Code'>";
textBox.push({label: something});
//this array is used to insert the textbox and also the clients afterwards
new_array = [];
new_array.push(searchArray[0]);
//the below push is used in a for loop that loops each client,
//so I am just putting it here just for reference
***
new_array.push(itemDisp[i]);
***
if(...){
var obj = {
"DuplicateFor" : {
label : "Duplicate for",
action: true,
"submenu": new_array,
disabled: false
}
}
document.body.innerHTML = obj['DuplicateFor']['submenu'][0].label
}
Try this. It will create the input successfully and it takes input as well
var searchArray = [];
//creating the text box and placing it in a variable
var textBox = "<input type='text' placeholder='Search Client Code'>";
searchArray.push({
label: textBox
});
//diaplaying the text box in a context menu sub menu
var obj = {
"Search": {
label: "Search",
action: true,
"submenu": searchArray,
disabled: false
}
}
console.log(obj)
document.body.innerHTML = obj['Search']['submenu'][0].label
I am trying to dynamically add an object with values from an input field to the end of an array using JavaScript. The only catch is that I'm trying to do it with an input field. Here's what I want to happen:
The user types in something in a text field
My program already adds a unique ID for it
Add it to the end of an array in the form of a object
Keep on adding objects to that array
This is what I want in my JSON file:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, {
"id": 1,
"description": "Task #2 Description"
}, {
"id": 3,
"description": "Task #3 Description"
}]
}
What I am currently getting is:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, ]
}
Every time I add a new Task, it replaces the one that is already there.
Here is my JavaScript code:
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.onclick = function() {
id = indentification++;
description = content.value;
var task = {
list: []
}
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
I would really appreciate it if anyone could help me out. I've spent hours trying to figure it out. Thanks!
The problem is here:
var task = {
list: []
}
task.list.push({id, description});
Each time you do this your list become empty then add new item.
change to this
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
var task = {
list: []
}
submit.onclick = function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8"); // what're you doing here, browser do not allow write file to disk
}
There are a couple of things that you need to consider here:
Form submit must be refreshing the page and resetting your global variables. Thus you need to prevent default action on click of submit.
(as mentioned in earlier answers) The list is being initiated on every click. You will need to initialize the variable task outside the onClick function
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
//initialize outside the on click function
var task = {
list: []
}
submit.onclick = function(e) {
//This prevents page refresh on form submission and preserves the global variable states
e.preventDefault();
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
This should hopefully solve your problem.
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.addEventHandler("click", function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
What I'm trying to achieve is the following. I'm (still) working on a timesheet, and the user has to be able to add a comment.
Comment [ .................. ] for D2
TaskID - Taskname - D1 - D2 - D3 ...
1 Hello 5 3 2
2 Bai 4 2 1
3 I'm back 3 4 3
When a user clicks on a specific textbox, where he has to fill in the hours, an additional textbox should get the comment value of that specific box. When he clicks on another textbox, it should get that value etc, etc.
I don't really know where to look for, or how I could do it best. Any ideas? Javascript? JQuery? I'm currently working with Spring MVC, so it should get the value and add it to a specific modelattribute so it can be submitted.
Another possibility is some kind of pop-up, which appears when you click on an icon next to the textbox...
I used Javascript to realize this.
Once you enter a certain field, I call a function to fill the commentary with a new classname:
<input type="text" onfocus='addComment(id, index, taskid)' />
Function:
function addComment(classname, commValue, taskid){
var comm = document.getElementById('comment');
var comment = document.getElementById(taskid + classname);
comm.className = taskid + classname;
comm.value = comment.value;
}
This will fill the textbox with the value from the latest focused textbox. It will also set the classname using the provided one.
To save the commentary value, I use jQuery Ajax:
function saveComment(){
var comment = document.getElementById('comment');
var classn = comment.className;
var firstday = document.getElementById('firstweek').value;
var commentval = comment.value;
var windex = comment.className.indexOf("w");
var day = comment.className.substring(windex+1, windex+2);
var taskid = comment.className.substring(0, windex);
var pid = document.getElementById('projectid').value;
if (classn != ""){
var commentSaved = document.getElementById(taskid+comment.className.substring(windex, windex+2));
commentSaved.value = commentval;
$.post("savecomm.html", { day: day, comment: commentval, taskid: taskid, firstday: firstday, pid: pid }, function(data) {
alert("callback");
});
} else {
alert("No entries selected");
}
}