samedi 25 juillet 2015

Passing checkbox values to database using javascipt

I find checkboxes a powerful tool but I have a hard time wrapping my head around them. I want customers to specify which kind of kitchen they like (fast food, italian, sushi, ..). Later I want to ask restaurants what kitchens they offer and based on the result I want to match customers and restaurants. I thought it would be nice to save all the choices in a kitchen array[]. Is that a good way to go about it or do you usually save each choice as an individual variable? My html looks like this:

<template name="hello">
    <form class="main form page">
    <div class="form-group">
      <label class="control-label" </label>
    <div class="checkbox">
      <label> <input  name="kitchen" type="checkbox" class="kitchen" id="italian"> italian</label>
    </div>
    <div class="checkbox">
      <label> <input name="kitchen" type="checkbox" class="kitchen" id="sushi"> sushi </label>
    </div>
    <div class="checkbox">
      <label><input name="kitchen" type="checkbox" class="kitchen" id="fastfood"> fast food </label>
    </div>
  </form>
</template>

The problem is that I don't know the most effective way in which to store the data in the mongo database.

I am working in meteor. So I have to create a template event:

Template.hello.events({
'submit form': function(e) {
e.preventDefault();

Now I need to get all the results to the database. Where kitchens is the variable that should be added to the Checkbox collection.

var kitchens = {
 fastfood: $(e.target).find('[name=fastfood]').val(),
 sushi: $(e.target).find('[name=sushi]').val(),
 italian: $(e.target).find('[name=italian]').val(),
};

kitchens._id = Checkbox.insert(kitchens);
console.log("added to database");

This code will send data to the database and an id is created but I can't see if the checkbox was checked or not. I found the below code to translate the check to a "Yes" or "No" but I don't know how to integrate this into my code:

function kitchensChecked(id) {
var X = document.getElementById(id);
if (X.checked == true) {
 X.value = "YES";
} else {
X.value = "NO";
};

Could you help me to integrate this code or show me a smoother way to save the checkbox results to the Checkbox collection?




Aucun commentaire:

Enregistrer un commentaire