Calling onclick on a radiobutton list using javascript - javascript

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();
}

Related

Dynamic Checkbox selector in jquery

I have a series of dyanmic checkboxes which are creating at runtime but with differnt Ids like this (patter is same)
ModellingTagID_1201
ModellingTagID_1202
ModellingTagID_1203
ModellingTagID_1204
I want to know that above check box change or not? how can i make a dyanmic event with dynamic selector? so that i can get that particular checkbox value has changed? is this kind of thing possible?
$jqLib("#ModellingTagID_*").change(function(){
var lastState =$jqLib("#ModellingTagAlternativePlanning").prop("disabled");
$jqLib("#ModellingTagAlternativePlanning").prop("disabled",!lastState);
});
you can apply same class to all those checkboxes
<li><input type="checkbox" id="yourcbid1" name="x" value="1" class="yourcbclass" /> cb1</li>
<li><input type="checkbox" id="yourcbid2" name="x" value="1" class="yourcbclass" /> cb2</li>
and then you can make function for it's change event like this.
$(function(){
$('.yourcbclass').on('change', function() {
if($(this).is(':checked'))
{
//do your stuff here
}
});
});
see if this helps..
Very simple using this way:--
$("#envoyer").click(function(e) {
var myArray = [];
$(":checkbox:checked").each(function() {
myArray.push(this.value);
});
if(myArray == ''){
alert('Please check');
}else{
alert("Checked: " + myArray.join(","));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
one<input type="checkbox" name='checkbox0' value="one_name" checked>
two<input type="checkbox" name='checkbox1' value="one_name1">
three<input type="checkbox" name='checkbox2' value="one_name2">
<input type="button" id="envoyer" value="Envoyer Reponse" />
</body>
</html>
From what I understand, your issue is to distinguish the unique id of the checkbox, which is being, changed. To achieve this, you can simply add a common class to all the elements, alongwith unique random ids.
cb_1<input type="checkbox" class="someclass" id='ModellingTagID_1201' value="value_1" checked>
cb_2<input type="checkbox" class="someclass" id='ModellingTagID_1202' value="value_2">
cb_3<input type="checkbox" class="someclass" id='ModellingTagID_1203' value="value_3">
And then you can simply bind a change event listener to the common class, and fetch the value of the random id, which has been changed, from inside the event listener.
$(document).ready(function(){
$('.someclass').on('change', function() {
alert($(this).attr("id"));
});
});

Validate form with checkboxes using Javascript

I have a set of checkboxes in a form as follows:
<form name="form1" onsubmit="return window.Validate()" method="post" action="myprog.cgi">
<div id="filters">
<input name="One_f" type="checkbox"> No. 1<br>
<input name="Two_f" type="checkbox"> No. 2<br>
<input name="Three_f" type="checkbox"> No. 3<br>
</div>
<div id="Colors">
<input name="Red" type="checkbox"> Red<br>
<input name="Blue" type="checkbox"> Blue<br>
<input name="Green" type="checkbox"> Green<br>
</div>
<div id="Button">
<input name="Submit" value="Submit" type="submit">
</div>
</form>
I want to write a function Validate in Javascript that would see whether any of the checkboxes in the div id
filters is checked. If none of them is checked, it should show an alert box and prevent the cgi from
getting executed. The checkboxes in the div filters all have their names ending in _f, if that helps.
How do I write such a function?
Here's a jQuery solution, I'll add a plain JS one in a few moments.
$('form[name="form1"]').on('submit', function(e) {
if(!$('#filters input:checkbox:checked').length) {
e.preventDefault();
alert('Please select at least one filter.');
}
});
This codes does not require the onsubmit inline event.
Since you are not familiar with jQuery I'll explain it more thoroughly:
$('form[name="form1"]') creates a jQuery object containing all elements matching the selector. It would be faster if you gave your form id="form1" and used $('#form1')
.on() binds an event handler. The first argument passed to the callback function is a wrapped event object which we'll need to prevent the form from being submitted if necessary.
$('#filters input:checkbox:checked') selects all checked checkboxes that are children of #filters. :checkbox and :checked are pseudo-selectors which will only match checkboxes that are currently checked)
.length is the number of elements in the jQuery object - if nothing is checked it's zero
e.preventDefault(); prevents the default action of the event from being executed, i.e. the form will not be submitted.
Usually you would wrap the whole code with $(document).ready(function() { ... }); to make it execute as soon as the DOM is ready - if you put the <script> tag containing the code after the </form> tag of your form, it's not necessary though.
If you really want a plain JS solution, try this:
function Validate() {
var container = document.getElementById('filters');
var checked = 0;
for(var i = 0; i < container.childNodes.length; i++) {
var elem = container.childNodes[i];
if(elem.tagName == 'INPUT' && elem.type == 'checkbox' && elem.checked) {
checked++;
}
};
if(checked) {
return true;
}
alert('Please select at least one filter.');
return false;
}

Knockout does not recognize manually click

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.

If radio button checked add new form element using dom?

How do I use DOM in Javascript to check if a radio button is checked and then if so add new form elements to datesettings?
//Radio buttons
<input type="radio" id="dateoption" name="dateoption" value="1">
<input type="radio" id="dateoption" name="dateoption" value="2">
//Add new form elements
<span id="datesettings"></span>
Im currently reading a Javascript book but its not helping me understand. If someone could help me with this example then maybe the penny will drop. Thanks for your time.
Check out this page:
It explains the process so you understand why you're doing it a certain way, AND it gives good example code.
http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_radio_button.php3
You would write a function to do the check, like this:
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.appendChild(...);
}
else if(o2.checked) {
eSettings.appendChild(...);
}
}
But, you have to make sure to assign your radio buttons unique id values. You can duplicate names to group the radio buttons, but for any element, the id should be unique.
<form id="TestForm">
<!-- //Radio buttons -->
<input type="radio" id="dateoption1" name="dateoption" value="1">Text 1</input>
<input type="radio" id="dateoption2" name="dateoption" value="2">Text 2</text>
<!-- //Add new form elements -->
<span id="datesettings"></span>
</form>

How to clear radio button in Javascript?

I have a radio button named "Choose" with the options yes and no. If I select any one of the options and click the button labeled "clear", I need to clear the selected option, using javascript. How can I accomplish that?
You don't need to have unique id for the elements, you can access them by their name attribute:
If you're using name="Choose", then:
With recent jQuery
$('input[name=Choose]').prop('checked',false);
With old jQuery (<1.6)
$('input[name=Choose]').attr('checked',false);
or in pure JavaScript
var ele = document.getElementsByName("Choose");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
Demo for JavaScript
If you do not intend to use jQuery, you can use simple javascript like this
document.querySelector('input[name="Choose"]:checked').checked = false;
Only benefit with this is you don't have to use loops for two radio buttons
This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)
document.getElementById("Choose_Yes").checked = false;
document.getElementById("Choose_No").checked = false;
An example of how the radio buttons should be named:
<input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
<input type="radio" name="Choose" id="Choose_No" value="2" /> No
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
Wouldn't a better alternative be to just add a third button ("neither") that will give the same result as none selected?
In my case this got the job done:
const chbx = document.getElementsByName("input_name");
for(let i=0; i < chbx.length; i++) {
chbx[i].checked = false;
}
Simple, no jQuery required:
clear
<script type="text/javascript">
function clearChecks(radioName) {
var radio = document.form1[radioName]
for(x=0;x<radio.length;x++) {
document.form1[radioName][x].checked = false
}
}
</script>
YES<input type="radio" name="group1" id="sal" value="YES" >
NO<input type="radio" name="group1" id="sal1" value="NO" >
<input type="button" onclick="document.getElementById('sal').checked=false;document.getElementById('sal1').checked=false">
if the id of the radio buttons are 'male' and 'female', value reset can be done by using jquery
$('input[id=male]').attr('checked',false);
$('input[id=female]').attr('checked',false);
Somtimes i have to remove attribute checked from inputs type="radio" :
let el = document.getElementById('your_input_id');
el.checked = false;
el.removeAttribute('checked');
<form>
<input type="radio" name="btn"> Item1
<input type="radio" name="btn"> Item2<br>
<input type="reset">
</form>
This could work..

Categories

Resources