How to Access A MC Question User Selection JS - javascript

how would I access the value of the radio mc choice (chosen by the user) through JS. For example, for this snippet from w3 schools
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
Please respond if you have an answer.

You can access the value of radio button by querySelector() method (There are other ways too). Add CSS for checked radio button in querySelector() method.
To avoid errors check if user selected any one of radio button. And then you're good to go.
let getValueBtn = document.getElementById("btn");
let output = document.getElementById("radioValue");
const getValue = () => {
const radioBtnValue = document.querySelector('input[type="radio"][name="fav_language"]:checked');
if(radioBtnValue === null) return `Nothing is Selected`;
return radioBtnValue.value;
}
getValueBtn.addEventListener("click", function() {
const radioValue = getValue();
output.innerText = radioValue;
});
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
<br>
<br>
<button id="btn">Get Value</button>
<p id="radioValue"></p>

Related

Radio button value selector

I am trying to write a form. In the form there will be one set of radio buttons. When I open my html page on my browser, I would like to click one of the buttons and then write its value in a text after I click a submit button.
This is part of the form code:
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
And this is part of my javascript code:
function buildData(){
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
return txtData;
}
$(function(){
// This will act when the submit BUTTON is clicked
$("#formToSave").submit(function(event){
event.preventDefault();
var txtData = buildData();
window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
});
});
But it is currently not working properly (it won't save the right selection in txt).
How can I fix it? Thanks in advance
UPDATE:
From one of the answers:
function buildData(){
var txtData =
"some text... " + $("[name=tipoBooster]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
}) + "other text...";
return txtData;
}
Here is a simple solution for getting user input when the user changes the checked radio button
$("[name=tb]").change(function() {
var txt = ["custom","block","dark","f1b"][this.value];
console.log(txt);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd><input type="radio" checked="checked" name="tb" value="1"/>
block
<input type="radio" name="tb" value="2" />
dark
<input type="radio" name="tb" value="3" />
f1b
<input type="radio" name="tb" value="0" />
custom
<p></p>
</dl>
</form>
but in your case you need to edit the build function to be like this
function buildData(){
return "type = " + ["custom","block","dark","f1b"][$("[name='tb']:checked").val()];
}
Or if you want more flexible solution you can add labels to your inputs
like this
$("[name='tb']").change(function() {
console.log($(this).parent().text().trim());
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<label><input type="radio" name="tb" value="1" checked="checked" />block</label>
<label><input type="radio" name="tb" value="2" />dark</label>
<label><input type="radio" name="tb" value="3" />f1b</label>
<label><input type="radio" name="tb" value="0" />custom</label>
</dd>
<p></p>
</dl>
</form>
this was for a change event but your build function should be like this then
function buildData() {
return $("[name='tb']:checked").parent().text().trim();
}
Explanation:
$("[name='tb']:checked") gets the checked radio input element
.parent() gets its parent since we need the label to get its text
.text() gets the text of the label
.trim() removes white space before and after the text
Your selector is referencing an id not the name attribute. Try this instead.
var txt =
"type = " + ($("[name='tb']").is(":checked") ? "block" :
($("[name='tb']").is(":checked") ? "dark" :
($("[name='tb']").is(":checked") ? "f1b" : "custom")))
You could use: $("[name='tb']").val() and just set the corresponding values on the actual radio buttons to block dark etc.
e.g:
<input type="radio" checked="checked" name="tb" value="block"/>
block
<input type="radio" name="tb" value="dark" />
dark
<input type="radio" name="tb" value="f1b" />
f1b
<input type="radio" name="tb" value="custom" />
custom
A # in a jQuery selector is for selecting by id attribute.
What if you change the selector from ($("#tb").is(":checked")... to a name selector.
e.g.
($("input[name*='tb']").is(":checked")
If you just want to get the selected radio button's text. Could you update the html to be.
<form method="post" action="" id="formToSave">
<dl>
<dt>Tipo di booster:</dt>
<dd>
<input id="option1" type="radio" checked="checked" name="tb" value="1"/>
<label for="option1">block</label>
...
<p></p>
</dl>
</form>
Then your function can just return the selected text
function buildData(){
return "type = " + $("input[name*='tb']").is(":checked").next("label").text();
}
If you don't want to add labels to the html, then I would try $("input[name*='tb']").is(":checked").next().text();
Maybe sharing a minimum working example link would help, as I am just writing the above from memmory, referencing the documentation (https://api.jquery.com/text/#text).

Autofill a radiobutton

I am trying to auto fill a radio button type, I was training on this website and used it's code to test it on my google chrome console, but it returns undefined.
The website : https://benalexkeen.com/autofilling-forms-with-javascript/
the html: view-source:https://benalexkeen.com/autofilling-forms-with-javascript/
I'm trying to tick the thrid radio button using this code:
var radioElements = document.getElementsByName("input3");
for (var i=0; i<radioElements.length; i++) {
if (radioElements[i].getAttribute('value') == 'Radio3') {
radioElements[i].checked = true;
}
}
output:
I tried to adapt this code to tick on another website and still have this undefined output
I hope this will help. You might be mistaken with the attribute value
var radioElements = document.getElementsByName("input3");
for (var i=0; i<radioElements.length; i++) {
if (radioElements[i].getAttribute('value') == 'radio3') {
radioElements[i].checked = true;
}
}
<input type="radio" id="radio1" name="input3" value="radio1">
<label for="radio1">Redio 1</label><br>
<input type="radio" id="radio2" name="input3" value="radio2">
<label for="radio2">Redio 2</label><br>
<input type="radio" id="radio3" name="input3" value="radio3">
<label for="radio3">Radio 3</label>
Here is another approach in case you want something easier to read IMO.
// Instead of var I used let.
let radioElements = document.getElementsByName("input3");
radioElements.forEach((input) => {
if(input.value === "Radio3") input.checked = true;
})
<input type="radio" id="Radio1" name="input3" value="Radio1">
<label for="radio1">Radio 1</label><br>
<input type="radio" id="Radio2" name="input3" value="Radio2">
<label for="radio2">Radio 2</label><br>
<input type="radio" id="radio3" name="input3" value="Radio3">
<label for="radio3">Radio 3</label>
And about undefined, if the code you are writing doesn't return anything, it will do that. Although, it doesn't mean is not working.

Javascript radio group by button

How to display an alert msg when all radio button checked to no? I only know check radio by individual only.
//I only know this method
$('#attraction1').change( function(){
if ($(this).is(':checked')) {
alert('Yes');
}
});
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br>
Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" name="individual" value="n" /> No
<br>
Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
In this case you should check something like this
$('#some_button').click( function(){
if ($('input[type="radio"][value="n"]:checked').length == 3) {
alert('Yes');
}
});
You can use a common class for all radio button with no value and a javascript array every method.
This line const radioNames = [...document.getElementsByClassName('no')]; will get all the radio button with no value ... is spread operator and will convert collection so that array method can be used on that collection.
This line item.addEventListener('change', checkIfAllNo) will attach event change to radio button with value no so that it checks the value for all other radio button
Array method every will return true if all the value in that array satisfies the condition.
So in this line radioNames.every(item => {return item.checked;}); if all the radio button with no value is checked then isAllFalse will be true & the alert will be triggered.
const radioNames = [...document.getElementsByClassName('no')];
function checkIfAllNo() {
const isAllFalse = radioNames.every(item => {
return item.checked;
});
if (isAllFalse) {
alert('All False')
}
}
radioNames.forEach((item) => {
item.addEventListener('change', checkIfAllNo)
})
<input type="radio" id="attraction1" name="attraction" value="y" checked/> Yes
<input type="radio" class="no" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" checked/> Yes
<input type="radio" id="individual2" class="no" name="individual" value="n" /> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" class="no" name="planBoard" value="n" /> No
In case you have an indeterminate number of inputs you can collect the values for every group and then check if all values match
$("input[type='radio']").change(function() {
// Extract all the radio group names
names = $.unique($('input[type="radio"]').map((v, e) => $(e).attr('name')))
// Collect the value for each group.
// Account for groups that are not selected yet
vals = $.map(names, function(name) {
return $(`input:radio[name="${name}"]:checked`).val() || 'undefined';
})
// Check if collected values match 'n'
console.log(vals.every(v => v == 'n'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Attraction :
<input type="radio" id="attraction1" name="attraction" value="y" /> Yes
<input type="radio" id="attraction2" name="attraction" value="n" /> No
<br> Individual Attraction :
<input type="radio" id="individual1" name="individual" value="y" /> Yes
<input type="radio" id="individual2" name="individual" value="n" checked/> No
<br> Plan Board:
<input type="radio" id="planBoard1" name="planBoard" value="y" checked/> Yes
<input type="radio" id="planBoard2" name="planBoard" value="n" /> No
#ForeverTwoWheels
Please try this code,To Javascript radio group by button
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Radio Buttons</title>
</head>
<body>
<form>
<input type="radio" name="choice" value="yes"> Yes
<input type="radio" name="choice" value="no"> No
<input type="button" id="btn" value="Show Selected Value">
</form>
<script>
const btn = document.querySelector('#btn');
// handle click button
btn.onclick = function () {
const rbs = document.querySelectorAll('input[name="choice"]');
let selectedValue;
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
break;
}
}
alert(selectedValue);
};
</script>
</body>
</html>
I hope this information will be usefull for you.
Thank you.

Validating Multiple Radio Button Groups in Vanilla JS

I am trying to validate multiple groups of radio buttons with pureJS. Basically my client has a group of around 50 questions, and each one has 4 radio buttons that can be used to pick 1 of 4 answers.
They do not want to use jQuery, but pureJS, I have gotten the following to work when there is just one question, but not when there is multiples, any help would be appreciated.
document.getElementById("submit_btn").addEventListener("click", function(event){
var all_answered = true;
var inputRadios = document.querySelectorAll("input[type=radio]")
for(var i = 0; i < inputRadios.length; i++) {
var name = inputRadios[i].getAttribute("name");
if (document.getElementsByName(name)[i].checked) {
return true;
var all_answered = true;
} else {
var all_answered = false;
}
}
if (!all_answered) {
alert("Some questiones were not answered. Please check all questions and select an option.");
event.preventDefault();
}
});
The questions are all laid out like this -
<div class="each-question">
<div class="unanswered-question">
<div class="question-text">
<div class="number">33</div>
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
</div>
<div class="options" id="ans_285">
<div class="radio-button">
<input type="radio" value="3" id="ans33op1" name="ans_285">
<label for="ans33op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans33op2" name="ans_285">
<label for="ans33op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans33op3" name="ans_285" class="custom">
<label for="ans33op3" class="radio-label"> Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans33op4" name="ans_285">
<label for="ans33op4" class="radio-label"> Not Interested</label>
</div>
</div>
</div>
This is the original jQuery used by the client which now has to be in pureJS
jQuery(document).ready(function () {
jQuery("#question_list").submit(function () {
var all_answered = true;
jQuery("input:radio").each(function () {
var name = jQuery(this).attr("name");
if (jQuery("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
if (!all_answered) {
alert("Some questiones were not answered. Please check all questions and select an option.");
return false;
}
});
});
Not sure if it's just an issue with the copy, but you have a return true in your for loop which will cause the entire function to simply return true if just one is answered. Removing that would help.
Ignoring that though, your solution is a bit unwieldy, as it'll loop through every single input on the page individually and will mark it false if not every radio button is unchecked.
Here is a different approach. Basically, get all of the radio buttons, then group them into arrays by question. Then, loop through each of those arrays and check that within each group, at least one is answered.
document.querySelector('form').addEventListener('submit', e => {
// Get all radio buttons, convert to an array.
const radios = Array.prototype.slice.call(document.querySelectorAll('input[type=radio]'));
// Reduce to get an array of radio button sets
const questions = Object.values(radios.reduce((result, el) =>
Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }), {}));
// Loop through each question, looking for any that aren't answered.
const hasUnanswered = questions.some(question => !question.some(el => el.checked));
if (hasUnanswered) {
console.log('Some unanswered');
} else {
console.log('All set');
}
e.preventDefault(); // just for demo purposes... normally, just put this in the hasUnanswered part
});
<form action="#">
<div>
<label><input type="radio" name="a" /> A</label>
<label><input type="radio" name="a" /> B</label>
<label><input type="radio" name="a" /> C</label>
<label><input type="radio" name="a" /> D</label>
</div>
<div>
<label><input type="radio" name="b" /> A</label>
<label><input type="radio" name="b" /> B</label>
<label><input type="radio" name="b" /> C</label>
<label><input type="radio" name="b" /> D</label>
</div>
<button type="submit">Submit</button>
</form>
First up, I get all of the radio buttons that have a type of radio (that way if there are others, I won't bother with them).
Then, I turn the NodeList returned by querySelectorAll() into an Array by using Array.prototype.slice.call() and giving it my NodeList.
After that, I use reduce() to group the questions together. I make it an array with the element's name as the key (since I know that's how they have to be grouped). After the reduce, since I don't really care about it being an object with the key, I use Object.values() just to get the arrays.
After that, I use some() over the set of questions. If that returns true, it'll mean I have at least one unanswered question.
Finally, inside that some(), I do another over the individual radio buttons of the question. For this, I want to return !some() because if there isn't at least one that is answered, then I should return true overall (that I have at least one question not answered).
The above is a bit verbose. This one is a bit more concise and is what I would likely use in my own code:
document.querySelector('form').addEventListener('submit', e => {
if (Object.values(
Array.prototype.reduce.call(
document.querySelectorAll('input[type=radio]'),
(result, el) =>
Object.assign(result, { [el.name]: (result[el.name] || []).concat(el) }),
{}
)
).some(q => !q.some(el => el.checked))) {
e.preventDefault();
console.log('Some questions not answered');
}
});
<form action="#">
<div>
<label><input type="radio" name="a" /> A</label>
<label><input type="radio" name="a" /> B</label>
<label><input type="radio" name="a" /> C</label>
<label><input type="radio" name="a" /> D</label>
</div>
<div>
<label><input type="radio" name="b" /> A</label>
<label><input type="radio" name="b" /> B</label>
<label><input type="radio" name="b" /> C</label>
<label><input type="radio" name="b" /> D</label>
</div>
<button type="submit">Submit</button>
</form>
Everything inside your for clause makes absolutely no sense. Here's why:
Since you already have inputRadios, there is no point and getting their name and then using that to get the elements by name, because you already have them.
Since you use return true, the function exits and everything beyond that is disregarded.
Instead of updating the existent all_answered variable you create a new, local one that will be lost once the current iteration ends.
What you should do:
Instead of getting all inputs, get all answers, the div.options elements that contain the inputs for each answer, and iterate over those.
Then, use the id of the answer, because it's the same as the name of the inputs, to get the related inputs.
Use some to ensure that there is a checked input among the group. Then, check whether there isn't and stop the loop. You've found an unanswered question.
Snippet:
document.getElementById("submit_btn").addEventListener("click", function(event) {
var
/* Create a flag set by default to true. */
all_answered = true,
/* Get all answers. */
answers = document.querySelectorAll(".options[id ^= ans_]");
/* Iterate over every answer. */
for (var i = 0; i < answers.length; i++) {
var
/* Use the id of the answer to get its radiobuttons. */
radios = document.querySelectorAll("[name = " + answers[i].id + "]"),
/* Save whether there is a checked input for the answer. */
hasChecked = [].some.call(radios, function(radio) {
return radio.checked;
});
/* Check whether there is a checked input for the answer or not. */
if (!hasChecked) {
/* Set the all_answered flag to false and break the loop. */
all_answered = false;
break;
}
}
/* Check whether not all answers have been answered. */
if (!all_answered) {
console.log("Some questions were not answered...");
} else {
console.log("All questions are answered!");
}
});
.question { display: inline-block }
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_285">
<div class="radio-button">
<input type="radio" value="3" id="ans33op1" name="ans_285">
<label for="ans33op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans33op2" name="ans_285">
<label for="ans33op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans33op3" name="ans_285" class="custom">
<label for="ans33op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans33op4" name="ans_285">
<label for="ans33op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_286">
<div class="radio-button">
<input type="radio" value="3" id="ans34op1" name="ans_286">
<label for="ans34op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans34op2" name="ans_286">
<label for="ans34op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans34op3" name="ans_286" class="custom">
<label for="ans34op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans34op4" name="ans_286">
<label for="ans34op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<div class="question">
<div class="text">
<p>Troubleshoot technology issues.</p>
</div>
<div class="options" id="ans_287">
<div class="radio-button">
<input type="radio" value="3" id="ans35op1" name="ans_287">
<label for="ans35op1" class="radio-label">Very Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="2" id="ans35op2" name="ans_287">
<label for="ans35op2" class="radio-label">Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="1" id="ans35op3" name="ans_287" class="custom">
<label for="ans35op3" class="radio-label">Slightly Interested</label>
</div>
<div class="radio-button">
<input type="radio" value="0" id="ans35op4" name="ans_287">
<label for="ans35op4" class="radio-label">Not Interested</label>
</div>
</div>
</div>
<button id="submit_btn">Submit</button>
The following is a simplified version, but there should be enough code to get you heading in the right direction.
var answer = [];
function checkAnswerCount(e) {
// for the answer ids
var i = 0, max = answer.length;
// for the radios
var j = 0; rMax = 0;
// And a few extras
var tmp = null, answerCount = 0;
for(;i<max;i++) {
tmp = document.getElementsByName(answer[i]);
rMax = tmp.length;
for(j=0;j<rMax;j++) {
if (tmp[j].checked) {
answerCount++;
break;
}
}
}
if (answerCount == answer.length) {
console.log("All questions have an answer, submit the form");
} else {
console.log("You need to answer all the questions");
}
}
window.onload = function() {
// each answer block is surrounded by the "options" class,
// so we use that to collect the ids of the raido groups
var a = document.querySelectorAll(".options");
var i = 0, max = a.length;
for(;i<max;i++) {
answer.push(a[i].id);
}
// And we want to check if all the answers have been answered
// when the user tries to submit...
var s = document.getElementById("submitAnswers");
if (s) {
s.addEventListener("click",checkAnswerCount,false);
}
}
<p>Question 1.</p>
<div class="options" id="ans_1">
<label><input type="radio" name="ans_1" value="a1_1" /> Answer 1, op1</label>
<label><input type="radio" name="ans_1" value="a1_2" /> Answer 1, op2</label>
</div>
<p>Question 2.</p>
<div class="options" id="ans_2">
<label><input type="radio" name="ans_2" value="a2_1" /> Answer 2, op1</label>
<label><input type="radio" name="ans_2" value="a2_2" /> Answer 2, op2</label>
</div>
<p>Question 3.</p>
<div class="options" id="ans_3">
<label><input type="radio" name="ans_3" value="a3_1" /> Answer 3, op1</label>
<label><input type="radio" name="ans_3" value="a3_2" /> Answer 3, op2</label>
</div>
<button id="submitAnswers">Submit / check</button>

dynamic variable name from form input name

How would i create a dynamic variable name based on all the forms input checkbox list names? This is what i have so far
var nameArray = [];
$.each($("#store-filter input").serializeArray(), function(i, field) {
nameArray[field.name] = field.value;
});
alert(nameArray[0]);
for (i = 0; nameArray.length > i; i++)
{
//alert(nameArray[i]);
var nameArray[i] = nameArray[i].value;
var nameArray[i]+'_checked_values' = $(\'input[name="nameArray[i]+[]"]:checked\').map(function() {
return this.value;
}).get();
}
alert(make); //variable name from name="make[]"
sample HTML
<form id="store-filter" action:"javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
so later on in my code i can create a url string ?make=1,2,3&store=40,5,6&time=1,2,3,4 etc
the $_GET parameters are taken from the input check boxes name's dynamically
I'd suggest the following approach, obviously I'm binding to the click of a button, you should add that to the event/interaction of your choice:
function makeQueryString() {
function keyValues(idPref) {
// using the pass-in 'id' as a key:
var key = idPref,
// searching within the element identified with that 'id' for
// other elements whose 'id' *starts* with that string:
values = $('#' + idPref + ' input[id^="' + idPref + '"]').map(function() {
// iterating over those found elements and, if the value is *not* the
// defaultValue (value on page-load), *or* the checked state is not the
// default state (checked/unchecked as on page-load):
if (this.value !== this.defaultValue || this.checked !== this.defaultChecked) {
// we return the value:
return this.value;
}
// get() converts to a JavaScript Array, join() concatenates Array elements
// to form a string:
}).get().join(',');
// if there is a key, and there are associated values, we return a 'key=value,value2'
// string, otherwise we return an empty string:
return key && values.length ? key + '=' + values : '';
}
// we return the value obtained after iterating over the form's span elements
// that have an [id] attribute:
return $('form span[id]').map(function(){
// obtaining the 'key=value1,value2' strings from the called-function:
return keyValues(this.id);
// converting those returned elements into an Array, and joining with & characters:
}).get().join('&');
}
$('#test').click(function(e) {
e.preventDefault();
console.log(makeQueryString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">test</button>
<form id="store-filter" action: "javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
References:
CSS:
Attribute-presence and value ([attribute],[attribute="value"]) selectors.
JavaScript:
Array.prototype.join().
defaultChecked and defaultValue (HTMLInputElement).
jQuery:
get().
map().
You are in Javascript, you do not need to declare the size of your arrays, there is no propblems by adding/removing anything from an Object/Array.
You should create a variable make then get the values in. Finally, you will be able to get it back.
var make;
$.each($("#store-filter input").serializeArray(), function(i, field) {
make[i] = field.name;
});
Later in your code, you will use the array make.
make[0];
EDIT:
Here is an example i did for you: http://jsfiddle.net/kjkzm8qm/
NOTE: Your $.each($("#store-filter input").serializeArray() ... is useless, you should select all your inputs by adding a class AND, you should END your input tags by adding a / at the end.
HTML
<input name="test" class="inputs" />
JAVASCRIPT
$.each($(".inputs"), function(){ });
Update for david's answer.
If you want to remove & then add this code below
For this check the key value is not null
let keyValue = keyValues(this.id);
if (keyValue != ''){
return keyValue;
}

Categories