jeudi 15 décembre 2022

Checking if the user selected the correct checkbox

I´m making a quiz with javascript and I have encountered a problem with getting the answer from chosen checkbox. I have gotten the checkboxes to work so that you can only pick one answer. Reason for using checkboxes is just that I tried to use radioboxes and I didn´t get it to work that way either.

Currently my form looks like this:

    <div id="vastausformi">
        <form id="vastaukset"> 

            <label for="a">A)</label>
<input type="checkbox" classname="box" id="Check1" value="Value1" onclick="selectOnlyThis(this.id)" />  
    
            <label for="b">B)</label>
  <input type="checkbox" classname="box" id="Check2" value="Value1" onclick="selectOnlyThis(this.id)" />  
             
            <label for="c">C)</label>
<input type="checkbox" classname="box"  id="Check3" value="Value1" onclick="selectOnlyThis(this.id)" />   

            <label for="d">D)</label>
<input type="checkbox" classname="box" id="Check4" value="Value1" onclick="selectOnlyThis(this.id)" /> 
        </form>
    </div>

Then i have javascript for a question:

let questions= {

  question: "Which city is the capital of Sweden?",
  vastaus:{
      a: 'Stockholm',
      b: 'Malmö',
      c: 'Göteborg',
      d: 'Helsingborg'
  },
  correctAnswer: 'a'
};

Then I have made a function that checks the users guess.

  function checkGuess(){
    let correctAnswer= questions.valueOf(oikeaVastaus);
    let playerChoice= document.getElementsByClassName("box");
    
    if(playerChoice===correctAnswer){
      console.log("correct");
    }

    else{
      console.log("wrong");
    }

   
  };
    
guessSubmit.addEventListener('click', checkGuess);

The checkGuess function doesn´t seem to get the "answer". I get it so that it says that the answer is correct (no matter which checkbox you choose) or that all the answers are wrong. I have tried to "retrieve" the information from the checkboxes with different ways with no luck. I can´t seem to get hold of that "correctAnswer". I have also tried to make one specific checkbox "the correct choice", so that everytime you choose it, it would be correct, but that doesn´t work either. So that checkGuess function is just one of the ways I have tried to do the checking. I have also tried to leave away the declaration of playerChoice and put the input straight to the if statement. I have also tried to

Reason to use those consolelogs are just the see if the script works, so in the future the answer will be displayed on screen and there will be more questions than just one. I´m new to coding so I might be doing this compeletely wrong, but I wanted to make it so that one question appears and then there is four checkboxes to choose from, then there will be a button to get to next question.

I apologize for my english, but hopefully you will understand what I mean.

If anyone has any idea how to get this to work or have some alternative ways to do this, I would greatly appreciate it!




unchek checkbox with another button in react js

I'm learning Reactjs and trying to make my own multiple checkbox like the existing multiple checkbox packages, but I'm confused at the final stage to make the checkbox unchecked when I press the checkbox indicator button,

enter image description here enter image description here

const ListProduct = () => {

    // Checkbox Handle
    const [checked, setChecked] = useState([]);

    // Add/Remove checked item from list
    const handleCheck = (event) => {
        var updatedList = [...checked];
        if (event.target.checked) {
        updatedList = [...checked, event.target.value];
        } else {
        updatedList.splice(checked.indexOf(event.target.value), 1);
        }
        setChecked(updatedList);
        
    };

    // Generate string of checked items
    const renderFilters  = () => {
        return checked.map((item) => {
            if (item.length >= 1){
                return (
                        <Badge className="filter-list-indikator" bg="secondary" key={item} onClick={handleCheck}>
                            {item}
                        </Badge>
                );
            } else {
                return null
            }
        })
    }

 
<div className="d-flex" key={1}>
      <input type="checkbox" onChange={handleCheck} value="3 Seater"/>
      <label>3 Seater</label>
</div>



mardi 13 décembre 2022

how to bind checkboxes with angular in reactive forms

Actually I made an dummy project on health care so in that i made a component having Test Services in that I made a Radio Button ,On the click of radio Specific data goes to dropdown which is Services , and on the click on specific service i need sub services in check boxes and thn on the click of submit i need that goes to json server

I tried i made every thing radio dependent dropdown n checkboxes too but , when i check with the debugger it fetch the target value in check box only true no value , so i need value in checkboxes

In this image i bind the data fro ts to html and applying the for loop [In this ts file i call the change event with tha event.target.value here in change service i get the value but when i see with debugger its empty string only

the test service with the subservice data the html file here i made custom checkboxes and binf them with subServiices

the ts file here i create the change event with the help of that i get my target id

the test service here i made the json data so that i can fetch that

the issue which i facing that i don't get the value of subservice in the request of post




How to store a checkbox value as array in mongoDB with mongoose

I would like to store checkbox a value as array in mongoDB, using mongoose schema. I can get the values in array if I check more than 2 boxes. But as string when I check only one.

The following is for the checkbox in form in ejs file

<div class="mb-3">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Culture" value="Culture" name="place[categories]">
      <label class="form-check-label" for="Culture">Culture</label>
   </div>
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Sport" value="Sport"  name="place[categories]">
      <label class="form-check-label" for="Sport">Sport</label>
   </div>
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Nature" value="Nature"  name="place[categories]">
      <label class="form-check-label" for="Nature">Nature</label>
   </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Education" value="Education"  name="place[categories]">
      <label class="form-check-label" for="Education">Education</label>
   </div>
</div>

This is mongoose Schema

const mongoose = require("mongoose");

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [String],
    location: String,
    description: String
})

This is backend with express, for your info.

app.get("/places/new", (req, res) => {
    res.render("places/new.ejs");
});

app.post("/places", async(req, res) => {
    const place = new Place(req.body.place);
    await place.save();
    res.redirect("/places");
});

Thank you for reading and I hope I could find solution.

I tried to change the schema design as following, but doesn't go well.

const categorySchema = new mongoose.Schema({ name: String });

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [categorySchema],
    location: String, 
    description: String,
    image: String,
})



lundi 12 décembre 2022

How to convert input field value into checkbox using javascript

I have been trying to create a To-Do list using HTML, CSS and Javascript. From what I found, I am able to get the value of the input field into a fieldset. However, I aim to create a way to convert the input field value from the textfield into the checkbox field.

Please find the codes below for my test project:

// Getting the Add Task button:
var add_task = document.getElementById('TaskAdd');

// Listen for the add task click on button:
add_task.addEventListener('click', addtask);

//// Creating functions:
// Adding task into the list:
function addtask()
{
    // Converting the input to task list:
    var task = document.getElementById("Taskname").value;
//    document.getElementById("Do1").innerHTML = task;
    
    var taskcheck = document.createElement("INPUT");
    taskcheck.setAttribute("TaskCheck", "checkbox");
//    document.getElementById("Do1").innerHTML = taskcheck;
    document.getElementById("TaskCheck").innerHTML = task;
    document.getElementById("Do1").innerHTML = taskcheck;

    
};
body
{
    /* The image used */
     background-image: linear-gradient(blue, red);
     object-fit: cover;

    /* Full height */
    height: auto;
    width: 100%;

    /* Center and scale the image nicely */
    background-position: center;
    background-size: cover;
    /*background-repeat: no-repeat;*/
}

.center
{
    text-align: center;
    background-color: aquamarine;
}

.background-cover
{
    background-color: aquamarine;
    background-image: url("images/Custom Background(7).jpg");
    background-size: cover;
    background-repeat: no-repeat;
    height: 400px;
    width: 1520px;
}

.background-cover-2
{
    background-color: aquamarine;
    background-size: cover;
    background-repeat: no-repeat;
    font-weight: bold;
}

.background-cover-3
{
    background-color: aquamarine;
    background-size: cover;
    background-repeat: no-repeat;
}

.container
{
    text-align: center;
}

.fieldset2 {
   margin:2px;
   padding:0px;
}
<html>
    <head>
        <title>To-Do List Project</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <!-- Title of the project -->
        <h1 class="center"> To-Do List Program </h1>
        <!-- Creating the background of the cover -->
        <div class="background-cover"></div>
            <!-- Creating container to present the Inputfield to add task for the To-Do list -->
            <div class="container">
                <h1 class="center"> Enter text into the input field to add items into your list </h1>
                <h1 class="center"> Click on the item to mark that the task are complete </h1>
                <h1 class="center"> Click on X to remove the task from To-Do List </h1>
                <input type="text" id="Taskname" name="Tname" placeholder="Input task" size="14">
                <button type="button" id="TaskAdd" onclick="addtask();"> Add </button>
                
                <!-- Creating fieldset to locate the tasks into two sections, first section is the To-Do list -->
                <fieldset class="background-cover-3">
                    <legend class="background-cover-2"> To-Do: </legend>
                    <ul id="Do1" style="list-style: none;">
                        <li>
                        </li>
                    </ul>
                </fieldset>

                <!-- Creating fieldset to locate the tasks into two sections, Second section is the Completed list -->
                <fieldset class="background-cover-3 fieldset2">
                    <legend class="background-cover-2 fieldset2"> Completed: </legend>
                    <ul id="Com1" style="list-style: none;">
                        <li>
                        </li>
                    </ul>
                </fieldset>
                
            </div>
    <script src="main.js"></script>
    </body>
</html>

So, How would I be able to get the input value from the textfield and convert it into checkbox?




JavaFX checkbox style does not apply

I have the following problem. I am trying to style a checkbox in JavaFX. The style is stored in a .css file and is added via getStylesheets().add() when the component is created.

The problem is that the style is only displayed correctly if it is defined twice. If the style is defined only once, the style is not applied.

.check-box>.box {
  -fx-background-color: white;
  -fx-border-color: blue;
  -fx-border-width: 1;
  -fx-border-radius: 4;
}

This doesnt work.

.check-box>.box {
  -fx-background-color: white;
  -fx-border-color: blue;
  -fx-border-width: 1;
  -fx-border-radius: 4;
}

.check-box>.box {
  -fx-background-color: white;
  -fx-border-color: blue;
  -fx-border-width: 1;
  -fx-border-radius: 4;
}

This works.

Does anyone know whats the problem here?




i want to select multiple items

this is my code 


class HighestEducation extends StatefulWidget {
  const HighestEducation({Key? key}) : super(key: key);

  @override
  State<HighestEducation> createState() => _HighestEducationState();
}

class _HighestEducationState extends State<HighestEducation> {
  int selectedPosition = -1;
  late Future<List<Region>> qualification;

  Region? selEdu;
  TextEditingController highestEducation = TextEditingController();

  NetWorkOperations ntop = NetWorkOperations();
  var education = [];
  final List<Region> _selEdu = [];
//List<bool> _checkBoxValues = [];
//bool x = false;

  @override
  void initState() {
    super.initState();

    qualification = ntop.getDropDownList(0, 5);
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
        shrinkWrap: true,
        scrollDirection: Axis.vertical,
        physics: const BouncingScrollPhysics(),
        children: [
          const AppText(
              text: 'HighestEducation', fontSize: 18, color: profileConnect1),
          12.hBox,
          Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: FutureBuilder<List<Region>>(
                  future: qualification,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      int length = snapshot.data!.length;

                      for (int i = 0; i < length; i++) {
                        Region edu = snapshot.data![i];
                        education.add(edu.value);
                      }
                   
                    return AppTextField(
                          suffixIcon: inputArrowDownIcon,
                          hint: 'M.Com',
                          controller: highestEducation,
                          enabledBorder: true,
                          suffixColor: captionInterest,
                          onTap: () => showOptionPicker(context,
                                  itemBuilder: (_, int index) {
                                if (education.length > 0) {
                                  return Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 20.0),
                                    child: Center(
                                        child: AppText(
                                            fontSize: 15,
                                            text: education[index])),

                                      );
                                } else {
                                  return const Center(
                                    child: CircularProgressIndicator(),
                                  );
                                }
                              }, onDonePressed: (int selectedIndex) {
                                setState(() {
                                  highestEducation.text =
                                      education[selectedIndex];
                                });
                              }, itemCount: education.length));
                    } else if (snapshot.hasError) {
                      return Text('${snapshot.error}');
                    }
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  }))
        ]);
  }
}

i am new to flutter and i dont know how to implement multiselection in my code using checkbox,here i am using an api to get data and i name it as "education" and i access the educationlevels from this api, i have to keep future builder and the logic what i used in my code, here i am using apptextfield as a customizes textfield , please help me to solve my issue,