Javascript display same content on each checkbox clicks? - javascript

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/

Related

How to hide and unhide form fields based on a radio button?

I'm trying to implement a radio button, which if clicked should get more options for the user to fill in.
Here's what I've tried.
<script>
function addmentor() {
if ( document.getElementById("type_Computer").checked ) {
document.getElementById('nextSetOfComputerOptions').style.display = "";
} else {
document.getElementById('nextSetOfComputerOptions').style.display = "none";
}
}
</script>
<input type="radio" name="type" id="type_computer" value="Computer" onClick="addmentor()">Add Mentor</button>
<div id="nextSetOfComputerOptions" style="display:none;">
.
.
</div>
The above code doesn't work. When I am clicking the radio button, nothing happens, the part of the form is always hidden.
EDIT: I originally misunderstood the question and have now adjusted my answer.
Additionally, I have also included a function that will hide your input if another radio button is clicked.
See the snippet below:
//your checkbox
var checkbox = document.getElementById("type_computer");
//your div
var inputDiv = document.getElementById("nextSetOfComputerOptions");
//function that will show hidden inputs when clicked
function addmentor() {
if (checkbox.checked = true) {
inputDiv.style.display = "block";
}
}
//function that will hide the inputs when another checkbox is clicked
function hideInputDiv() {
inputDiv.style.display = "none";
}
<input type="radio" name="type" id="type_computer" value="Computer" onChange="addmentor();" ">Add Mentor</input>
<input type="radio" name="type" onClick="hideInputDiv();">Other radio input</input>
<div id="nextSetOfComputerOptions" style="display: none;">
<input placeholder="PC"></input>
<input placeholder="Mac"></input>
</div>

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>

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

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.

Checkboxs disabled with jquery not working as intended

i have some checkboxes that are displayed by doing a select in database that represents tables of a restaurant. Those tables that are already reserved i add them an disabled attribute. The problem with my script is that i only want to select three tables max and that means i need to add disabled atribute to the other to block them. and when i want to deselect those 3 already selected i need to remove the disabled attribute. Problem is that it removes the attribute from all tables even those that are reserved and selected from database.
Here is my script:
JSFIDDLE HERE
<script type="text/javascript">
var $checks = $(".table").change(function () {
if ($checks.filter(":checked").length<3)
{
$(".formular").toggle($checks.filter(":checked").length>0);
$checks.not(":checked").removeAttr("disabled");
}
else
{
$checks.not(":checked").attr("disabled", "disabled");
}
});
</script>
Added a class .ignore to the input disabled from start and in js binding change event only to checkboxes without the ignore class as mentioned by #lolka_bolka
HTML
<input type="checkbox" class="bowling ignore" disabled/>
<input type="checkbox" class="bowling ignore" disabled/>
<input type="checkbox" class="bowling"/>
<input type="checkbox" class="bowling"/>
JS
var $checks = $(".bowling:not(.ignore)").change(function () {
if ($checks.filter(":checked").length < 3) {
$(".formular").toggle($checks.filter(":checked").length > 0);
$checks.not(":checked").removeAttr("disabled");
} else {
$checks.not(":checked").attr("disabled", "disabled");
}
});
:not(foo){} will match anything that isn't foo, including html and
body. Source
Demo

Checking a different checkbox hides input field

I have an input field that only shows when the option "Other" is checked. The input field fades out when I uncheck the "Other" checkbox, but I would also like the input field to fade out say if, instead of unchecking the "Other" checkbox I check another checkbox of the same group. Therefore, the "Other" input field should not be visible unless "Other" is checked. I have the javascript partially working, but when I check another checkbox the "Other" input field stays visible.
HTML
<input type="checkbox" id="residence_check" name="found"/>
<label for="residence_check">
Residence
</label>
<input type="checkbox" id="tradeshow_check" name="found"/>
<label for="tradeshow_check">
Tradeshow
</label>
<input type="checkbox" id="office_check" name="found"/>
<label for="office_check">
Office Building
</label>
<input type="checkbox" id="check_other" value="found_other" name="found"/>
<label for="check_other">
Other
</label>
<input type="text" id="check_input" placeholder="Other"/>
Javascript
$('#check_other').change(function() {
if($(this).is(":checked")) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
});
From what I gather from your use case is that you don't want to use checkboxes, but radio buttons. If that is the case, this would be a good way to implement what you want:
http://jsfiddle.net/AeP58/1/
$('input[type=radio]').on('change', function() { //event on all radio buttons
if($(this).attr('id') == 'check_other' && $(this).prop('checked')) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
});
If you do want checkboxes, you could change the code a bit and probably get what you want.
If you want to have some fun with checkboxes you could try this:
function showHideOtherInput() {
console.log($(this)[0]==$('#check_other')[0]);
var shouldShow=$('[id$="_check"]:checked').length===0 && $('#check_other').prop('checked');
console.log(shouldShow);
if(shouldShow) {
$('#check_input').fadeIn();
} else {
$('#check_input').fadeOut('fast');
}
}
$('#check_input').hide(); //since nothing is selected at this point just hide the input
$('#check_other').change(showHideOtherInput);
//for each XXXX_check checkbox trigger the show or hide function
$('[id$="_check"]').each(function(ix,el){$(el).change(showHideOtherInput)});
Hope this works for you.
:)

Categories

Resources