I want to disable the radiobutton the second time it is clicked..I want to put some code in the head..that when a radiobutton is clicked the second time,, it isnt marked anymore..
I want to check and uncheck the radiobutton with each click.
Note: I generate 20 radiobuttons dynamically
Take into account that it is a Radiobutton that is run on the server:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.radiobutton.aspx
UPDATE: This is the only event that the RadioButton (asp WebControl run at="server") has:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
var rad = (CheckBox)sender;
if (rad.Checked)
{
rad.Checked = false;
}
}
I can uncheck it after each post back..but unless a post back doesnt happen, i cant select and deselect it.. Thats the problem!! :(
I think you should keep with the standard use of RadioButtons, by saying this - use CheckBoxes instead, and clear all checkboxes if a different one is clicked...so when a checkbox is clicked the second time the standard uncheck will occur.
if i get you right then
all u need is a flag attribute of how many times u have clicked on the radio button and each time u click the radio the attribute increased by 1 and check the attribute every click if its 2nd time then disable the radiobutton
so you need to generate ur radiobuttons like this
<input type='radio' onclick='radioClick(this);' how_many_clicked='0' id='whatever id u need' name='whatever name u need' />
and create ur function in the head like the following
function radioClick(e) {
var flag = e.getAttribute('how_many_clicked');
var times = Number(flag);
times += 1;
e.setAttribute('how_many_clicked', times.toString())
if (times > 1) {
e.checked = false;
e.setAttribute('how_many_clicked', "0");
}
else {
e.checked = true;
}
}
Id create an empty array. For every radiobutton you create, add its ID to the array as the key and set its value to 0. This will be the count for the specific button. Whenever a radiobutton is clicked, check the buttons ID against the array, if its less than 2, increment it. If not, disable the current button.
EDIT : didn't realize you were checking if it was already checked, thoguht it was the number of times checked.
$("#id").is(":checked")
Should suffice
Another note ...if all you're doing is disabling an element from being accessed by the user, you should handle this event on the client side. You'll be using unnecessary server callback for functionality easily achievable via javascript. Use jquery click event handlers which can be generic enough for you not to have to use identifiers, making the job that much easier.
Cheers
Related
I did an exclusive menu of 2 input checkboxes : each input checkbox corresponds to a different case : (Player Vs Computer) and (Player1 Vs Player2) and each case is associated to 2 buttons (which work as I want).
My issue is that I would like to add a functionality, i.e enable to uncheck the current checked box by clicking on the current checkbox (this one which is already checked).
For the moment, I have to click directly on the other input checkbox to uncheck the current one; I would like to get the both functionalities.
Here's the current code which handles these 2 exclusive input checkbox :
// Check input checked
checkBoxState = $('#'+gameType+'').find('.game').prop('checked');
// Set oneButtonClicked to no for restore
$('#formGame').prop('oneButtonClicked', 'no');
// Handling input.game
$('#'+gameType+'').find('.game').prop('checked', !checkBoxState);
//$('#'+gameType+'').siblings().find('.game').prop('checked', checkBoxState);
// Set pointer-events to all for formGame
$('#formGame').css('pointer-events', 'all');
// Handling button.btn
$('#'+gameType+'').find('.btn').css('pointer-events', 'none');
$('#'+gameType+'').siblings().find('.btn').css('pointer-events', 'all');
$('#'+gameType+'').find('.btn').prop('disabled', checkBoxState);
$('#'+gameType+'').siblings().find('.btn').prop('disabled', !checkBoxState);
gameType is the current type of game (Player Vs Computer or Player1 Vs Player2).
input.game represent the input checkboxes
button.btnrepresent the 2 buttons available for each ìnput.game.
How can I add this functionality, i.e uncheck by clicking on current checked, or uncheck by clicking directly on the other checkbox?
Update 1
A click on a checkbox should automatically set its negation to the other checkbox.
Update 2
I tried to adapt the solution given by #CodeAt30 by doing simply:
gameType = (gameType == 'PlayerVsComputer') ? 'Player1VsPlayer2' : 'PlayerVsComputer';
$('#'+gameType).find('.game').prop('checked', !$('#'+gameType).find('.game').prop('checked'));
This solution works for uncheck the current checkbox and check its siblings().
But now, I can't select directly the other checkbox unlike to the JS Fiddle: Uncheck checkbox by clicking directly on the other no-checked "input checkbow"
https://jsfiddle.net/m059rr88/
HTML
<input id="one" type="checkbox"></input>
<input id="two" type="checkbox"></input>
Javascript:
let afterFirstClick = false;
$("input").click(function(){
let passiveCheckboxId = "one";
if($(this).attr("id") === "one"){
passiveCheckboxId = "two"
}
if(afterFirstClick){
$("input#" + passiveCheckboxId).prop("checked", !$("input#" + passiveCheckboxId).prop("checked"));
}
afterFirstClick = true;
});
Easier than you might think:
$('input.game').click(function(){
$('input.game').not(this).removeAttr('checked');
});
What is does is assign a click handler to the checkboxes that removes the checked attribute from all other boxes. The status of the current box is handled by the native checkbox code, so checking and unchecking will work normally.
... or ...
$('input.game').click(function(){
if (this.checked) {
$('input.game').not(this).removeAttr('checked');
} else {
$('input.game').not(this).trigger('click');
}
});
This code will allow you to swap checkboxes by clicking on either one. Once a box is checked there is no way to uncheck it, like a radio button.
I have an application that pairs a textbox with a checkbox. The user can check the checkbox, which auto-populates the textbox with a specific dollar amount. If they uncheck the checkbox, this sets the textbox's value to zero. They can also enter a dollar amount in the textbox and an onblur event handler toggles the checkbox.
The problem comes when they enter a dollar amount in the textbox and then check the checkbox with a mouse click. This fires the onblur event, which automatically toggles the checkbox, then recognizes the mouse click, setting the dollar amount back to zero.
My solution was to disable the checkbox on textbox focus, then enable the checkbox on textbox onblur event.
This works well in Firefox and Chrome, but fails miserably in Internet Explorer. FF and Chrome ignore any mouse click on the checkbox when it is disabled. This means that the onblur event does not fire, when the user clicks on the disabled checkbox after entering a dollar amount in the textbox. The checkbox stays disabled. They have to click elsewhere on the page for it to be enabled.
In Internet Explorer, the onblur event fires when the user clicks on the disabled checkbox, and the checkbox recognizes the click, right after it is checked with the onblur event handler, unchecking the checkbox, setting the textbox value back to zero.
I need a better solution. How do I get Internet Explorer to act like FF and Chrome, ignoring any click on a disabled checkbox. Or, is there a more elegant solution altogether?
Example Code:
<input type=textbox id=textbox1 onFocus=CheckboxDisable('pairedWithTextBox1'); onBlur=CheckboxEnable('pairedWithTextBox1');>
<input type=checkbox id=pairedWithTextBox1>
Javascript code:
function CheckboxDisable(id){
document.getElementById(id).disabled = true;
}
function CheckboxEnable(id){
document.getElementById(id).disabled = false;
}
Short of a real solution. .. you COULD set a data attribute on the check box on focus of the text element, then check for it on the cb on click event and override the default action. ..
Aside from a possibly confusing user interface design (can't say for sure since you genericized the problem too much), the problem is that the checkbox and textbox are both views of the same model.
The model is the dollar amount.
The textbox is a view of the
actual dollar amount.
The checkbox is a view that indicates
whether the amount is 0 or something else.
Your current design is complex, which is not by itself a bad thing, because the event handlers for the text box onblur and checkbox onclick are also controllers of the model. (This is a bit of an oversimplification; the controller also consists of the browser and all the JavaScript code.)
Here is a solution that helps illustrate this fact. It works based on the business rule that once the user has modified the value in the textbox (to a non-zero value) changing the state of the checkbox from unchecked to checked will not update the model (or the textbox view).
var txtAmount = document.getElementById('txtAmount');
var chkAmount = document.getElementById('chkAmount');
var defaultValue = 0;
var model = defaultValue;
function UpdateViews() {
if (model === 0) {
chkAmount.checked = false;
}
txtAmount.value = model.toFixed(2);
}
function UpdateModel(val) {
// update model when view changes
model = parseFloat(val) || defaultValue;
UpdateViews();
}
UpdateViews(); // set initial view
txtAmount.onchange = function () {
UpdateModel(this.value);
};
chkAmount.onclick = function () {
if (this.checked) {
// when user checks the box, only update model if not yet modified
if (model === defaultValue) UpdateModel(55); // hardcoded default of $55
} else {
UpdateModel(defaultValue);
}
};
<input type='text' id='txtAmount' />
<input type='checkbox' id='chkAmount' />
If I were in your case, I will put an If-Else in the click event of the checkbox...
Something like:
if (!String.IsNullOrEmpty(textBox1.Text) | textBox1.Text != "0")
{
// Do nothing since textbox1 already has a value greater than zero
}
else
{
// Enter amount in textbox
}
Try this..
function CheckboxDisable(id){
$("#id").attr("disabled", "disabled");
}
function CheckboxEnable(id){
$("#id").removeAttr("disabled");
}
I need to be able to tell if the checkboxes are checked to do some basic validation. Problem: I don't have access to the PHP generating this. There is no class added, or the basic checked=checked that most forms have. What's the easiest way to target the checked boxes?
http://www.inpresence.in/event-registration?ee=4
EDIT: freak out!! here's the code, i just need to target the checked boxes, everything else is working. the :checked method of jquery uses checked=checked within the checkbox, which isn't there.
$(document).ready(function(){
//when the submit button is clicked...
$("input.btn_event_form_submit").click(function(){
//find the value of the drop down with one evening or four evenings
var priceOption = $("#price_option-4").val();
//match a string ending with "one evening" as the first numbers will be randomly generated by php
var oneEvening = /^\d{2}\|One Evening$/.test(priceOption);
//match a string ending with "four evenings" as the first numbers will be randomly generated by php
var fourEvenings = /^\d{2}\|Four Evenings$/.test(priceOption);
//HOW DO I GET THE CHECKED BOXES?!
var checkedBoxCount = $('#dates-1351733097 .valid').is(':checked').length;
//if one evening is selected make sure the checked boxes count does in fact equal one
if(oneEvening && checkedBoxCount != 1){
//if it doesn't alert the user and return false
alert('You must select one date');
return false;
}
//if one evening isn't selected, four is. make sure the count does indeed in 4
else if (fourEvenings && checkedBoxCount != 4){
//if it doesnt alert the user and return to the form
alert('You must select four dates');
return false;
}
//else, everything checks out!
else {
return;
}
});
});
Using this JavaScript code you can check if a checkbox is checked:
var isChecked = document.getElementById("my-checkbox").checked;
Or using jQuery:
var isChecked = $('#my-checkbox').is(':checked');
EDIT: Try this and tell me if it works:
var checkedBoxCount = $('#dates-1351733097 .valid:checked').length;
Have you tried using jquery to resolve this?
http://jquery-howto.blogspot.co.uk/2008/12/how-to-check-if-checkbox-is-checked.html
$('#edit-checkbox-id').is(':checked');
use the jquery :checked selector. http://api.jquery.com/checked-selector/
This will give you a boolean in javascript of what you want:
document.getElementById("Nov.12-4_1").checked
You can view source and find the elements to view whatever id's they have.
Other answers: the OP didn't specify that he wanted a jquery answer. If he hasn't used jquery for anything up to this point. I think adding it just for this would be a tad overkill.
I have 50 rows of data and i want users to give them points by 1 to 50. I put dropdown boxes near them with options 1/50. But all i want is when a user selects 15(for example) for a row, 15 will be deleted from all other select tags of other rows. I am not as good as you in JavaScript. How can i accomplish this?
Hi casablanca i couldnt make he script you sent work. I need it to work on just one select tag so i give select tag an ID and an ID for the form too. I edit the scripts getElementsByTagName with getElementsByTagID (select tag's ID) to effect only one select tag. But the function doesnt triggered?
This might not be a very good idea, because it is very difficult for the user to modify choices -- for example, if I want to give 15 to a different option, I need to change the old one to something else and then change the new one to 15. Also, once all points have been assigned, it's impossible to make any changes because all options are gone.
A better idea would be to let the user do whatever he/she wants and then validate the form in the end. You could do that like this:
function validate() {
var used = []; // This array stores already used options
var rows = document.getElementById('myForm').getElementsByTagName('select');
for (var i = 0; i < rows.length; i++) {
var points = rows[i].value;
if (used[points]) {
// This value was already used
alert('Please choose a different value.');
rows[i].focus();
return false;
} else {
// This value was not used before; mark it as used now
used[points] = true;
}
}
return true;
}
And call this function in the onsubmit handler of your form:
<form id="myForm" onsubmit="return validate();">
EDIT1: id -> class
give each option the class of the number it is
<option class="15">15</option>
<option class="16">16</option>
etc.
Then jquery can remove() an item by class
$('.15').remove();
obviously have to do an on change and get the value just set. "remove()" is nice in this instance because I believe it will yank every instance of that class.
EDIT3: upon further consideration the above method would be further complicated by the need to not remove the "selected" option. Not going to figure out the exact method but I think changing the class from "15" to "selected15" with a $(this).append() or something of the sort before calling the remove would get the job done fairly safely.
EDIT2:
As noted by casblanca below this is not an ideal user interface at all for this type of input. You may want to look into this: http://www.utdallas.edu/~jrb048000/ListReorder/
Allows user to drag and drop items in a list to reorder them. Much more natural.
I have a dropdown select list on my page of class="TypeFilter".
I have a jQuery event that fires when a value in that list is selected.
$(".TypeFilter").change(function()
{
// Extract value from TypeFilter and update page accordingly
));
I now have to add another list to the page, and I want to implement functionality which will prevent the .change(function() from running unless both are selected.
In both lists the first option in the list is some text instructing the user to select one of the items, so I was thinking of just writing some logic to test that both lists have a selected index greater than 0.
I think this is a touch unclean though, especially considering that other pages that have a TypeFilter use the same logic.
Is there any nifty functionality in jQuery that can do this?
edit I should specify that the user needs to be able to update the page by selecting either dropdown, so I can't put the onchange on the second element and test that the first element has a selected value, as suggested in one of the answers
If you bind the same event to all dropdowns, you can get a collection of all the dropdowns and check that all of them are selected. Example:
$('.Dropdown').change(function(){
var elements = $('.Dropdown');
if (
elements.filter(function(){
return this.selectedIndex > 0;
}).length == elements.length
) {
// all dropdowns are selected
}
});
As you partly mention, put the onchange on the second element and test that the first element has a selected value before you fire off any logic.
Use bind instead, and as the eventdata, send a function that checks that either that both are selected or that the other is selected. Untested code:
function checker() {
// test your conditions
}
$(".TypeFilter").bind('change', {test: checker}, function(event)
{
if (event.data.test && event.data.test()) {
// Extract value from TypeFilter and update page accordingly
}
));
This way the other pages that use the same function will not notice any changes.