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');
}
}
Related
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>
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>
The goal is to have several elements trigger a specific text message for each one when the mouse if over it, and no text if neither one if hovered over. From other questions I found that $("#id").is(":hover") should return true if the mouse is over the element, but it doesn't seem to do it. They all return false and the text is "None"
HTML:
<input class="r_check" type="checkbox" id="r1" name="rating" value="1"><label for="r1"></label>
<input class="r_check" type="checkbox" id="r2" name="rating" value="2"><label for="r2"></label>
<input class="r_check" type="checkbox" id="r3" name="rating" value="3"><label for="r3"></label>
<p class="text" id="the_text"></p>
Javascript/Jquery:
$(document).ready(function(){
var text = $("#the_text");
if($("#r1").is(":hover")){
text.html("Low");
}else if($("#r2").is(":hover")){
text.html("Medium");
}else if($("#r3").is(":hover")){
text.html("High");
}else{
text.html("None");
}
});
I tried to replace the input fields with simple <p id="r1">input 1</p> elements to see if the label or the class of the inputs is preventing the hover event, but that didn't work either.
Your problem can be written in a much neater and easier way as below
Working JSFiddle
<input class="r_check" type="checkbox" id="r1" name="rating" value="1" data-text="Low">
<input class="r_check" type="checkbox" id="r2" name="rating" value="2" data-text="Medium">
<input class="r_check" type="checkbox" id="r3" name="rating" value="3" data-text="High">
<p class="text" id="the_text"></p>
$(document).ready(function() {
$(".r_check").each(function() {
$(this)
.mouseover(function() {
$("#the_text").html($(this).attr('data-text'))
})
.mouseleave(function() {
$("#the_text").html('');
});
})
});
$("#id").on("mouseenter", function(e) { });
That should do it
What you're doing is testing if themouse is over it just once when the page is loaded, what you should do is using an event that's triggered when the mouse is over your input( either with jquery's $('selector').hover(handlerIn,handlerOut) or with $('selector').on("mouseenter,function() {} ) ;
(Here's the difference )
Working jsFiddle
I am quite new to js and html and have some problems with a task. I want to create a "checkbox" that will make some pictures visible. For example I have 5 pictures. On each picture there is a male or female. Now i want to make all female picures visible if someone check the "female checkbox". I think that I will need to create some datatable (?) in js but not sure how to do it.
This is what I created so far
function toggleVisibility(id) {
var el = document.getElementById(id);
if (el.style.visibility=="visible") {
el.style.visibility="hidden";
}
else {
el.style.visibility="visible";
}
}
<div class='Humans'>
<label for="menu">male</label>
<input type="checkbox" id="malecheck" onChange="checkpaycondition('1');" /><br/>
<label for="menu">female</label>
<input type="checkbox" id="femalecheck" onChange="checkpaycondition('2');" /><br/>
<label for="picture">Person1</label>
<input type="checkbox" id="Person1check" onChange="toggleVisibility('4');" /><br/>
<label for="picture">Person2</label>
<input type="checkbox" id="Person2check" onChange="toggleVisibility('1');" /><br/>
<label for="picture">Person3</label>
<input type="checkbox" id="Person3check" onChange="toggleVisibility('2');" /><br/>
<label for="picture">Person4</label>
<input type="checkbox" id="Person4check" onChange="toggleVisibility('3');" /><br/>
<label for="picture">Person5</label>
<input type="checkbox" id="Person5check" onChange="toggleVisibility('5');" /><br/>
<img id='1' src='/home/Person1.png' style='visibility:hidden'/> <!--male-->
<img id='2' src='/home/Person2.png' style='visibility:hidden'/> <!--female-->
<img id='3' src='/home/Person3.png' style='visibility:hidden'/> <!--female-->
<img id='4' src='/home/Person4.png' style='visibility:hidden'/> <!--male-->
<img id='5' src='/home/Person5.png' style='visibility:hidden'/> <!--female-->
</div>
Any idea how I can get this to work? Hope you can help.
Cheers!
I have made some changes to your HTML; it's usually better to use classes when dealing with a group of elements --- it's harder using ids. Here are some changes I have made:
Removed inline JavaScript -- it's not recommended
Removed inline CSS -- not recommended either
Added a class instead of inline css and define a rule
Added two event handlers instead of inline JS
Changed you :checkbox ids to names instead
Removed IDs from img elements
Added a data attribute to each image, data-gender to be used with name="gender"
Added a value attribute to each :checkbox
BONUS added one proper use of IDs -- label for attribute -- click label to check/uncheck
As you can see, once your HTML is well designed, writing your JavaScript and CSS is a piece of cake.
$(document).ready(function() {
//Event handler for checkboxes with name="gender"
$(':checkbox[name=gender]').on('change',function() {
$('img[data-gender=' + this.value + ']').css('visibility', this.checked ? 'visible' : 'hidden');
});
//Event handler for checkboxes with name="visibility"
$(':checkbox[name=visibility]').on('change', function() {
$('img[src*=' + this.value + ']').css('visibility',this.checked ? 'visible' : 'hidden');
});
});
.myimage {
visibility:hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='Humans'>
<label for="gender1">male</label>
<input type="checkbox" name="gender" id="gender1" value="male" /><br/>
<label for="gender2">female</label>
<input type="checkbox" name="gender" id="gender2" value="female" /><br/>
<label for="visibility1">Person1</label>
<input type="checkbox" name="visibility" id="visibility1" value="Person1" /><br/>
<label for="visibility2">Person2</label>
<input type="checkbox" name="visibility" id="visibility2" value="Person2" /><br/>
<label for="visibility3">Person3</label>
<input type="checkbox" name="visibility" id="visibility3" value="Person3" /><br/>
<label for="visibility4">Person4</label>
<input type="checkbox" name="visibility" id="visibility4" value="Person4" /><br/>
<label for="visibility5">Person5</label>
<input type="checkbox" name="visibility" id="visibility5" value="Person5" /><br/>
<img src='/home/Person1.png' data-gender="male" class="myimage"/> <!--male-->
<img src='/home/Person2.png' data-gender="female" class="myimage"/> <!--female-->
<img src='/home/Person3.png' data-gender="female" class="myimage"/> <!--female-->
<img src='/home/Person4.png' data-gender="male" class="myimage"/> <!--male-->
<img src='/home/Person5.png' data-gender="female" class="myimage"/> <!--female-->
</div>
You need to change id to something string_with_number.
For example:
id="image1"... etc
Then you can use this function with having
var el = document.getElementById("image"+id);
and instead of visibility, you should use display: block and display: none
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;
}