greasemonkey script to select radio button - javascript

i'm new here. i've a question related to greasemonkey.
A page contain multiple radio buttoned values and one choice is to made, this correct choice option is hidden within the page
the radio buttons are present in the form whose structure is
<form name="bloogs" action="/myaddres.php" id="bloogs" method="post" >
then the hidden field as
<input type=hidden value="abcd" name="ans">
then all the radio button values are followed as
<input type="radio" id="r1" name="opt" value="abcd"> abcd
<input type="radio" id="r2" name="opt" value="efgh"> efgh
<input type="radio" id="r3" name="opt" value="ijkl"> ijkl
and so on
thus i need the button with value=abcd be 'checked' as soon as the page loads. Thanks

There are some ways you can use:
1 You can pre-select it by putting in selected="selected" like this:
<input type="radio" id="r1" name="opt" value="abcd" checked="checked" /> abcd
2 You can use jQuery to do it easily (I don't know whether it will be applicable in terms of greasmonky though)
$(function(){
$('input[value="abcd"]').attr('checked', 'checked');
});
3 You can loop through all elements and selected the one with raw javascript
var form = document.getElementById('bloogs');
for(var i=0; i<form.elements.length; i++)
{
if (form.elements[i].type == 'radio')
{
if (form.elements[i].value == 'abcd')
{
form.elements[i].setAttribute('checked', 'checked');
break;
}
}
}
Update:
This uses jquery and selects a radio after reading the value from hidden field:
$(function(){
$('input[value="' + $('#hidden_field_id').val() + '"]').attr('checked', 'checked');
});
Or with raw javascript:
var form = document.getElementById('bloogs');
var hidden_value = document.getElementById('hidden_field_id').value;
for(var i=0; i<form.elements.length; i++)
{
if (form.elements[i].type == 'radio')
{
if (form.elements[i].value == hidden_value)
{
form.elements[i].setAttribute('checked', 'checked');
break;
}
}
}
Update 2:
As per the name, here is how you can go about:
$(function(){
$('input[value="' + $('input[name="ans"]').val() + '"]').attr('checked', 'checked');
});

I haven't done greasemonkey, but this may help:
use jQuery and do
$('[value="abcd"]').click()
Good luck.

If you're trying to use jQuery with GreaseMonkey you're going to have to get good at writing delayed and try / retry type code. You need to start with something like this:
var _s1 = document.createElement('script');
_s1.src = 'http://www.ghostdev.com/jslib/jquery-1.3.2.js';
_s1.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(_s1);
That loads jQuery into your page. Next, you set something up that operates like so:
function dojQueryStuff() {
if (jQuery == undefined) {
setTimeout(dojQueryStuff, 1000);
} else {
// In here is where all of my code goes that uses jQuery.
}
}
dojQueryStuff();
You've defined a function that'll check for jQuery's presence, and if it doesn't find it try again 1 second later. That gives the script time to load. Please note, if you don't use your own copy of jQuery the one listed in my example does not provide a $ variable. At the end of the script I have var $j = jQuery.noConflict();, so you'll access the jQuery functionality via $j or jQuery.

Related

The radio inputs from my html are not interacting well with my if statements in javascript [duplicate]

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
var value = $('input:radio[name="radiogroupname"]:checked').val();

How to get the selected radio button’s value?

I’m having some strange problem with my JS program. I had this working properly but for some reason it’s no longer working. I just want to find the value of the radio button (which one is selected) and return it to a variable. For some reason it keeps returning undefined.
Here is my code:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
Search
</form>
This works with any explorer.
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.
You also do not need to include jQuery path.
You can do something like this:
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0">Female</input>
jsfiddle
Edit: Thanks HATCHA and jpsetung for your edit suggestions.
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is
$('input[name="genderS"]:checked').val();
Not $('input[#name="genderS"]:checked').val(); anymore, which was working in jQuery 1.7 (with the #).
ECMAScript 6 version
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
Here's a nice way to get the checked radio button's value with plain JavaScript:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked property to find the checked item:
Array.from(form.elements.characters).find(radio => radio.checked);
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Edit:
As said by Chips_100 you should use :
var sizes = document.theForm[field];
directly without using the test variable.
Old answer:
Shouldn't you eval like this ?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.
Try this
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
A fiddle here.
This is pure JavaScript, based on the answer by #Fontas but with safety code to return an empty string (and avoid a TypeError) if there isn't a selected radio button:
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:
Line 1: get a reference to the control that (a) is an <input> type, (b) has a name attribute of genderS, and (c) is checked.
Line 2: If there is such a control, return its value. If there isn't, return an empty string. The genderSRadio variable is truthy if Line 1 finds the control and null/falsey if it doesn't.
For JQuery, use #jbabey's answer, and note that if there isn't a selected radio button it will return undefined.
First, shoutout to ashraf aaref, who's answer I would like to expand a little.
As MDN Web Docs suggest, using RadioNodeList is the preferred way to go:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector, which works fine too:
const form = document.querySelector('form[name="somename"]')
However, selecting the radios directly will not work, because it returns a simple NodeList.
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements Method. Aside from all the input Nodes, the RadioNodeList also includes a property value, which enables this simple manipulation.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [Click Find without selecting any Radio]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs' answer into a general function:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name. Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question. you can write your javascript like so:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.
I realize this is extremely old, but it can now be done in a single line
function findSelection(name) {
return document.querySelector(`[name="${name}"]:checked`).value
}
I like to use brackets to get value from input, its way more clear than using dots.
document.forms['form_name']['input_name'].value;
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.
Note that it shows a snapshot of the form values. If you change the value, you need to recreate the FormData object. If you want to see the state change of the radio, you need to subscribe to the change event change event demo
Demo:
let formData = new FormData(document.querySelector("form"));
console.log(`The value is: ${formData.get("choice")}`);
<form>
<p>Pizza crust:</p>
<p>
<input type="radio" name="choice" value="regular" >
<label for="choice1id">Regular crust</label>
</p>
<p>
<input type="radio" name="choice" value="deep" checked >
<label for="choice2id">Deep dish</label>
</p>
</form>
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML:
<form action="#n" name="theForm" id="yourFormId">
var value = $('input:radio[name="radiogroupname"]:checked').val();

Use javascript comma separated variable to repopulate a forms checkbox values when page loads

I have a jquery variable that is storing a comma separated list of id names. I need help writing something in jquery that separates that variable and uses those values to populate a forms checkbox values when the page loads.
so my jquery variable is $storedFormValues that is a comma separated list of values "checkbox1, checkbox, etc."
and my form
<form name="formname" id="formid">
<input type='checkbox' class='catcheck' id='checkbox1' value='checkbox1' name='catselect' />Checkbox 1
<input type='checkbox' class='catcheck' id='checkbox2' value='checkbox2' name='catselect' />Checkbox 2
<input type="submit" name="submit" value="Submit" />
</form>
Any help would be greatly appreciated!
This should do it:
var $storedFormValues = "checkbox3,checkbox5";
$(function() {
$.each($storedFormValues.split(","), function(intIndex, objValue) {
$("#" + objValue).attr("checked", "true");
});
})
See the fiddle: http://jsfiddle.net/xNyww/
Not jQuery, but plain JS: You can use split to separate the values in an array:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
I do not know what do the csv looks like. If it's only one line, e.g:
checkbox1, checkbox7, checkbox2
then use it as:
var checkboxes[] = csvString.split(",");
for (str in checkboxes) {
$("#"+str).yourActionHere();
}
If it's several lines (one per checkbox) , e.g.
checkbox1, true
checkbox2, false
then :
var checkboxes[] = csvString.split(/\r\n|\r|\n/);
for (str in checkboxes) {
var data = str.split(",");
$("#"+data[0]).yourActionHere(data[1]);
}
Live Demo
var storedFormValues = "checkbox1, checkbox3, checkbox4";
$('#formid').children('input[id^=checkbox]').each(function() {
if (storedFormValues.indexOf($(this).attr('id')) != -1) {
$(this).attr('checked', 'checked');
}
});
Note: If you plan on having more than 10 checkboxes, I recommend naming them with a leading zero (ex: checkbox01) otherwise you may run into an issue where checkbox1 matches against checkbox11.

How to Uncheck A radio button

I have two forms, one with a radio button that users must select to edit.
[form name="A"]
<li>[input type="radio" name="BookItem" value="1" /]</li>
<li>[input type="radio" name="BookItem" value="2" /]</li>
<li>[input type="radio" name="BookItem" value="3" /]</li>
[form]<p>
After "BookItem" is selected from form (A) I call the $("#EditFormWrapper").load("callEditData.cfm? ID="+ID); function to load the second form (B)
<div id="EditFormWrapper"><div></p>
<!---// begin dynamic form generated by external file callEditData.cfm //--->
[form id="editForm" name="B"]
<ul class="hourswrapper">
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs1" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs1" /> 2 Hours PM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="AM2Hrs2" /> 2 Hours AM</li>
<li><input type="checkbox" id="TOR2Hours" class="TOR2Hours" name="TOR2Hours" value="PM2Hrs2" /> 2 Hours PM</li>
</ul>
[input type="image" src="images/submit-btn.gif" id="addBTN" name="addBTN" class="buttons" alt="SubmitRrequest" /]
[input type="image" src="images/cancel-btn.gif" id="editBTNcancel" name="editBTNcancel" class="buttons" alt="Cancel Request" /]
[/form]
<!---// end dynamic form from external file //--->
I want to uncheck the radio button on form (A) when user click on cancel button (editBTNcancel) in form(B).
Here's my script:
$("#editBTNcancel").live("click", function(event){
event.preventDefault();
$("#EditFormWrapper").slideUp("fast").empty();
//$('.TOR2Hours').removeAttr('checked');
$('.TOR2Hours').attr('checked', false);
});
I hope I clearly state my problem, any suggestion would be greatly appreciated!
you can access form like so ...
var exampleForm = document.forms['form_name'];
then loop through the form
for( var i=0; i<exampleForm.length; i++ ){
alert( exampleForm[i].type );
}
you can test for checked like so ...
if( exampleForm[i].checked )
to deselect the checked radio button try ...
exampleForm[i].checked=false;
the final code would look like this ...
var exampleForm = document.forms['form_name'];
for( var i=0; i<exampleForm.length; i++ ){
if( exampleForm[i].type ) == 'radio' && exampleForm[i].checked == true ){
exampleForm[i].checked = false;
}
}
I'm not sure exactly what you want but you might try using a reset input.
<input type='reset' />
Seeing as this is pretty much the easiest DOM task there is and works in every scriptable browser, I suggest not using the jQuery methods for it:
$(".TOR2Hours")[0].checked = false;
The other thing that ocurs to me is whether your selector is correct. Did you mean to select a set of elements by class or should it be an ID selector?
Your selector is simply wrong.
If you want to uncheck the radio button from first form you should use $('input[name="BookItem"]') and not $('.TOR2Hours') :
$("#editBTNcancel").on("click", function(event){
$("#EditFormWrapper").slideUp("fast").empty();
$('input[name="BookItem"]').attr('checked', false);
});
As far as which method to use to uncheck radio buttons, The following 3 methods should all work:
$('input[name="BookItem"]').attr('checked', false);
$('input[name="BookItem"]').removeAttr('checked');
$('input[name="BookItem"]').prop('checked', false);
However, check out jQuery's docs on jQuery prop() for the difference between attr() and prop().
I just discovered a great solution to this problem.
Assuming you have two radios that need to be able to be checked/unchecked, implement this code and change what's necessary:
var gift_click = 0;
function HandleGiftClick() {
if (document.getElementById('LeftPanelContent_giftDeed2').checked == true) {
gift_click++;
memorial_click = 0;
}
if (gift_click % 2 == 0) {document.getElementById('LeftPanelContent_giftDeed2').checked = false; }
}
var memorial_click = 0;
function HandleMemorialClick() {
if (document.getElementById('LeftPanelContent_memorialDeed2').checked == true) {
memorial_click++;
gift_click = 0;
}
if (memorial_click % 2 == 0) { document.getElementById('LeftPanelContent_memorialDeed2').checked = false; }
}
:) your welcome
I use this way to solve your problem in ASP.net, check this..
radioButton.InputAttributes["show"] = "false";
string clickJs = " if(this.show =='true'){this.show ='false'; this.checked = false;}else{this.show='true'; this.checked = true;};";
radioButton.Attributes["onClick"] = clickJs;
In asp.net, you can use this way to add an attribute. And you can also to add an attribute manually to the radioButton, and do the function(clickJs) to change the ckecked attributes!!!

can the name of a input tag be changed with javascript?

I want to know if its possible to change the name of the input tag with javascript or jquery, for example in this code :
<input type="radio" name="some_name" value="">
I want to change the some_name value when user select this radio button.
the reason what i want to do this is described here : How might I calculate the sum of radio button values using jQuery?
Simply elem.name = "some other name" or elem.setAttribute("name", "some other name") where elem is the element you want to alter.
And to do that on selection, use the onchange event:
<input type="radio" name="some_name" value="" onchange="if(this.selected) this.name='some other name'">
And to apply that behavior to every radio button with that name:
var inputElems = document.getElementsByTagName("input");
for (var i=inputElems.length-1; i>=0; --i) {
var elem = inputElems[i];
if ((elem.type || "").toLowerCase() == "radio" && elem.name == "some_name") {
elem.onchange = function() {
if (this.selected) {
this.name = "some other name";
}
};
}
}
But using jQuery for that is quite easier.
The jQuery way
$('input:radio[name="some_name"]').attr('name', 'new name');
Gumbo has the vanilla JavaScript way covered
Yes, you can change the name of any element with javascript. Keep in mind though that IE 6 and 7 have trouble with submitted forms where the input elements have been tinkered with in javascript (not sure if this exact case would be affected).
$('input:radio[name="some_name"]').attr('name', 'new_name');
Edit: To change it only when it is selected, here is the code for that:
$("input:radio[name='some_name']").click(function() {
if ($(this).attr('checked')) $("input:radio[name='some_name']").attr('name', 'new_name');
else $("input:radio[name='some_name']").attr('name', 'some_name');
});
Sure. If jQuery is your poison, this should do the trick:
$("input[name=some_name]").attr("name", "other_name");
I came up with this:
<input type="radio" name="some_name" value="" id="radios">
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#radios").click(function()
{
$(this).attr("name", "other_name");
});
});
</script>
Trying to change the name attribute of a radio button will cause strange, undesirable behavior in IE.
The best way to handle this is to replace the old radio button with a new one. This post may help you. If you are using jQuery, you can do it with the replaceWith function.
More information about changing name attributes in IE.

Categories