Headaches with radios in Jquery - javascript

I have 2 radios:
<input id="a_15_0" type="radio" value="abc" name="a_15"/>
<input id="a_15_1" type="radio" value="xyz" name="a_15"/>
Both are unselected. I have only the name of the radio, i.e a_15, but not the IDs.
1) How can I get the value of the selected option of this radio? E.g if the user clicked 'xyz', how can I get it? Right now I'm using:
var val=$('[name="a_15"]').val();
Which always gives abc even when xyz is selected.
2) How can I get xyz to be selected through javascript, without knowing the ID of the radio which says xyz? Doing:
$('[name="a_15"]').val('xyz');
Changes the value of both radios to xyz rather than selecting the one whose value had been xyz.
Do I need to use document.myForm.a_15.value? Would that work consistently?

1)
try
var val = $('input[name=a_15]:checked').val();
jQuery docs on checked pseudo-class
2) the only solution I found is
$('input[name=a_15][value=xyz]').get(0).checked=true

Have you tried using the val() in conjunction with the :checked selector?
$('[name="a_15"]:checked').val();
As for setting the selection based on the value, you may have to perform a multiple attribute tests?
$('[name="a_15"][value="xyz"]').get(0).checked = true;

There are many ways of selectors in jQuery; id, class, etc..I believe this will do the job, not tested:
var val= $("input[name=a_15]:checked").val();
if you know the name of the form then this will definitely do it
var val= jQuery('#radio_form input:radio:checked').val();

you have the correct code here:
to run
to edit
the correct form is:
$("input[name='a_15']:checked").val();
as you can test using the links above

Related

Checking a Checkbox through JS in browser

I'm looking to set multiple values and checkboxes on a webpage using JS.
I'm able to do values using
document.querySelector('input[name="date"]').value = '1/1/2000';
document.querySelector('form').submit();
...that's simple enough. There are multiple checkboxes that may or may not need to be checked. What is the process to check a box through the console? Here is a sample of one of them when it is checked:
input id="FormView1_cb_EXAMPLE" type="checkbox"
name="FormView1$cb_EXAMPLE" checked="checked"
You can do this by targeting the checked attribute of the item after selecting it with either querySelector or getElementByID. Then simply set it to true for checked.
document.querySelector('#steve').checked=true
<input id="steve" type="checkbox">
If you need to do it to multiple and they all have the same class name, you can use querySelectorAll and a forEach/for loop and set each one to true (checked) using that method. (this would only work if your list of which ones need to be checked conditionally is constant)
I hope your job looks
var input = document.querySelector('#FormView1_cb_EXAMPLE').checked;
console.log(input)
<input id="FormView1_cb_EXAMPLE" type="checkbox">

Selection from dropdownlist javascript event

I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.

Radio button value regardless of selected input

I have this code:
<input type="radio" name="pay" id="payid" value="banktransfer"> Bank Transfer <br/>
<input type="radio" name="pay" id="payid" value="paypal"> PayPal <br/> <br/>
I try:
var sample = $('#payid').val()
alert(sample);
Why I have still banktransfer? (regardless of the selected input)?
The id must be unique. Radios need the same name for their on-off functionality to work, but each must have a unique id. You could, for instance, have "payid1" and "payid2"
The ID attribute must be unique across the page. In your case jQuery is just picking the first element with that ID and returning that value. This code will get you the selected value.
jQuery("input[name=pay]:checked").val();
Try
var sample = $("[name=pay]:checked").val()
You need to specify which one of the radio buttons you want, you can get the correct one (the checked one) by using the :checked selector. You also need to use the name attribute selector, because id needs to be unique and JQuery will only ever return the first match.
This should work for you:
var sample = $('[name="pay"]:checked').val();
alert(sample);
Here is a working example

How to disable enable a checkbox based on another checkbox?

Following code is generated by a for loop.
<form action="saveresponse.php" method="POST" name="mainForm">
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="01.jpg" disabled />Special<br />
<input class="cbox_yes" type="checkbox" name="yes[]" value="02.jpg"
onclick="spenable()" /> OK
<input class="cbox_sp" type="checkbox" name="sp[]" value="02.jpg" disabled />Special<br />
etc etc upto n times...
Now, what I want is that on page load, all the sp[] checkboxes should be disabled and enabled only if their corrosponding yes[] checkbox is checked by user.
Javascript code I am using: (Just to check if JS is capturing the states of yes[] checkbox?
function spenable(){
var yes = document.mainForm.yes[].value;
if (yes == true)
//alert("true");
document.mainForm.yes[].value = checked;
else
//alert("false");
document.mainForm.yes[].value = checked;
};
};
But I am not getting any alert (Neither Yes, Nor No).
So, is yes[] (Square brackets) in second line is incorrect? Or my if/else condition is wrong in JS?
P.S. All the questions here at SO or on Google deal with only one case/pair.
P.S. If required, I can change yes[] to yes1, yes2, yes3 etc and corresponding sp1, sp2, sp3 where 1,2,3 is $i of For loop, but then how will I capture/refer to it in JS?
_UPDATE:_
The flow/conditions are(Clarification):
Initially Special checkbox will be disabled and OK checkbox will be unchecked.
Then if user checks Ok, Special gets enabled.
If user want, he can tick Special.
If, later, user changes mind and untick the OK, Special should be unticked as well as disabled again.
I used jQuery here for the sake of simplicity.
$("input[name='yes[]']").change(function() { //When checkbox changes
var checked = $(this).attr("checked");
$(this).next().attr("disabled", !checked); //The next checkbox will enable
});​ // or disable based on the
// checkbox before it
Demo: http://jsfiddle.net/DerekL/Zdf9d/
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/1/
Update
It will uncheck the first checkboxes when the Special checkbox is checked.
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/2/
More Updates
Here's the demo:
Pure JavaScript: http://jsfiddle.net/DerekL/Zdf9d/3/
jQuery: http://jsfiddle.net/DerekL/Zdf9d/4/
Little note: document.querySelectorAll works on all modern browsers and IE8+ including IE8. It is always better to use jQuery if you want to support IE6.
You can't use yes[] as an identifier in the Javascript, so you have to access the field using the name as a string:
document.mainForm["yes[]"]
This will not return a single element, it will return an array of elements. Use an index to access a specific element:
document.mainForm["yes[]"][0]
The value of the checkbox will always be the value property, regardless of whether the checkbox is selected or not. Use the checked property to find out if it's selected:
function spenable() {
var yes = document.mainForm["yes[]"][0].checked;
if (yes) {
alert("true");
} else {
alert("false");
};
}
To access the specific checkbox that was clicked, send the index of the checkbox in the event call:
<input class="cbox_yes" type="checkbox" name="yes[]" value="01.jpg" onclick="spenable(0);" /> OK
Use the index in the function:
function spenable(idx) {
var yes = document.mainForm["yes[]"][idx].checked;
var sp = document.mainForm["sp[]"][idx];
sp.disabled = !yes;
}
If you are open to using jQuery:
$('input[type="checkbox"]').click(function(){
var obj = $(this);
obj.next('.cbox_sp').attr({'disabled':(obj.is(':checked') ? false : 'disabled')});
});
This solution will assign an onclick event handler to all checkboxes and then check to see if the corresponding "special" checkbox should be disabled or not. It also sets the default checked state to true.
Working Example: http://jsfiddle.net/6YTqC/

jQuery way to handle select lists, radio buttons and checkboxes

When I handle HTML form elements with jQuery, I always end up with an ugly mix of jQuery syntax and plain JavaScript like, e.g.:
function doStuff($combo){
if( $combo.get(0).options[$combo.get(0).selectedIndex].value=="" ){
var txt = "";
}else{
var txt = $combo.get(0).options[$combo.get(0).selectedIndex].text;
}
var $description = $combo.closest("div.item").find("input[name$=\[description\]]");
$description.val(txt);
}
Are there standard jQuery methods to handle typical operations on elements like <select>, <input type="radio"> and <input type="checkbox">?
With typical, I mean stuff like reading the value of the selected radio button in a group or replacing elements in a selection list. I haven't found them in the documentation but I admit that method overloading can make doc browser kind of tricky.
Update
Thanks everyone. Once in the right track, I figured out myself the rest of the stuff. E.g., I can handle a <select> list like any other DOM tree:
$("select")
.empty()
.append('<option value="">(Pick one)</option><option value="a">Option A</option><option value="b">Option B</option>');
Yes, you should be able to simplify your code a lot. Here are a few examples of working with form elements:
<input type="text">
$(':text') // select all text boxes
$('input#example').val(); // gets value of a text box
<input type="checkbox">
$(':checkbox') // selects all checkboxes
$('input.example:checked') // selects all ticked checkboxes with class 'example'
$('#example').is(':checked'); // true if checkbox with ID 'example' is ticked
<input type="radio">
$(':radio') // selects all radio buttons
$(':radio:checked').each( function() {
$(this).val(); // gets value of each selected radio button
});
$('input:radio[name="asdf"]'); // gets particular group of radio buttons
<select>
$('select#example').change( function() {
// this part runs every time the drop down is changed
$(this).val(); // gets the selected value
});
See also http://api.jquery.com/category/selectors/form-selectors/ for more selectors.
Since you want the text and not the value, use .text() for that <option> (find it using the :selected selector), like this:
function doStuff($combo){
var txt = $combo.children("option:selected").text();
$combo.closest("div.item").find("input[name$=\[description\]]").val(txt);
}
If you wanted the value part of <option value="4" selected>Four</option> then you could use .val(), like this:
var val = $combo.val();
For <select> elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).
For selects you can use the val() method. In case of multiple select the val() method returns an array of the selected options.
For checkboxes and radio you can grab all the selected checkboxes using the :checked selector.
You'll find all the details as well as examples at the jQuery site : http://api.jquery.com/val/
For Select elements, you should be able to just get the value (with .val()). For radio buttons, you can do this:
$('input:radio[name=whatever]:checked').val()
Checkboxes are similar:
$('#checkboxId:checked').val()
Those two will be null if things are unchecked (though with radio buttons it's kind-of evil for that to be the case).
edit see Nick's answer for getting the text of a selected option instead of the value (basically call .text() instead of .val()).
Ignore formatting....i havent done that..;)

Categories

Resources