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>
Related
I have several groups of checkboxes in a form. For each grouping of checkboxes(by name) I want to create an array and if the box is checked, add it to that particular array and if it's unchecked, remove it. I have that working like this:
var color = [];
var size = [];
$('input[name="color[]"]').change(function () {
color = $('input[name="color[]"]:checked').map(function(i) {
return $(this).val();
}).get();
console.log(color);
});
$('input[name="size[]"]').change(function () {
size = $('input[name="size[]"]:checked').map(function(i) {
return $(this).val();
}).get();
console.log(size);
});
label {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<h4>Color</h4>
<label>
<input type="checkbox" name="color[]" value="red" />
Red
</label>
<label>
<input type="checkbox" name="color[]" value="green" />
Green
</label>
<label>
<input type="checkbox" name="color[]" value="blue" />
Blue
</label>
<h4>Size</h4>
<label>
<input type="checkbox" name="size[]" value="small" />
Small
</label>
<label>
<input type="checkbox" name="size[]" value="medium" />
Medium
</label>
<label>
<input type="checkbox" name="size[]" value="large" />
Large
</label>
</form>
What I'm wondering is if there's a way to do this dynamically so that instead of having a separate change function for each grouping of checkboxes(there will be many) is there a way to combine this into one change function and have it map to the correct array based on the name? Something like this:
var color = [];
var size = [];
$('input[type="checkbox"]').change(function () {
var group = $(this).attr('name');
value = $('input[name="' + group + '"]:checked').map(function(i) {
return $(this).val();
}).get();
console.log(color);
console.log(size);
});
label {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<h4>Color</h4>
<label>
<input type="checkbox" name="color[]" value="red" />
Red
</label>
<label>
<input type="checkbox" name="color[]" value="green" />
Green
</label>
<label>
<input type="checkbox" name="color[]" value="blue" />
Blue
</label>
<h4>Size</h4>
<label>
<input type="checkbox" name="size[]" value="small" />
Small
</label>
<label>
<input type="checkbox" name="size[]" value="medium" />
Medium
</label>
<label>
<input type="checkbox" name="size[]" value="large" />
Large
</label>
</form>
I believe this is what you want. I've set up a codepen to demonstrate.
Tip here: Any time you want to initialise an arbitrary number of variables that you can access later in the global scope, it's usually a good idea to initialise them as properties on an object in the global scope.
const groups = {};
$('input[type="checkbox"]').on("change", function (e) {
const checkedInput = $(e.target);
const groupName = checkedInput.attr('name');
const updatedArray = $(`input[name="${groupName}"]:checked`).map(function(i) {
return $(this).val();
}).get();
groups[groupName] = updatedArray;
console.log(groups[groupName]);
});
It won't get the 2 selector to work together it only uses the second one, I don't know how. I am new to jQuery.
HTML
<div class="janee">
<input id="JA2" type="radio" name="group3" value="Ja">
<label for="JA2" class="form-field__radio__label">Ja, meerprijs €1.50 per m<sup>2</sup></label><br>
<input id="NEE2" type="radio" name="group3" onclick="JaNeeFirst()" value="Nee">
<label for="NEE2">Nee</label>
</div>
<hr>
<div class="janee">
<input id="JA3" type="radio" name="group4" value="Ja">
<label for="JA3" class="form-field__radio__label">Ja</label><br>
<input id="NEE3" type="radio" name="group4" onclick="JaNeeSecond()" value="Nee">
<label for="NEE3">Nee</label>
</div>
jQuery
$('#JA2') && $('#JA3').click(function(){
if ( $(this).is(':checked') )
{
alert('Selected');
}
});
Because that's not valid JavaScript.
You can separate selectors with a comma:
$('#JA2, #JA3').click(function() { });
You can specify any number of selectors to combine into a single
result. This multiple expression combinator is an efficient way to
select disparate elements. The order of the DOM elements in the
returned jQuery object may not be identical, as they will be in
document order.
Or you can use add():
$('#JA2').add('#JA3').click(function() { });
Separate them by comma
$('#JA2, #JA3').click(function()...
$('#JA2, #JA3').click(function(){
if ( $(this).is(':checked') )
{
alert('Selected');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="janee">
<input id="JA2" type="radio" name="group3" value="Ja">
<label for="JA2" class="form-field__radio__label">Ja, meerprijs €1.50 per m<sup>2</sup></label><br>
<input id="NEE2" type="radio" name="group3" onclick="JaNeeFirst()" value="Nee">
<label for="NEE2">Nee</label>
</div>
<hr>
<div class="janee">
<input id="JA3" type="radio" name="group4" value="Ja">
<label for="JA3" class="form-field__radio__label">Ja</label><br>
<input id="NEE3" type="radio" name="group4" onclick="JaNeeSecond()" value="Nee">
<label for="NEE3">Nee</label>
</div>
With jQuery you have to supply a comma-separated string if you want to select multiple elements. You can refer to their documentation here https://api.jquery.com/multiple-selector/#post-435
For example:
$('#element-one, #element-two').css('border', '3px solid red');
The above will add a red border to elements with an id of 'element-one' and 'element-two'.
$('#JA2, #JA3').click(function() {
if ($('#JA2').prop('checked') && $('#JA3').prop('checked')) {
alert('Both checked');
}
}
I have to do a simple work.
I have:
echo' <div class="col-sm-12" id="recensioni_titolo">
<form role="form" id="review-form" method="post" action="php\insert_comment.php">
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<input type="text" class="form-control" name="Titolo" id="titolo_review" placeholder="Titolo">
<input type="text" class="form-control" name="ID_locale" id="titolo_review" value="'.$id_Local.'" style="visibility: hidden; position:fixed;">
</div>
</div>
<div class="col-sm-4">
<fieldset class="rating">
<input type="radio" id="star5'.$id_Local.'" name="Voto" value="5" /><label class = "full" for="star5'.$id_Local.'" title="Ottimo - 5 stelle"></label>
<input type="radio" id="star4'.$id_Local.'" name="Voto" value="4" /><label class = "full" for="star4'.$id_Local.'" title="Buono - 4 stelle"></label>
<input type="radio" id="star3'.$id_Local.'" name="Voto" value="3" /><label class = "full" for="star3'.$id_Local.'" title="Discreto - 3 stelle"></label>
<input type="radio" id="star2'.$id_Local.'" name="Voto" value="2" /><label class = "full" for="star2'.$id_Local.'" title="Insufficiente - 2 stelle"></label>
<input type="radio" id="star1'.$id_Local.'" name="Voto" value="1" /><label class = "full" for="star1'.$id_Local.'" title="Pessimo - 1 stella"></label>
</fieldset>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control textarea" rows="3" name="Review" id="review" placeholder="Inserisci una descrizione.."></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="button" class="btn main-btn pull-right" name="submit_review" id="submit_review'.$id_Local.'">Invia</button>
</div>
</div>
This code is generating the same thing for 5 times. I'have to find one method to declare and use the id="review-form" in a unique mode because with this code:
$(document.getElementsByName("submit_review")).unbind().click(function() {
var chx = document.getElementsByName("Voto");
for (var i=0; i<chx.length; i++) {
// If you have more than one radio group, also check the name attribute
// for the one you want as in && chx[i].name == 'choose'
// Return true from the function on first match of a checked item
if (chx[i].type == 'radio' && chx[i].checked) {
$.ajax({
url : "php/insert_comment.php",
type : "post",
data : $("#review-form").serialize(),
success : function(data){
$.ajax({
url : "php/reviews.php",
type : "post",
data: {'id_Local' : $('.modal').attr('data-modal')},
success : function(data){
$('#box_recensioni').html(data);
chx[i].checked=false;
}
})
}
})
return true;
}
}
// End of the loop, return false
alert("Inserisci almeno il voto!!")
return false;
});
I have only the first element is working.
I can generate the id with "id'.$variable'" but I don't know how to refers to every single id in the javascript file.
Thank you to all in advance
In HTML, an ID is supposed to be unique :
The id global attribute defines a unique identifier (ID) which must be unique in the whole document.
This is why JavaScript can grab only the first occurence of an ID, since it's supposed to be the only one. You may want to replace those multiple IDs with classes, which is at least correct in HTML5 and will be also smarter in Javascript.
Here is a link to the post in the Mozilla documentation of IDs in HTML, to be sure that you understand the role of this tag.
As other's have said using the same ID would be useless instead you may want to use a class identifier. And assuming you want to create multiple form elements... and you don't have a unique identifier to use in your scripts you may try the following which I haven't tested...
I see you have already gotten the radio button
var chx = document.getElementsByName("Voto");
and performed a check on it under your if statement
if (chx[i].type == 'radio' && chx[i].checked) {
if so, maybe you can try to get the closest form element of the radio button that you are dealing with (i.e. checked) by doing something like
var thisForm = chx[i].closest('form')
--and later do thisForm.serialize();
check this out for more detail in using closest
You can create an array, then use an loop through each radio button pushing the id into the array. Then use the array for the ids.
var radioIds = new Array();
$('.rating input[name="Voto"]').each(function(){
radioIds.push($(this).attr('id'));
});
console.log(radioIds)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4">
<fieldset class="rating">
<input type="radio" id="star54" name="Voto" value="5" /><label class="full" for="star54" title="Ottimo - 5 stelle"></label>
<input type="radio" id="star44'" name="Voto" value="4" /><label class="full" for="star44" title="Buono - 4 stelle"></label>
<input type="radio" id="star34" name="Voto" value="3" /><label class="full" for="star34" title="Discreto - 3 stelle"></label>
<input type="radio" id="star24'" name="Voto" value="2" /><label class="full" for="star24" title="Insufficiente - 2 stelle"></label>
<input type="radio" id="star14" name="Voto" value="1" /><label class="full" for="star14" title="Pessimo - 1 stella"></label>
</fieldset>
</div>
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;
}
(I was unsure what title to use so i took what i felt described it if it doesnt fit please tell me/change it)
So i've been making this league of legends site for a while now and ran into a trouble.
I've been making a Filter menu that filters the "Champions"(Hero's) to only show those with the correct role/ability.
So i got an on-click script on checkboxes that should show the correct Champions when clicked on. but it doesnt seem to work.
When i uncheck the textbox it correctly takes back all of the champions, but when i "Check" it all champions disappears (should do this) but it doesnt show those wich apply to the filter. (I got all the correct id's on the DIV's, i know this since i have a search bar that works for filtering aswell but i want checkboxes for it since its simpler)
Checkboxes:
AD<input type="checkbox" name="adcarry" value="adcarry" id="check1" class="check1" onclick="boxchanged()">
AP<input type="checkbox" name="apcarry" value="apcarry" id="check2" class="check2" onclick="boxchanged()">
Carry<input type="checkbox" name="carry" value="carry" id="check3" class="check3" onclick="boxchanged()">
Tank<input type="checkbox" name="tank" value="tank" id="check4" class="check4" onclick="boxchanged()">
Support<input type="checkbox" name="support" value="support" id="check5" class="check5" onclick="boxchanged()">
Jungler<input type="checkbox" name="jungler" value="jungler" id="check6" class="check6" onclick="boxchanged()">
Burst<input type="checkbox" name="burst" value="burst" id="check7" class="check7" onclick="boxchanged()">
<button type="button" onclick="boxchanged()">Reset</button>
Affected divs are designed as following: (The classes changes depending on what the champion can do)
<div class="champion apcarry mid" id="ahri" onclick="OnClickChampion(this.id)"><img src="img/champions/ahri.jpg"> Ahri </div>
Script:
function boxchanged ( )
{
$("#num1").val("Search..");
if ($("[type='checkbox']:checked").length == 0)
{
$(".champion").show(200);
}
else
{
$(".champion").hide(200);
for (var i = 1;i < 7; i++)
{
var name = "check"+i;
console.log(name)
var name2 = document.getElementById(name);
console.log(name2)
if (name2.checked == true)
{
var name3 = name2.name;
$("."+name3).show();
}
}
}
};
You should stop any animation
$("."+name3).stop().show();
Here is your code much simplified
DEMO
$(function() {
$(".champion").on("click",function() {
// put OnClickChampion here
});
$(".check").on("click",function() {
$("#num1").val("Search..");
var checked = $("[type='checkbox']:checked");
console.log(checked.length);
if (checked.length == 0) {
$(".champion").stop().show(200);
}
else {
$(".champion").hide(200);
checked.each(function() {
var klass = $(this).val();
$("."+klass).stop().show(200);
});
}
});
});
using
<form>
<label for="check1">AD</label>
<input type="checkbox" value="adcarry" id="check1" class="check"/>
<label for="check2">AP</label>
<input type="checkbox" value="apcarry" id="check2" class="check"/>
<label for="check3">Carry</label>
<input type="checkbox" value="carry" id="check3" class="check"/>
<label for="check4">Tank</label>
<input type="checkbox"value="tank" id="check4" class="check"/>
<label for="check5">Support</label>
<input type="checkbox" value="support" id="check5" class="check"/>
<label for="check6">Jungler</label>
<input type="checkbox" value="jungler" id="check6" class="check"/>
<label for="check7">Burst</label>
<input type="checkbox" value="burst" id="check7" class="check"/>
<button type="reset" class="check">Reset</button>
</form>
<div class="champion apcarry mid" id="ahri"><img src="img/champions/ahri.jpg"> Ahri </div>
To show only the ones with more than one class
var klasses=[]
checked.each(function() {
klasses.push("."+$(this).val())
});
$(".champion").not(klasses.join(",")).stop().hide(200);