Is there a way I can deselect a radio button on click of it? I'm using AngularJS 1.4.4. Using one of the solutions I found here, I've added an ng-click event, but it doesn't work.
foreach (var part in Model.ChildParts)
{
<div class="radio col-md-12">
<input type="radio"
id="#Model.FieldName"
name="#Model.FieldName"
ng-model="gPA(#Model.Id).value"
value="#((part as BaseInputPartVM).GetStringValue())"
ng-click="uncheck($event, #Model.Id)" />
</div>
}
In the controller, I have the following code. The below "if" condition is always turning to true and hence everytime I try selecting a radio, it is always set to false. My goal is to deselect a radio button on click of it, if it is already selected.
$scope.uncheck = function (event, partId) {
if ($scope.gPA(partId).value == event.target.value)
$scope.gPA(partId).value = false
}
The radio button, by design, is not supposed to be unselected. I would consider using a checkbox instead. https://ux.stackexchange.com/questions/13511/why-is-it-impossible-to-deselect-html-radio-inputs
Following code worked:
foreach (var part in Model.ChildParts)
{
<div class="radio col-md-12">
<input type="radio"
id="#Model.FieldName"
name="#Model.FieldName"
ng-model="gPA(#Model.Id).value"
value="#((part as BaseInputPartVM).GetStringValue())"
ng-mouseup = "setPreviousSelectedValue(#Model.Id)"
ng-click="uncheck($event, #Model.Id)" />
</div>
}
<input type="hidden" id="previousRadioSelection" name="previousRadioSelection" ng-model="previousRadioSelection" value="" />
In the controller,
//set previous selected value of radio button
$scope.setPreviousSelectedValue = function (partId) {
$scope.previousRadioSelection = $scope.gPA(partId).value;
}
//uncheck radio button
$scope.uncheck = function (event, partId) {
if ($scope.previousRadioSelection == event.target.value)
$scope.gPA(partId).value = null;
}
Related
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>
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>
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.
:)
Here is sample http://jsfiddle.net/HhXGH/57/
I am clicking radio button by jquery but knockout.js does not recognize it.Still it shows first clicked value.
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
Preferred flavor of spam:
<div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
<div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
<div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable('cherry')
};
ko.applyBindings(viewModel);
$(':radio:last').click();
alert(viewModel.spamFlavor())
This because Knockout is subscribing to the click events of checked radio/checkbox elements only. If you checkout the binding handler code for checked. It does this.
var updateHandler = function() {
var valueToWrite;
if (element.type == "checkbox") {
valueToWrite = element.checked;
} else if ((element.type == "radio") && (element.checked)) {
valueToWrite = element.value;
} else {
return; // "checked" binding only
responds to checkboxes and selected radio buttons
}
So in order to get your code to work do this.
$(':radio:last').prop('checked', true).click();
However if the goal is to check the last value, why not just do
viewModel.spamFlavor("msg");
This would achieve the same result.
Hope this helps.
Adding $(':radio:last').attr('checked', true); in addition to triggering click makes it work for me:
http://jsfiddle.net/jearles/HhXGH/61/
I have two different jsFiddles since I'm not sure exactly what your after.
The first jsFiddle will respond via alert when the last radio button is manually clicked.
The second jsFiddle is your posted /57/ jsFiddle without the alert.
Using an alert or console.log with a function will actually invoke that function. That said, after you have manually set the .click() to the last radio button, it's inadvertently reset back to cherry since that's the default value.
RE-EDIT: The second jsFiddle now includes alert written in syntax that doesn't invoke the function & now uses shorted markup.
How do I call onclick on a radiobutton list using javascript?
How are you generating the radio button list? If you're just using HTML:
<input type="radio" onclick="alert('hello');"/>
If you're generating these via something like ASP.NET, you can add that as an attribute to each element in the list. You can run this after you populate your list, or inline it if you build up your list one by one:
foreach(ListItem RadioButton in RadioButtons){
RadioButton.Attributes.Add("onclick", "alert('hello');");
}
More info: http://www.w3schools.com/jsref/event_onclick.asp
To trigger the onClick event on a radio button, invoke the click() method on its DOM element:
document.getElementById("radioButton").click()
using jQuery:
$("#radioButton").click()
AngularJs:
angular.element('#radioButton').trigger('click')
I agree with #annakata that this question needs some more clarification, but here is a very, very basic example of how to set up an onclick event handler for the radio buttons:
window.onload = function() {
var ex1 = document.getElementById('example1');
var ex2 = document.getElementById('example2');
var ex3 = document.getElementById('example3');
ex1.onclick = handler;
ex2.onclick = handler;
ex3.onclick = handler;
}
function handler() {
alert('clicked');
}
<input type="radio" name="example1" id="example1" value="Example 1" />
<label for="example1">Example 1</label>
<input type="radio" name="example2" id="example2" value="Example 2" />
<label for="example1">Example 2</label>
<input type="radio" name="example3" id="example3" value="Example 3" />
<label for="example1">Example 3</label>
The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.
The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.
This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.
I think all of the above might work. In case what you need is simple, I used:
function checkRadio(name) {
if (name == "one") {
console.log("Choice: ", name);
document.getElementById("one-variable-equations").checked = true;
document.getElementById("multiple-variable-equations").checked = false;
} else if (name == "multiple") {
console.log("Choice: ", name);
document.getElementById("multiple-variable-equations").checked = true;
document.getElementById("one-variable-equations").checked = false;
}
}
<div class="radio-buttons-choice" id="container-3-radio-buttons-choice">
<input type="radio" name="one" id="one-variable-equations" onclick="checkRadio(name)"><label>Only one</label><br>
<input type="radio" name="multiple" id="multiple-variable-equations" onclick="checkRadio(name)"><label>I have multiple</label>
</div>
Try the following solution
$(document).ready(function() {
$('.radio').click(function() {
document.getElementById('price').innerHTML = $(this).val();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="variant">
<label><input type="radio" name="toggle" class="radio" value="19,99€"><span>A</span></label>
<label><input type="radio" name="toggle" class="radio" value="<<<"><span>B</span></label>
<label><input type="radio" name="toggle" class="radio" value="xxx"><span>C</span></label>
<p id="price"></p>
</div>
The other answers did not work for me, so I checked Telerik's official documentation it says you need to find the button and call the click() function:
function KeyPressed(sender, eventArgs) {
var button = $find("<%= RadButton1.ClientID %>");
button.click();
}