mercredi 27 décembre 2017

Saving checkbox text value to an array

I've been trying to figure out a good solution all day and believe I'm getting close, but I can't figure out the final solution. What I'm trying to do is save the selected (only the selected) text values of checkboxes into an array so I can eventually save it to a database. Now I'm able to do it if I do the following:

yourArray.push($('label[for=checkbox3]').text());

However, I want to avoid using specific 'for=checkbox3' and just automatically get the text value for those selected checkboxes. Once I have it working properly I'll be saving the array content into local storage. Any help is appreciated.

HTML:

<form role="form" action="" class="margin-top-fortypx">
   <div class="checkbox checkbox-container">
      <label class="checkbox-label" for="checkbox1">
         <input type="checkbox" id="checkbox1" name="type" class="remove-bootstrap checkbox-circle margin-right checkbox-js" value="true" />
          Option #1
       </label>
    </div>

    <div class="checkbox checkbox-container">
       <label class="checkbox-label" for="checkbox2">
          <input type="checkbox" id="checkbox2" name="type" class="remove-bootstrap checkbox-circle margin-right checkbox-js" value="true" />
           Option #2
        </label>
     </div> 
  </form>

Javascript:

function jobType() {

  // Not trying to do this for the 6+ checkboxes
  // var text = $('label[for=checkbox1]').text();
  // var textt = $('label[for=checkbox2]').text();
  // var texttt = $('label[for=checkbox3]').text();
  var yourArray = [];

  $("input:checkbox[name=type]:checked").each(function() {
    yourArray.push($('label[for=checkbox3]').text());
  });

  alert(yourArray);

  localStorage.setItem('jobs-selected', text);
  var job = localStorage.getItem("jobs-selected");

}

Image of current checkbox form:

enter image description here

My goal is this: yourArray = [Option #1, Option #2, Option#4, Option #8] depending on random selection from the user.

I hope I explained it well enough for what I'm trying to do.




Aucun commentaire:

Enregistrer un commentaire