How to change a radio button value [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to check a radio button with jQuery?
How to change a radio button value.
jQuery('input:radio[name=search][id=search-damages]').checked = true;
i have tried this but it is not working
<input type="radio" name="search" id="search-vehicle" value="search-vehicle" checked>
<input type="radio" name="search" id="search-damages" value="search-damages">

How to change a radio button value?
checked property doesn't change the value of radio button. note that checked property is one the DOM INPUT Element properties and not one of the jQuery object properties(by selecting an element using jQuery, a jQuery object is created). If you want to change this property you should first convert the jQuery object into a DOM Element object.
$('#search-damages')[0].checked = true;
or use the jQuery object's prop() method:
$('#search-damages').prop('checked', true)
If you want to change the value of an input you can use the jQuery val() method:
$('#search-damages').val('new value');

I'm a fan of "use jQuery when reduce complexity, use JS in other cases", so I would go for:
$("#search-damages")[0].checked = true;
Otherwise, if you prefer use jQuery syntanx, you could use:
$("#search-damages").prop("checked", true);
See: http://api.jquery.com/prop/

Try this:
$('#search-damages').attr('checked','checked');

Related

How to access data-attributes of HTML elements using javascript [duplicate]

This question already has answers here:
PURE JS get selected option data attribute value returns Null
(4 answers)
Closed 4 years ago.
I have a dropdown menu in my form. Each option has 3 data-attributes associated with it. When one option is selected I call a function that sets the values of hidden html objects to the value of each data attribute so I can pull that information on the next page. However, the value of the data-attributes keeps coming up as "undefined". What am I doing wrong?
<script>
function change_charge(x)
{
alert (x.dataset.amount);
}
</script>
<select name="description" id="description" onchange="change_charge(this)">
<option value="Test" data-amount="10.00" data-type="charge" >TEST </option>
</select>
I expect the alert to say the value of data-amount but instead it says "undefined"
I have also tried:
alert (x.getAttribute('data-amount'));
But that returns "null".
x is the <select>, not the <option>. The select has no data- attributes.
If you want the option, use
var option = x.options[x.selectedIndex];
console.log(option.dataset.amount);
This answer shows how you can get a custom attribute from JavaScript.
Summary: you can use getAttribute()
x.getAttribute("data-amount");
EDIT:#James also makes a good point, which is x is the selector, not the option. Thus you will probably need a combination of our two answers:
x.options[x.selecetdIndex].getAttribute("data-amount");

Check a radio button with javascript

For some reason, I can't seem to figure this out.
I have some radio buttons in my html which toggles categories:
<input type="radio" name="main-categories" id="_1234" value="1234" /> // All
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category
The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234 to be set checked radio button, because this is the default checked radio button.
I have tried versions of this (with and without jQuery):
document.getElementById('#_1234').checked = true;
But it doesn't seem to update. I need it to visibly update so the user can see it.
Can anybody help?
EDIT: I'm just tired and overlooked the #, thanks for pointing it out, that and $.prop().
Do not mix CSS/JQuery syntax (# for identifier) with native JS.
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
If you want to set the "1234" button, you need to use its "id":
document.getElementById("_1234").checked = true;
When you're using the browser API ("getElementById"), you don't use selector syntax; you just pass the actual "id" value you're looking for. You use selector syntax with jQuery or .querySelector() and .querySelectorAll().
Today, in the year 2016, it is safe to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):
document.querySelector("input[name=main-categories]:checked").value
Easiest way would probably be with jQuery, as follows:
$(document).ready(function(){
$("#_1234").attr("checked","checked");
})
This adds a new attribute "checked" (which in HTML does not need a value).
Just remember to include the jQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
By using document.getElementById() function you don't have to pass # before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo:
JSFiddle
I was able to select (check) a radio input button by using this Javascript code in Firefox 72, within a Web Extension option page to LOAD the value:
var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
if (response["reload_mode"] == "Periodic") {
document.querySelector('input[name=reload_mode][value="Periodic"]').click();
} else if (response["reload_mode"] == "Page Bottom") {
document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
} else {
document.querySelector('input[name=reload_mode][value="Both"]').click();
}
});
Where the associated code to SAVE the value was:
reload_mode: document.querySelector('input[name=reload_mode]:checked').value
Given HTML like the following:
<input type="radio" id="periodic" name="reload_mode" value="Periodic">
<label for="periodic">Periodic</label><br>
<input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
<label for="bottom">Page Bottom</label><br>
<input type="radio" id="both" name="reload_mode" value="Both">
<label for="both">Both</label></br></br>
It seems the item.checked property of a HTML radio button cannot be changed with JavaScript in Internet Explorer, or in some older browsers.
I also tried setting the "checked" attribute, using:
item.setAttribute("checked", ""); I know the property can be set by default,
but I need just to change the checked attribute at runtime.
As a workarround, I found another method, which could be working. I had called the item.click(); method of a radio button. And the control has been selected. But the control must be already added to the HTML document, in order to receive the click event.

How can I check which of the two radio button is checked in javascript/jquery? [duplicate]

This question already has answers here:
How can I know which radio button is selected via jQuery?
(40 answers)
Closed 9 years ago.
How can I check which of the two radio button is checked in javascript/jquery in order to get the value of the input considering the fact that, in the HTML, both of them are by default unchecked (no checked attribute is added)
<input type="radio" name="AS88" value="true" required>
<input type="radio" name="AS88" value="false">
The following code does not work:
var elements = document.getElementsByName("AS88");
for (var i=0, len=elements.length; i<len; ++i) {
if (elements[i].checked) {
alert(elements[i].value)
}
};
EDIT:
Solutions with :checked in jquery such as:
$('input[name="AS88"]:checked').val();
always return undefined
use attribute selector along with :checked selector and .val() to get the value of the checked input element with name AS88
$('input[name="AS88"]:checked').val()
Demo: Fiddle

Checkbox irregularities with jQuery

Here's some html:
<form>
<input type="checkbox" id="check-123" />
<input type="text" id="text-123" onchange="doSomething('123')" />
</form>
And here's some javascript:
function doSomething(key)
{
var textbox = $('#text-'+key);
var checkbox = $('#check-'+key);
checkbox.attr('checked',(textbox.val()!="") );
}
My goal here is to check the checkbox anytime there's a value in the text box, and uncheck when that value is removed. This appears to work fine in the html (I can see checked="checked" being added to the checkbox), but the checkbox only appears checked the first time something is entered in the textbox.
Why would a checkbox show unchecked even if checked="checked" was added to the html?
Use element properties rather than attributes to change their state via javascript
checkbox.prop('checked',(textbox.val()!="") );
From the jQuery docs on .attr() and .prop():
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
The emphasis is jQuery's own. Only the checked property will reflect and control the checkbox's current state. The checked attribute shouldn't be used to control the checkbox state.
consider something like:
function doSomething(el) {
el.form['check-' + el.name.split('-')[1]].checked = !!el.value;
}
<form>
<input type="checkbox" name="check-123">
<input type="text" name="text-123" onchange="doSomething(this)">
</form>
I've seen some funny things with the checked attribute in IE8 and lower. In some cases I've had to set both the property and the attribute, even though modern browsers seem to be okay with just adjusting the property:
checkbox.prop('checked',textbox.val()!="");//property
Note, the following is only necessary if you come across any browser related inconsistencies.
if(textbox.val()!="")
{
checkbox.attr('checked','checked');
}
else
{
checkbox.removeAttr('checked');
}

Toggle Disabled Attribute on Input Based on Checkbox in jQuery [duplicate]

This question already has answers here:
How do i disable a submit button when checkbox is uncheck?
(7 answers)
Closed 8 years ago.
I have a checkbox that is unchecked by default and a disabled input by default.
<label class="checkbox span3"><input type="checkbox"> I am a full-time student.</label>
<input class="inputIcon span3" id="disabledInput" type="text" placeholder="Enter School Name" disabled>
I have full control over the class and id names and the site uses jQuery so can use that or plain javascript if needed.
If a user checks the box, then the "disabled" attribute should be removed from the following input. If the user unchecks it should become disabled again.
Found a several similar questions on StackOverflow but none seem to be this exact use case.
You have to assign id to checkbox to bind the click to particular checkbox,
Live Demo
<input type="checkbox" id="chk">
$("#chk").click(function(){
$("#disabledInput").attr('disabled', !this.checked)
});
First give your checkbox an id
<input id='cbFullTime' type="checkbox">
Then in its click handler, fetch the textbox, and set its disabled property to the inverse of the current value of the checkbox's checked property:
$('#cbFullTime').click(function() {
var cbIsChecked = $(this).prop('checked');
$('#disabledInput').prop('disabled', !cbIsChecked);
});
Note that, while using attr and removeAttr will work (assuming you're not using exactly jQuery 1.6), using the prop function is a bit simpler, and a bit more correct. For more information, check out this link
Try the below
$(".checkbox").find("checkbox").click(function() {
$('#disabledInput').prop('disabled', $(this).prop('checked'));
});

Categories