check the radio button when click on the li using javascript - javascript

I have radio button
Html code:
<input type="radio" class="first" name="bright" checked>
<input type="radio" class="second" name="bright" >
<input type="radio" class="third" name="bright">
<input type="radio" class="four" name="bright">
And i have a nav bar
Html code
<ul class="nav">
<li class="st st1 active" data-cont="first">
<h2 class="inner">وزارة الاستثمار</h2>
</li>
<li class="st st2" data-cont="second">
<h2 class="inner">وزارة التجارة</h2>
</li>
<li class="st st3" data-cont="third">
<h2 class="inner">جهات حكومية اخرى</h2>
</li>
<li class="st st4" data-cont="four">
<h2 class="inner">مكتب هندسي</h2>
</li>
</ul>
These 2 are conected with the data-cont that have the class of the radio button
I want when i click on the li the correct radio button be checked using javascript
I tried to make it using this code in JavaScript
let radio = document.querySelectorAll("input");
let radioArray = Array.from(radio);
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);
tabsArray.forEach((ele) => {
ele.addEventListener("click", function (e) {
tabsArray.forEach((ele) => {
ele.classList.remove("active");
});
e.currentTarget.classList.add("active");
document.querySelector(e.currentTarget.dataset.cont).checked = true;
});
});
I try to remove the active class from li and put it on the li where i click then i want the radio button be checked
Any body can help me on this?

the last querySelector is where your code is failing you're not referencing the class for your input it needs to be document.querySelector('.' + e.currentTarget.dataset.cont).checked = true; note the "." prefix
Although that answers your question there is probably more value in pointing out that by changing your html markup to be a little more accessible you can eliminate the need for all of the javascript in your example
e.g.
input:checked + label {
color:Red;
}
<div><input type="radio" id="first" name="bright" checked>
<label for='first'>وزارة الاستثما</label>
</div>
<div>
<input type="radio" id="second" name="bright" >
<label for='second'>وزارة التجارة</label>
</div>
<div>
<input type="radio" id="third" name="bright">
<label for='third'>جهات حكومية اخرى</label>
</div>
<div>
<input type="radio" id="four" name="bright">
<label for='four'>مكتب هندسي</label>
</div>
The use of labels associated with your radio buttons is now significantly more accessible and you can drastically reduce a lot of your markup ( though to be accessible you would need to provide a more meaningful name for for attribute.

Related

Why is my javascript code duplicating li?

I am a Javascript beginner (this is my first javascript program) and I have a few problems with my mini app...
I am trying to build a page that allows you to choose who was in your team working with you today. The user should be able to build his own list among a list of names.
When the user clicks on "Add to the team", it should remove the corresponding <li> and add it to the selected list below.
The button needs to change from Add to the team to Delete
I am struggling to change the button textcontent if user choose to add then remove then add the same <li>...
I've been trying a lot of things, this is my last try:
'script type="text/javascript"';
var selected = document.querySelector('#selected-list ul');
var team = document.querySelector('#team-list ul');
var searchBar = document.forms['search-employees'].querySelector('input');
//add to the selected team
team.addEventListener("click", function(e){
if(e.target.className == 'add'){
const li = document.createElement('li');
const employeename = document.createElement('span');
const deleteBtn = document.createElement('span');
//add content
deleteBtn.textContent = 'add';
employeename.textContent = e.target.parentElement.firstElementChild.textContent;
//add classes
employeename.classList.add("name");
deleteBtn.classList.add('delete');
// append to document
li.appendChild(employeename);
li.appendChild(deleteBtn);
selected.appendChild(li);
console.log(deleteBtn);
}
})
//delete teammate from selected team
selected.addEventListener('click', function(e){
if(e.target.className == 'delete'){
const li = document.createElement('li');
const employeename = document.createElement('span');
const addBtn = document.createElement('span');
//add content
addBtn.textContent = 'delete';
employeename.textContent = e.target.parentElement.firstElementChild.textContent;
//add classes
employeename.classList.add("name");
addBtn.classList.add('add');
// append to document
li.appendChild(employeename);
li.appendChild(addBtn);
team.appendChild(li);
//delete from selected
console.log(addBtn);
}
})
//add a new employee - listen to submit event from form
var addForm = document.forms['add-employee'];
addForm.addEventListener('submit', function(e){
e.preventDefault(); //prevent default behavior
const value = addForm.querySelector('input[type="text"]').value;
console.log(value);
//create elements
const li = document.createElement('li');
const employeename = document.createElement('span');
const deleteBtn = document.createElement('span');
//add content
deleteBtn.textContent = 'delete';
employeename.textContent = value;
//add classes
employeename.classList.add("name");
deleteBtn.classList.add('delete');
// append to document
li.appendChild(employeename);
li.appendChild(deleteBtn);
selected.appendChild(li);
//apply style
})
//filter names
//grab a reference to the form
searchBar.addEventListener('keyup', function(e){
//term the user is searching
const term = e.target.value.toLowerCase();
//names to compare
const names = team.getElementsByTagName('li');
Array.from(names).forEach(function(name){
const fullname = team.firstElementChild.textContent;
//check if name exists
if(fullname.toLowerCase().indexOf(term) != -1){
name.style.display = 'block';
} else {
name.style.display = 'none';
}
})
})
It gives me the following result:
Every time I hit the button, it gives me a duplicate (same for the input Teammate not found)
Moreover, I still can't, once deleted, get back to a "Add to the team"...
I hope you guys can enlighten me, I spent maybe too much time on it, but I cant find out right now...
This is few captions of what it does:
enter image description here
once you clicked on delete in selected list
enter image description here
Thank you
HTML:
<?php
require_once 'core/init.php';
include 'includes/checkedboxes.php';
include 'includes/headerfront.php';
//include_once 'includes/dbh.inc.php';
if(Session::exists('Success')){
echo Session::flash('Success');
}
?>
<html>
<head>
<link rel="stylesheet" href="styleChief.css">
</head>
<body>
<section class="team">
<div id="wrapper">
<div id="container-left">
<div id="search">
<h2 class="title">Who was in your team today?</h1>
<form id="search-employees">
<input type="text" name="search" placeholder="Search a name..">
</form>
</div>
<div id="team-list">
<h3 class="title">Team list</h3>
<p>Select today's teammates</p>
<ul>
<li>
<span class="name">name</span>
<span class="add">Add to the team</span>
</li>
<li>
<span class="name">name 1</span>
<span class="add">Add to the team</span>
</li>
<li>
<span class="name">name 2</span>
<span class="add">Add to the team</span>
</li>
<li>
<span class="name">name 3</span>
<span class="add">Add to the team</span>
</li>
</ul>
</div>
<div id=newmember class="newmember">
<h4>
<a class="not-found" href="#"><img class="img" src="img/not-found.png" width="20" height="20" alt="not-found">
</a>Teammate not found?</h4>
<form id="add-employee">
<h3 class="title">Add a new member:</h3>
<input type="text" placeholder="New teammate name">
<button>Add</button>
</form>
</div>
</div>
<div id="container-right">
<h2>Selected</h2>
<div id="selected-list">
<h3 class="title">You have selected the following teammates for today: </h3>
<ul>
</ul>
</div>
</div>
</div>
</section>
<section class="part">
<h2>Which part(s) have you been working on today?</h2>
<input type="checkbox" name="checklist-part" value="Decoratives"><label>Decoratives</label>
<input type="checkbox" name="checklist-part" value="Windows"><label>Windows</label>
<input type="checkbox" name="checklist-part" value="Signage Gibela"><label>Signage Gibela</label>
<input type="checkbox" name="checklist-part" value="Signage Prasa"><label>Signage Prasa</label>
<input type="checkbox" name="checklist-part" value="Stripes"><label>Stripes</label>
<input type="checkbox" name="checklist-part" value="Other"><label>Other</label><br/>
<input type="submit" name="submit" value="Continue" /><br/>
</form>
</section>
<?php
$sql="SELECT * FROM dttechnames;";
$result=mysqli_query($conn,$sql);
?>
<script src="app/app.js"></script>
<script src="app/app.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</body>
</html>
I tried to fx a few issues with your snippet (e. g. there was a <form> tag missing). Basically, you were working far too hard in your script part. If you want to move a <li> from one <ul> to another then it is easiest to simply .appendChild() it to the target <ul>. Doing so will automatically remove it from its original parent <ul>. As the "move" operation is universal to all team-member-<li>s - whether they are part of the "team" or the "selected" group - we can use a single "click" event-listener for all of them. I added it to the outer #wrapper div.
The following snippet only covers the team member picking part (I removed all other script components for clarity) but it should demonstrate the basic points:
var grps=['#selected','#team'].map(s=>document.querySelector(s+'-list ul')),
btn=['Add to the team','Remove from the team'];
[...grps[1].querySelectorAll('.move')].forEach(sp=>sp.textContent=btn[0])
// move members ...
document.querySelector('#wrapper').addEventListener("click", function(e){
if(e.target.classList.contains('move')){
var i=btn.indexOf(e.target.textContent); // i=0 (Adding) or i=1 (Removing) ?
e.target.textContent=btn[1-i]; // exchange button caption
grps[i].appendChild(e.target.parentNode) // move team member ...
}
})
li {margin: 10px}
.move{
float: right;
background: #9361bf;
padding:4px;
border-radius: 3px;
}
<section class="team">
<div id="wrapper">
<div id="container-left">
<div id="search">
<h2 class="title">Who was in your team today?</h1>
<form id="search-employees">
<input type="text" name="search" placeholder="Search a name..">
</form>
</div>
<div id="team-list">
<h3 class="title">Team list</h3>
<p>Select today's teammates</p>
<ul>
<li>
<span class="name">Roman BARON</span>
<span class="move"></span>
</li>
<li>
<span class="name">Vincent Houdeville</span>
<span class="move"></span>
</li>
<li>
<span class="name">Jayson Abrams</span>
<span class="move"></span>
</li>
<li>
<span class="name">Bafana Hlongwane</span>
<span class="move"></span>
</li>
</ul>
</div>
<div id=newmember class="newmember">
<h4>
<a class="not-found" href="#"><img class="img" src="img/not-found.png" width="20" height="20" alt="not-found">
</a>Teammate not found?</h4>
<form id="add-employee">
<h3 class="title">Add a new member:</h3>
<input type="text" placeholder="New teammate name">
<button>Add</button>
</form>
</div>
</div>
<div id="container-right">
<h2>Selected</h2>
<div id="selected-list">
<h3 class="title">You have selected the following teammates for today: </h3>
<ul>
</ul>
</div>
</div>
</div>
</section>
<section class="part">
<h2>Which part(s) have you been working on today?</h2>
<form id="parts">
<label><input type="checkbox" name="checklist-part" value="Decoratives">Decoratives</label>
<label><input type="checkbox" name="checklist-part" value="Windows">Windows</label>
<label><input type="checkbox" name="checklist-part" value="Signage Gibela">Signage Gibela</label>
<label><input type="checkbox" name="checklist-part" value="Signage Prasa">Signage Prasa</label>
<label><input type="checkbox" name="checklist-part" value="Stripes">Stripes</label>
<label><input type="checkbox" name="checklist-part" value="Other">Other</label><br/>
<input type="submit" name="submit" value="Continue" /><br/>
</form>
</section>
This seems to have been the first question you posted on StackOverflow, so a belated: "Welcome here!"
But I would like to point out that your question was unnecessarily long and complicated. You should try and focus on one point per question. This would make it much more accessible for other Stackoverflow members to answer without having to review large chunks of code first.
And one final remark: You tagged your question with jQuery, but as you haven't used it in your script I also removed the script src="...jquery..."></script> tag from my snippet. I am eternally grateful to John Resig for giving us jQuery but in modern browsers you can now mostly do without it.
After trying cars10m solution, I have few problems..
1. The css style of my "Add to the team" disappeared. I of course changed my code above to:
.add,.delete {
float: right;
background: #9361bf;
padding:6px;
border-radius: 4px;
}
to :
.move{
float: right;
background: #9361bf;
padding:6px;
border-radius: 4px;
}
but doesnt style the class.
Maybe move is a reserved keyword?
Anyways, I have another problem:
2. That solution moves the selected "li", but inside the same <ul>.
When I do a console.log(e.target.textContent) just after if(e.target.classList.contains('move')), i get to see that it contains "Add to the team" and "Remove from the team".
I found out that it was behaving as if I clicked two twice, but I only clicked once.
Why?
Thank you guys for your answers!!

ng-checked in radio button

I'm making a quiz app.To show the progress of the quiz there is question pallette of small boxes which turn yellow when users click on any of the the radio button to show that the user has attempted the question.Along with this there is a button to move to the previous question.To show the users initial answer I have used ng-checked directive with some logic in the controller.Everything is working fine but after attempting a question when I move to the next question and click on the same option as the previous question then the question pallette box does not turn yellow.But when I click on the other option it works fine.
.html
<div class="questionsBox" >
<div class="questions">{{liveCtrl.questions[liveCtrl.activeQuestion].question}}</div>
<ul class="answerList">
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===1" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,1)" name="answerGroup" value="0" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionA}}</label>
</li>
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===2" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,2)" name="answerGroup" value="1" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionB}}</label>
</li>
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===3" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,3)" name="answerGroup" value="2" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionC}}</label>
</li>
<li>
<label>
<input data-id="{{liveCtrl.activeQuestion}}" type="radio" ng-checked="liveCtrl.useranswers[liveCtrl.activeQuestion].q===4" ng-click="liveCtrl.answers(liveCtrl.activeQuestion,4)" name="answerGroup" value="3" > {{liveCtrl.questions[liveCtrl.activeQuestion].optionD}}</label>
</li>
</ul>
<div class="questionsRow">
<button ng-disabled="liveCtrl.questions.length==liveCtrl.activeQuestion+1" class="subques btn btn-lg btn-secondary" ng-click="liveCtrl.nextQuestion()">Save & Next</button>
<button ng-click="liveCtrl.prevQuestion()" ng-disabled="liveCtrl.activeQuestion == 0" class="subques btn btn-lg btn-secondary" >Previous</button>
</div>
</div>
//Question Pallete
<div class="question-pallete">
<div id="{{$index}}" ng-repeat="question in liveCtrl.questions" class="square">
<a ng-click="liveCtrl.gotoQues($index)">
{{$index + 1}}
</a>
</div>
//jquery to give color to the boxes
<script type="text/javascript">
$(document).on('click',"input[name='answerGroup']",function(){
var qid=$(this).data('id');
console.log(qid);
$('#'+qid).addClass('box-color');
});
</script>
Controller functions
this.nextQuestion=()=>{
live.activeQuestion++;
//console.log(live.activeQuestion);
};
this.prevQuestion=()=>{
live.activeQuestion--;
//console.log(live.activeQuestion);
};
this.gotoQues=(qno)=>{
live.activeQuestion=qno;
}
this.answers=(qid,option)=>{
//console.log(qid);
live.useranswers[qid]={
q:option
};
When I'm tried to console qid in jquery part it outputs the same qid for the same option in the next question but it is not the case for other options.I think "data-id" in html is not updating for that case.Sorry If I was not able to explain it properly.
I find 2 issues with your implementation.
I don't see ng-model in any of your input field.
Why don't you use ng-class instead of using jquery to get the id and add class?
<label ng-class="val==0 ? 'highlight':''">
<input type="Radio" ng-model="val" ng-value="0">Option A</label>
Here is the jsfiddle link

if checkbox is checked remove class from div on click

Posted a question on about the same project in the morning. After battling it for a while came up with a bit different approach.
Trying to build a filter. And the idea is that a filter checkboxes have matching id's with filtered items classes. So, once a filter item clicked, filtration is applied to item class. Classes (except for inditem) and ids are dynamic
simplified html of it
<div class="itemswrap">
<div class="inditem dynamic1"></div>
<div class="inditem dynamic2"></div>
<div class="inditem dynamic3"></div>
<div class="inditem dynamic2"></div>
</div>
<ul class="subnav">
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic1" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic2" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic3" />
<label for="dynamic1">whatever label</label>
</li>
</ul>
js
$(".lifilter").each(function() {
var filter1 = $(this).find('.filtercheck').attr('id');
if ( $(this).find('.filtercheck').attr('checked') ) {
$(this).find('.filtercheck').click(function(){
$('.' + filter1).removeClass('checkeditem').hide();
});
}
else
{
$(this).find('.filtercheck').click(function(){
$('.inditem').hide();
$('.' + filter1).addClass('checkeditem');
});
}
});
and this one marked as important not to be hidden when extra items are added into filtration
.checkeditem {display:block !important}
Initial filtration works fine. But when I click on checked item the associated div does not hide.
Do you mean something like
var $filters = $('.filtercheck').change(function() {
var $items = $('.inditem').hide();
var filters = $filters.filter(':checked').map(function() {
return '.' + this.id;
}).get();
if (filters.length) {
$items.filter(filters.join()).show();
} else {
$items.show();
}
});
.checkeditem {
display: block !important
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="itemswrap">
<div class="inditem dynamic1">dynamic1</div>
<div class="inditem dynamic2">dynamic2</div>
<div class="inditem dynamic3">dynamic3</div>
<div class="inditem dynamic2">dynamic2</div>
</div>
<ul class="subnav">
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic1" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic2" />
<label for="dynamic1">whatever label</label>
</li>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="dynamic3" />
<label for="dynamic1">whatever label</label>
</li>
</ul>
The problem with the code is that the event handler attaches the second click event on the first successful case. This means that the "click" on the checkbox is being given the "addclass" case, and all subsequent clicks are being handled by that handler instead of the intended one.
Using the same HTML. I created this:
$(document).ready(function() {
$(".filtercheck").click(function(){
$('.inditem').hide();
var filter1 = $(this).attr('id');
$('.' + filter1).toggleClass('checkeditem');
});
});
which I think is the intended behavior? Instead of individually attaching click handlers, I simply attached a single handler to all of them. It would be fairly easy to do something like
$(this).prop()
to determine if the currently clicked on item had was active or not. For this simple example, I opted to just use a class toggle to illustrate the point.

Removing an element from an array when a dropdown item is unselected

I have this script that runs when a user selects an element in a dropdown list:
<script type="text/javascript">
var seSelection = [];
$(document).ready(function() {
$(".dropdown-menu input").click(function() {
var value = $(this).val();
$(this).closest("#seButton").data();
if (this.checked) {
seSelection.push(this.value);
}
});
console.log("se equals " + seSelection);
});
</script>
<button id ="seButton" data-toggle="dropdown" class="btn btn-primary dropdown-toggle">
Options<span class="caret"></span>
</button>
<ul class="dropdown-menu noclose">
<li>
<input type="checkbox" id="ex3_1" name="ex3" value="A" checked="">
<label for="ex3_1">Option 1</label>
</li>
<li>
<input type="checkbox" id="ex3_2" name="ex3" value="B">
<label for="ex3_2">Option 2</label>
</li>
<li>
<input type="checkbox" id="ex3_3" name="ex3" value="C">
<label for="ex3_3">Option 3</label>
</li>
</ul>
I'm using the Twitter Bootstrap noclose, so dropdown-menu stays open until I click out of it. This is designed to allow a user to select multiple options. So as I select various options, my console looks like this, as the script fires on each click:
se equals
se equals A
se equals A,B
se equals A,B,C
This is great - and it's functioning properly, but in the same dropdown, if I deselect C after I have selected it, it doesn't REMOVE c as a value from the array seSelection.
I'm not sure how to write the code that does the inverse of what my script's code above does since I can't find any unclick(function) or unpush(this.value) that exists in jQuery.
How do I write this?
On unchecking you can remove the item from the array just like this http://jsfiddle.net/93zL0ae9/
<script type="text/javascript">
var seSelection = [];
$(document).ready(function(){
$(".dropdown-menu input").click(function() {
var value = $(this).val();
$(this).closest("#seButton").data();
if (this.checked) {
seSelection.push(this.value);
}
else
{
var index = seSelection.indexOf(this.value);
if(index>=0)
{
seSelection.splice(index,1);
}
}
console.log("se equals " + seSelection);
});
});
</script>
<button id ="seButton" data-toggle="dropdown" class="btn btn-primary dropdown-toggle">Options<span class="caret"></span></button>
<ul class="dropdown-menu noclose">
<li>
<input type="checkbox" id="ex3_1" name="ex3" value="A" checked="">
<label for="ex3_1">Option 1</label>
</li>
<li>
<input type="checkbox" id="ex3_2" name="ex3" value="B">
<label for="ex3_2">Option 2</label>
</li>
<li>
<input type="checkbox" id="ex3_3" name="ex3" value="C">
<label for="ex3_3">Option 3</label>
</li>
</ul>
</div>
It's because the instance is still being saved in your global variable, seSelection. I bet you if you unselect and then re-select an option it would show up twice.
It depends what your requirements are, but you probably instead want to generate that array of results from scratch after each click. You can do this by moving your var seSelection = []; line within the anonymous callback function, as well as that console.log statement.

close other div when div1 is show and duplicate code pb jquery

I have 2 problems
1.First i need to allow only one div open , so when div question1 is show
div question2 and all other should hide, actually its not case in my poor code :).
2.Second problem , I achieve to made a code with an addclass when "is checked", but actually i duplicate all the code for each div .. Perhaps someone have a better elegant option to merge the code and avoiding duplicate code..
$(".checkbox").hide();
$(".question").show();
$('.question').click(function(){
$(".checkbox").toggle(10);
});
$('#test').change(function(){
if($(' input[type=checkbox]:checked').length) {
$('div.question').addClass("question-active");
} else {
$('div.question').removeClass("question-active");
}
});
$(".checkbox2").hide();
$(".question2").show();
$('.question2').click(function(){
$(".checkbox2").toggle(10);
});
$('#test2').change(function(){
if($(' input[type=checkbox]:checked').length) {
$('div.question2').addClass("question-active");
} else {
$('div.question2').removeClass("question-active");
}
});
Here is my code : http://jsfiddle.net/5C3p9/3/
Thanks for help
Regards
If you want to keep your HTML markup as it is, this should work:
// The ^= selector is used to select the elements which have the
// property starting with the text provided.
// ie: class starting with checkbox
$("div[class^='checkbox']").hide();
$("div[class^='question']").show();
$("div[class^='question']").click(function () {
// This way you are able to close the clicked one itself
$("div[class^='checkbox']").not($(this).next()).hide();
$(this).next("div[class^='checkbox']").toggle(10);
});
$("ul[id^='test']").change(function () {
// You can use the .toggleClass() method giving the class name
// and a boolean (add/remove) as parameters
$(this)
.parents()
.prev("div[class^='question']")
.toggleClass("question-active", $("input[type='checkbox']:checked").length != 0);
});
Demo: http://jsfiddle.net/5C3p9/7/
EDIT: I've put some comments in the code.
Some minor dom changes
<div class="quest question"></div>
<div class="ans checkbox">
<ul id="test">
<li>
<input type="checkbox" name="question-1" value="1"
/> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"
/> is it melon ?
</li>
</ul>
</div>
<div class="quest question2"></div>
<div class="ans checkbox2">
<ul id="test2">
<li>
<input type="checkbox" name="question-1" value="1"
/> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"
/> is it melon ?
</li>
</ul>
</div>
then
$(".quest").show();
$(".ans").hide();
$('.quest').click(function(){
$(this).next().toggle(10);
});
$('.ans').change(function(){
var $ans = $(this).closest('.ans');
$ans.prev().toggleClass('question-active', $ans.find('input:checkbox:checked').length > 0)
});
Demo: Fiddle
I made some modifications to your code. What I did is that I added some HTML-classes and made the javascript more general and traverse the HTML instead of pointing straight to the element.
Here's the jsFiddle: http://jsfiddle.net/E595w/1/
The new HTML:
<div class="question"></div>
<div class="checkbox">
<ul id="test" class="test">
<li>
<input type="checkbox" name="question-1" value="1"> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"> is it melon ?
<li>
</ul>
</div>
<div class="question"></div>
<div class="checkbox">
<ul id="test2" class="test">
<li>
<input type="checkbox" name="question-1" value="1"> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"> is it melon ?
<li>
</ul>
</div>
And here's the resulting Javascript:
$(".checkbox").hide();
$(".question").show();
$('.question').click(function(){
$('.checkbox').hide();
$(this).next(".checkbox").toggle(10);
});
$('.test').change(function(){
if($(' input[type=checkbox]:checked').length) {
$(this).parents('.checkbox').prev('div.question').addClass("question-active");
} else {
$(this).parents('.checkbox').prev('div.question').removeClass("question-active");
}
});
EDIT: Updated with code to answer your #1 question. See updated link to jsFiddle.
put to all your questions same class .question
if you want to differentiate between questions, use ids instead
also, put to to all answers container .checkbox
then use this function which will work for questions , no matter how many you have
$('.question').click(function(){
$(".checkbox").hide();
$(this).next(".checkbox").show(10);
});

Categories