Checking a different checkbox hides input field - javascript

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.
:)

Related

Changing text with a toggle function

I made my checkmark input have a toggle function to show/hide an input box, but what I am trying to do is get two different options of text to fade in with the toggle choice ( and obviously since the checkmark is true on page load, for the appropriate text to show on load too).
When the checkbox input is true, I want it to say,Enabled.
When the checkbox input is false, I want it to say, Turned Off.
How can I do this?
// Checkbox checked and input disbaled when page loads
$('#TYemailCheck').prop('checked', true);
// Enable-Disable text input when checkbox is checked or unchecked
function TYenable(trigger, target) {
$(trigger).on('change', function () {
$(target).toggle();
});
}
TYenable("#TYemailCheck", "#TYemailEnabled");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="TYemailCheck">
<div id="TYemailEnabled">
<input type="text">
</div>
You should include two divs that contain your texts and toggle between them according to checkbox change.
// Checkbox checked and input disbaled when page loads
$('#TYemailCheck').prop('checked', true);
$('#turnedOff').hide();
// Enable-Disable text input when checkbox is checked or unchecked
function TYenable(trigger, target) {
$(trigger).on('change', function () {
$(target).toggle();
$('#enabled, #turnedOff').fadeToggle(500);
});
}
TYenable("#TYemailCheck", "#TYemailEnabled");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="TYemailCheck"><span id="enabled">Enabled</span><span id="turnedOff">Turned Off</span>
<div id="TYemailEnabled">
<input type="text">
</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.

Radio Button On select or unselect Javascript Jquery

When i select the radio button then i want to hide one div and when i uncheck the radio button then i want to show that div . please if anyone know. I want to hide div on check the radio button.
<input type="radio" id="fix" name="price" checked="checked" value="fix">
<div id="hour">
<input type="text" name="rs"/>
</div>
You can use the change() function from jQuery that triggers when the selector has been changed. Then just compare the val() with your value, and take action.
$("input[type='radio']").change(function() {
if ($(this).val() == "fix") {
// show div
} else {
// hide div
}
});
You have single radio button you probably want to use checkbox instead. As single radio button could not be unchecked.
Live Demo
Html
<input type="checkbox" id="fix" name="price" checked="checked" value="fix">
Javascript
$('#fix').change(function(){
$('[name=rs]')[0].style.display = this.checked ? 'block' : 'none';
});
$("input[type='radio']").change(function() {
if ($(this).val() == "fix") {
document.getElementById("hour").style.display = '';
} else {
document.getElementById("hour").style.display = 'none';
}
});
Simple solution.
We can't uncheck a radio button when there is only one.
So, change the input type to checkbox. Then you can use this CSS:
:checked + #hour{
display: none;
}
Working Fiddle

How to identify whether or not a radio has been checked programmatically?

I have a form page in which the user can enter an ID, and the corresponding profile data is pulled from mysql and displayed in the form so that the user may edit it.
One element is a group of radios, so you may select a year level (ie "1", "2", "3", etc).
When a user provides an ID, an AJAX call is made to pre-populate the form with data, including selecting the appropriate radio.
problem:
The user must select a year level to submit the form. I check this with a verifyForm() method:
function verifyForm() {
if( !document.addStudentForm.elements["yearLevel"].checked ) {
alert( "You must select a year level before submitting." );
return false;
}
};
I expect this to check yearLevel and, if an option isn't selected, alert/return false.
However, when the yearLevel radio is pre-selected by the AJAX data, this is still behaving as if the user did not select a radio.
The radio is populated by js via the following code:
document.getElementById( "yearLevel_<?=$student['student']->get('yearLevel')?>" ).checked = true;
edit: Here is the relevant HTML.
<form name="addStudentForm" action="validation/updateStudentValidate.php" method="POST" onSubmit="return verifyForm()">
<input type="radio" value="1" name="yearLevel" disabled id="yearLevel_1" /> 1
<input type="radio" value="2" name="yearLevel" disabled id="yearLevel_2" /> 2
<input type="radio" value="3" name="yearLevel" disabled id="yearLevel_3" /> 3
<input type="radio" value="4" name="yearLevel" disabled id="yearLevel_4" /> 4
<input type="radio" value="5" name="yearLevel" disabled id="yearLevel_5" /> 5
<input type="radio" value="6" name="yearLevel" disabled id="yearLevel_6" /> 6
</form>
Question:
How can I have my javascript properly identify whether or not the radio has been checked, regardless of if it was selected by hand or programmatically?
Taken from this StackOverflow post and adapted for this example and for speed, you can have this in your AJAX success return:
var radios = document.getElementsByName('yearLevel'),
i = radios.length,
isChecked = false;
while(i--){
if (radios[i].checked) {
isChecked = true;
break;
}
}
Then when the function is called:
function verifyForm(){
if(!isChecked){
alert( "You must select a year level before submitting." );
return false;
}
};
This is assuming that you don't have any other items with the name yearLevel in your HTML.
This will actually return the value, I guess I'm unsure if you are wanting to see a specific item checked, or just that they have been checked at all. This function will do both.

Using jQuery, hide a textbox if a radio button is selected

I have 2 radio buttons, what I want is if a user selects the top radio button then hide a textbox.
Not sure how to bind an event to a radio button.
Something like this:
<input type="radio" name="foo" value="top" />
<input type="radio" name="foo" value="bottom" />
And in jQuery:
$('input[name=foo]').click(function() {
if($(this).val() == "top") {
$('#textbox').hide();
} else {
$('#textbox').show();
}
});
click because change doesn't seem to work correctly on IE.
This will allow you to add the event to a selected radio, in case your radio's do not have the same name.
$('checkbox-selector').click(function() {
if ($(this).is(':checked')) {
$('textbox-selector').hide();
}
else {
$('textbox-selector').show();
}
});

Categories

Resources