0

I have a form with two text input fields and a series of checkboxes.

There is a variable fields which stores some arrays with data pertaining to the selected fields. I have hardcoded the values into the script with no problem but I cannot seem to find out how to properly compose an if statement to check the status of the checkboxes and only use those values, rather than hardcoding the selected fields.

var start, end, fields;

$(function() {
  $("#form1").submit(function(event) {
    var endD = $("#endDate").val();
    end = endD;
    var startD = $("#startDate").val();
    start = startD;

    //fields = ['PM1','PM2.5','PM10'];


    //if $("#PM1").is("checked"))){
    //fields = ["PM1"];
    //}


    if ($("PM1").attr("checked")) {
      fields = ["PM1"];
    }


    event.preventDefault();

    build_graph();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
  Start Datetime:<br>
  <input type="text" name="startDate" id="startDate" class="Date" placeholder="YYYYMMDD-HHMM"><br> End Datetime <br>
  <input type="text" name="startDate" id="endDate" class="Date" placeholder="YYYYMMDD-HHMM"><br> Parameter
  <br>
  <input type="checkbox" class="parameter" id="PM1">PM1<br>
  <input type="checkbox" class="parameter" id="PM2.5" checked>PM2.5<br>
  <input type="checkbox" class="parameter" id="PM10">PM10<br>
  <input type="checkbox" class="parameter" id="Temp">Temperature<br>
  <input type="checkbox" class="parameter" id="Humidity">Humidity<br>
  <input type="checkbox" class="parameter" id="Pressure">Pressure<br>
  <input type="checkbox" class="parameter" id="WindSpeed">Wind Speed<br>
  <input type="checkbox" class="parameter" id="Direction">Direction<br>
  <input type="checkbox" class="parameter" id="RainVolume">Rain Volume<br>
  <input type="submit">
</form>

3
  • 1
    A lot of us are developers, not literature gurus, So keep you commentary to a minimal and you may get a better response. -How does telling us about your work environment add to the situation? TLDR; Jun 28, 2017 at 17:48
  • The uncommented conditional statement is a missing a # in the selector
    – APAD1
    Jun 28, 2017 at 17:48
  • 1
    @SethMcClaine noted and will do in the future. Jun 28, 2017 at 17:54

2 Answers 2

3

You can select only the checked checkbox, using a JQuery selector :
$('.myCheckboxs:checked')

this will give you only the checked one.

10
  • And this would select all elements with the class "mycheckboxs" which were checked like you said? I'm going to try and work this out for a couple minutes and I'll return when I've something presentable. Thank you Jun 28, 2017 at 18:03
  • this will return each checkbox with the class myCheckboxs that are checked, if you don't want to use a class, you could always use this $('.theClassOfMyForm input[type="checkbox"]:checked)
    – Nicolas
    Jun 28, 2017 at 18:05
  • So two ways of going about this immediately come to mind. One to somehow pass each of those selected elements id's directly into the fields variable as an array. Two is to make an if statement with something that would loop through each and check if it was if it was checked with a modification of that selector in a much more clunky way. Jun 28, 2017 at 18:14
  • here i made a fiddle so you can understand my solution jsfiddle.net/dyomLqzz/5
    – Nicolas
    Jun 28, 2017 at 18:27
  • 1
    Thank you so much that makes so much more sense now. Jun 28, 2017 at 19:30
0

with jQuery you can properly check if a checkbox is checked like:

if($('#mycheckbox').prop("checked")){
  // it´s checked
}

my tip, use this function that serializes your form into an object

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

you can then serialize your form like this:

fields = $("#form1").serializeObject()

all input values and checkboxes that are checked will occur as property

4
  • This is probably exactly what I need to do but it is over my level of understanding as far as execution. I will try and get back to you after I do some reading and understand what all is going here and see if I can implement it properly. Jun 28, 2017 at 17:57
  • it is allready possible to serialize a form to JSON, api.jquery.com/serialize
    – Nicolas
    Jun 28, 2017 at 18:06
  • no by default it will create an URI-query-String instead of an object
    – john Smith
    Jun 28, 2017 at 18:20
  • @hotmaildotcom1 you´re welcome, it´s a little extension of jquery so you can call .serializeObject() on a jQuery object, it will basically turn all your form inputs and their values into a javascript object, the name attribute of the input is the key and the value is the value ;) (ideal to send to backend and avoid code repitition like you do )
    – john Smith
    Jun 28, 2017 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.