Checkboxes, javascript runs 2 times through function if I click on text - javascript

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});

The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});

Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

Related

JQuery selective hiding not working

I'm trying to create a menu where each element has its own checkbox. On selecting the sorting button ( for now it is a checkbox here ), the menu is supposed to show only the elements who already have the checkboxes active ( this is done by manually clicking the checkbox of the element and keeping it active)
Here's my HTML code
<input type= "checkbox" class="toggler" id="clicked" onclick="tclick()" >click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked()">Hello3</p>
And here is my Jquery
function but_clicked(){
// alert("Hello, checkbox clicked");
if(this.id=="active"){
this.id="inactive";
console.log(this.id);}
else{
this.id="active";
console.log(this.id);
}
}
function tclick(){
//alert("Toggler clicked");
if(this.id=="clicked"){
this.id="empty";
console.log(this.id);
}
else{
this.id="clicked";
console.log(this.id);
}
}
$(document).ready(function(){
$('.toggler').change(function(){
if($(this).is('clicked')){
$('#inactive').hide();
$('#active').show();
}
else{
$('#active').show();
$('#inactive').show();
}
})
});
But when I am setting the Click here to sort checkbox, the others are not being hidden regardless of each of their checkbox status. I feel like it's a very silly mistake that I am doing, please help.
First of all id property must be unique in the DOM, so you cannot have multiple elements with id active or inactive.
This is the main problem as $('#inactive') will only return the first element it matches (since it should be unique).
Furthermore, checkboxes have a checked property that signifies if they are checked or not so all your code could just check that instead of altering the id all the time.
Last, you should use label tags for the text instead of p so that clicking on the text will also check/uncheck the checkbox.
(oh, the .toggler checkbox actually filters, and not sorts ,the others)
So taking all issues into account you could simplify your code to
$(document).ready(function() {
$('.toggler').change(function() {
if (this.checked) {
$('.grouped').parent().hide();
$('.grouped:checked').parent().show();
} else {
$('.grouped').parent().show();
}
})
});
label{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="toggler">click here to filter</label></p>
<label><input type="checkbox" class="grouped">Hello1</label>
<label><input type="checkbox" class="grouped">Hello2</label>
<label><input type="checkbox" class="grouped">Hello3</label>
Your code can be way easier with some little tricks.
First thing, do not change IDs at run time, it's a bad practise.
Checkboxes have properties like checked, which evaluates to false or true when tested with this.checked.
<input type= "checkbox" class="toggler" id="click_to_toggle" >click here to toggle
<p class="item"><input type="checkbox" >Hello1</p>
<p class="item"><input type="checkbox" >Hello2</p>
<p class="item"><input type="checkbox">Hello3</p>
And this is the only JS you need:
$('#click_to_toggle').on('change', function(){
if( this.checked ){
$('.item').hide();
$('.item input:checked').each(function(){
$(this).closest('.item').show();
});
} else {
$('.item').show();
}
});
Working fiddle HERE
Pass in the element itself this this in the html, and just use that parameter in your javascript instead of this. Also you need to use .is with the :checked selector instead of just clicked. I also change changed .changed() to .clicked() since they are the same event in this case. You also might want to consider changing the id of inactive/active to be a class since all ids must be unique.
function but_clicked(e) {
if (e.id == "active") {
e.id = "inactive";
console.log(e.id);
} else {
e.id = "active";
console.log(e.id);
}
}
function tclick(e) {
if (e.id == "clicked") {
e.id = "empty";
console.log(e.id);
} else {
e.id = "clicked";
console.log(e.id);
}
}
$(document).ready(function() {
$('.toggler').click(function() {
if($('.toggler').is(':checked')) {
$('#inactive').hide();
$('#active').show();
} else {
$('#active').show();
$('#inactive').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="toggler" id="clicked" onclick="tclick(this)">click here to sort
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello1</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello2</p>
<p><input type="checkbox" id="inactive" onClick="but_clicked(this)">Hello3</p>

Show hide text box from a dynamic element jQuery c#

Below is my code, I am trying to hide and show dynamic elements. The problem I am having is, I only want my hidden div to only show one at a time if only I check "Other". However, the code below will show the hidden div for all number of #dynamicRows I have. so it works for initial 1st #dynamicRow added, the problem is when I have two or more #dynamicRows
$('#dynamicRow').on('click', 'input[id^=race]', function () {
if ($(this).is(":checked")) {
if ($(this).val() == "Other") {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
}
else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
}
});
Below are dynamic rows, for help purposes i am showing the html code, however, it doesn't exist on the screen, a user will click "ADD" to generate the code below. I have no problem in generating dynamic row and it is not why I am posting. note the name in my radio button is generated by c# and everything works. Again the problem is not how to create a dynamic row, it is nicely taken care of in C#.
Dynamic row one works with the above jQuery:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Dynamic row two doesn't work with the above jquery and it takes the above form events as its own, so if i check the radio button in row 2, the 1st dynamic row responds to that event and vice versa:
<div id="dynamicRow">
<input type="radio" value="No" id="race[]" name="Person[hhhhh].race"> No:
<input type="radio" value="Other" id="race[]" name="Person[hhhhh].race"> Other:
<div id="iamhidden" class="cssclass">
I appear one at a time, when other radio button is checked
</div>
</div>
Working Example
id should be unique in same document, replace the duplicate ones by a class :
<input type="radio" value="No" class="race" name="Person[hhhhhh].race"> No:
<input type="radio" value="Other" class="race" name="Person[hhhhhh].race"> Other:
Also add class and not id to the dynamic rows generated by your C# code :
<div class="dynamicRow">
Then in your js use this class :
$(".cssclass").hide();
$('.dynamicRow').on('click', '.race', function () {
if ($(this).val() == "Other") {
$(this).next(".cssclass").show();
} else {
$(this).nextAll(".cssclass").hide();
}
});
Hope this helps.
Try this:
$('body').on('click', '#dynamicRow', function () {
if ($(this).find('[value=Other]').is(":checked")) {
$(".cssclass").each(function (index) {
$(this).closest("div").show();
});
} else {
$(".cssclass").each(function () {
$(this).closest("div").hide();
});
}
});
He is a working example of what you wanted. I am generating the required with js only.
Few Points to mention
you add the event listener to the parent of the dynamic generated content.
Avoid use of IDs if they are not going to be unique and prefer classes and pseudo selectors if required
var counter = 0;
function addNewEntry(){
++counter;
var str = '<div class="dynamicRow"><input type="radio" value="No" id="race[]" name="Person[hh'+counter+'].race"> No:<input type="radio" value="Other" id="race[]" name="Person[hh'+counter+'].race"> Other:<div id="iamhidden" class="cssclass"> I appear one at a time, when other radio button is checked</div> </div>';
$('#dynamicRowContainer').append(str);
$("#dynamicRowContainer .dynamicRow:last-child .cssclass").hide()
}
$('#dynamicRowContainer').on('change', '.dynamicRow > input', function () {
if(this.value=="Other"){
$(this).siblings('.cssclass').show();
}else{
$(this).siblings('.cssclass').hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="addNewEntry()">Add New Entry</button>
<div id="dynamicRowContainer">
</div>

Javascript/jQuery: search within object

I have the following code.
<div class="days">
<input name="days-select" type="radio" value="Mon" > Mon </input>
<br>
<input name="days-select" type="radio" value="Tue" > Tue </input>
</div>
<script>
$(document).ready(function() {
radiobtn = $('.days');
radiobtn.find('value="Tue"').prop('checked', 'checked');
});
</script>
Basically, I need a two-stage search. First, find the group of radio buttons, then set one of them as checked. HOWEVER, I do not want to combine these two steps into one. Thanks for the hint.
BTW, since I am new to Javascript I would like to ask how to debug this code. For example, single-step through the script, and after "radiobtn = $('.days');" check whether "radiobtn" is assigned correctly etc. Thanks again.
HTML
<div class="days">
<input id="dayMonday" name="days-select" type="radio" value="Mon">
<label for="dayMonday">Monday</label>
<br>
<input id="dayTuesday" name="days-select" type="radio" value="Tue">
<label for="dayTuesday">Tuesday</label>
</div>
script
$(document).ready(function () {
//your .days selector is actually getting the div and not the radio button
var div = $('.days');
//maybe here you want to do some things with the div...
//...
var radiobtn = div.find('input[value="Tue"]');
//maybe here you want to do some things with the radio button...
//...
//now you have the correct element...
radiobtn.prop('checked', true);
//F12 in Chrome to see the console
console.log(radiobtn);
//notice the selector property returns: .days input[value="Tue"]
console.log(radiobtn.selector);
//so you could just do this all in one line:
$('.days input[value="Tue"]').prop('checked', true);
//see last commented line regarding this next line...
//$('.days input[value="Tue"]').click(
// function(){ console.log("you clicked Tuesday");});
//Note: you could do this:
//radiobtn.click();
//... or this:
//$('.days input[value="Tue"]').click();
//but it also fires the click event which is why you would see
//"you clicked Tuesday" in the console with the above line uncommented
});
Here's a fiddle.

Javascript display same content on each checkbox clicks?

I have multiple check boxes and i want them to display the same content when each of them is clicked. Now when I click on one check box, the content appears, but until I unclick it the next checkbox won't display any content. I want the all the contents to be displayed as long as check boxes are clicked. any tip with this.
I tried this:
function showTime(days){
var showTime = document.getElementById("time_schedules");
var days = document.getElementById("schedule");
if (days.checked) {
showTime.style.display = "Block";
}
else{
showTime.style.display = "none";
}
}
Insert some class attribute to all your checkboxes so you can select them, then capture the click event, iterate over all checkboxes and perform whatever you need to do (setting label etc).
I recommend using some javascript library such as jquery, for example:
<input type="checkbox" name="cb1" class="cb" />
<label for="cb1" class="cblabel">label1</label>
<input type="checkbox" name="cb2" class="cb" />
<label for="cb2" class="cblabel">label2</label>
$('.cb').bind('click', function() {
$('.cblabel').each(function(i,v) { v.innerHTML = 'hello'; });
});
http://jsfiddle.net/3EMyY/

Check to see if none of the checkboxes was checked in jquery

I have two checkboxes and one of the checkboxes must be checked. I can see that it's right, no syntax errors. What should be made to my code to check if none of the checkboxes were checked?
HTML :
<input type="checkbox" value="aa" class="first" name="a"> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b"> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
JavaScript:
$('button').on('click',function(){
if( $(".first:not(:checked)") && $(".second:not(:checked)") ){
$('.error').text('You must select atleast one!');
}else
$('.error').hide();
});
Example : http://jsfiddle.net/ptbTq/
Check this fiddle: http://jsfiddle.net/692Dx/
Checking code:
if($('input[type="checkbox"]:checked').length == 0) {
alert('none checked');
}
You are using selectors which do not return boolean values which is what you need when writing an if condition. Here's what you could do:
$('button').on('click',function() {
if(!$(".first").is(":checked") && !$(".second").is(":checked")) {
$('.error').text('You must select atleast one!').show();
} else {
$('.error').hide();
}
});
or if you prefer and think it could be more readable you could invert the condiciton:
$('button').on('click',function() {
if($(".first").is(":checked") || $(".second").is(":checked")) {
$('.error').hide();
} else {
$('.error').text('You must select atleast one!').show();
}
});
Also notice that you need to .show() the error message in the first case as you are hiding it in the second.
And here's a live demo.
Short:
$("input[type=checkbox]").is(":checked")
returns true if:
one of your checkboxes - from the selector ("input[type=checkbox]") - is checked.
else return false
and in your case:
$(".first, .second").is(":checked")
Do something at least one of your checkboxes is checked
Put the same class on both checkboxes and you can do something like
if ($(':checkbox.the_class:checked').length > 0) {
// at least one checkbox is checked
// ...
}
The best would be to put your checkboxes inside a div with an unique ID so you can verify all the checkboxes in there, so your code will work in all cases. Even when adding new checkboxes to the div later on.
<div id="cb">
<input type="checkbox" value="aa" class="first" name="a" /> Yes<br/>
<input type="checkbox" value="bb" class="second" name="b" /> No <br/>
<button type="submit">Go!</button>
<p class="error"></p>
</div>
Your JQuery:
$('button').click(function() {
var checked_one = $('div#cb input[type="checkbox"]').is(':checked');
if (!checked_one )
$('.error').text('You must select atleast one!');
else
$('.error').hide();
});
Live demo can be seen here: http://jsfiddle.net/ptbTq/15/

Categories

Resources