0

I'm trying to make a joke generator. The user can choose between Programming, Miscellaneous and Dark jokes (or two / all of them but cannot choose none). Right now, for my Javascript and HTML, I have this:

$("#first-input").val("Programming");
  $("#middle-input").val("Miscellaneous");
  $("#bottom-input").val("Dark");

  let checkboxes = $(".content-top input[type=checkbox]");
  let submitButton = $("button[type=submit]");
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Joke</title>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>
        <form action="/joke" method="POST">
            <div class="section">
                <label><span>*</span> Select a category / categories:</label>
                <div class="content content-top">
                    <input type="checkbox" name="category" id="first-input">
                    <h5>Programming</h5>
                    <br>
                    <input type="checkbox" name="category" id="middle-input">
                    <h5>Miscellaneous</h5>
                    <br>
                    <input type="checkbox" name="category" id="bottom-input">
                    <h5>Dark Jokes</h5>
                </div>
            </div>
            <button type="submit">Generate Joke</button>
        </form>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>

</html>

The HTML I have right now are three checkboxes with the same name attribute, but with different values set (values were set in Javascript above). How do I use jQuery to make it so that once the submit button is clicked, there is an array, and the items in the array are the ones the user checked?
So for example: If the user selects the "Programming", "Miscellaneous" and "Dark" check boxes, the array would have the 3 items (the three items would be "Programming", "Miscellaneous" and "Dark"). Then if the user proceeds to uncheck the "Dark" checkbox (so now only the "Programming" and "Miscellaneous" checkboxes are checked), the array would also remove the "Dark" item and would now only have 2 items.

I've been trying a lot of things and searching on Google, and tried using "input:checked", is(), etc. but I couldn't figure out how to get it to work.

Question: How do I get an array, and the items in the array are the values of the checkboxes the user checked (e.g. "Programming", "Dark", etc.) with no repeats, and if the user, for example, initially selected all three checkboxes, and then proceeds to uncheck the "Dark" checkbox, the array should also remove "Dark" as one of it's items.

I've been stuck on this for hours and would really appreciate any help, thanks!

3
  • $('input:checked') Commented Aug 2, 2020 at 2:35
  • You have jQuery not actual Javascript. Commented Aug 2, 2020 at 3:36
  • jQuery is JavaScript last I checked. Both tags make sense here. Commented Aug 2, 2020 at 20:01

3 Answers 3

1

First, change your checkboxes to declare their values in the HTML:

<input type="checkbox" name="category" id="first-input" value="programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="dark">
<h5>Dark Jokes</h5>

Add the following onclick attribute to your submit button:

<button type="submit" onclick="submit(event)">Generate Joke</button>

Then add the following script tag after your inclusion of jQuery:

<script type="text/javascript">
  window.submit = event => {
    event.preventDefault();

    let checkedValues = Array.from($('input:checked')).map(input => input.value);
    // ... looks like, e.g., ["programming", "miscellaneous"]

    // ... do stuff with checkedValues here...
    console.log(checkedValues);
  };
</script>

I added the event.preventDefault() thing so that the form doesn't actually send anything to the server. It seems like you'll need that if you want to do things in JS first.

The whole thing should look like this:

<form id="form" action="/joke" method="POST">
      <div class="section">
          <label><span>*</span> Select a category / categories:</label>
          <div class="content content-top">
<input type="checkbox" name="category" id="first-input" value="programming">
<h5>Programming</h5>
<br>
<input type="checkbox" name="category" id="middle-input" value="miscellaneous">
<h5>Miscellaneous</h5>
<br>
<input type="checkbox" name="category" id="bottom-input" value="dark">
<h5>Dark Jokes</h5>
          </div>
      </div>
      <button type="submit" onclick="submit(event)">Generate Joke</button>
  </form>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  <script type="text/javascript">
    window.submit = event => {
      event.preventDefault();

      let checkedValues = Array.from($('input:checked')).map(input => input.value);
      // ... looks like, e.g., ["programming", "miscellaneous"]

      // ... do stuff with checkedValues here...
      console.log(checkedValues);
    };
  </script>

I don't think you need those few lines of JS at the top of your question.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this really helped out!
1

Add the value attribute to your inputs then get all checkboxes iterate through them then push the values to the array, the elements in the array will be removed each time you click submit which means you will always get the new values checked by the user pushed to the result array

  results = []
  let submitButton = $("button[type=submit]");
  submitButton.click(function(e) {
   var $checkboxes = $('input[name=category]:checked');
   e.preventDefault()
   results.splice(0,results.length)
   $checkboxes.each(function(){
      results.push($(this).val())
 });
 console.log(results)
});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Joke</title>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>
        <form action="/joke" method="POST">
            <div class="section">
                <label><span>*</span> Select a category / categories:</label>
                <div class="content content-top" id="checkb">
                    <input type="checkbox" name="category" id="first-input" value="Programming">
                    <h5>Programming</h5>
                    <br>
                    <input type="checkbox" name="category" id="middle-input" value="Miscellaneous">
                    <h5>Miscellaneous</h5>
                    <br>
                    <input type="checkbox" name="category" id="bottom-input" value="Dark Jokes">
                    <h5>Dark Jokes</h5>
                </div>
            </div>
            <button type="submit">Generate Joke</button>
        </form>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>

</html>

1 Comment

I see what went wrong, thank you so much for the explanation, really appreciate it!
1

I don't do jQuery for years, but if you want to sent an array you have to ending element's names with [] and set a value for each.

here it is in javascript

const DomParser = new DOMParser()
  ,   myForm = document.getElementById('my-form')
  ;
function newCategory(val)
  {
  let elm = `<input type="hidden" name="category[]" value="${val}">`
  return DomParser.parseFromString( elm, 'text/html').body.firstChild
  }
myForm.oninput=()=>
  {
  while (el=myForm.querySelector('input[name="category[]"]')) el.remove();
  myForm.querySelectorAll('input[data-category]:checked').forEach(el=>
    {
    myForm.appendChild( newCategory( el.dataset.category ) )
    })
  }
label, button {
  display: block;
  float: left;
  clear: both;
}
button { margin-top: 1em;}
<form id="my-form" action="/joke" method="POST">
  
  <label>
    <input type="checkbox" data-category="Programming">
    Programming
  </label>

  <label>
    <input type="checkbox" data-category="Miscellaneous">
    Miscellaneous
  </label>

  <label>
    <input type="checkbox" data-category="Dark Jokes">
    Dark Jokes
  </label>

  <button type="submit">Generate Joke</button>
</form>

3 Comments

I didn't know that the names had to end with "[]". Really appreciate the explanation, thank you!
I think that's to send an array to the server. But it looks like you intercept the form submission anyway, so... you may not need the brackets.
@weltschmerz anyway this form is far from perfect, it would have been better to use checkboxes instead of radiobutton, for a start ...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.