I'm trying to add text to a div based on which radio button a user checks, but it ends up firing the "else" block no matter which attribute is checked, and displaying "female" every time.
Please help!
<input type="radio" name="gender" class="gender" id="male" value="male">Male<br />
<input type="radio" name="gender" class="gender" id="female" value="female">Female<br />
$(".gender").change(function () {
if ($("#male").attr("checked")) {
$("#content").text("male");
}
else {
$("#content").text("female");
}
});
Use .prop('checked') rather than .attr('checked'). The latter is based on the HTML attribute which will always be false because it is not in the DOM. .prop can be used to check property changes that may not be visible in the DOM.
http://jsfiddle.net/Xxuh8/
Your code would have worked until jQuery 1.8 or lesser. http://jsfiddle.net/Dnd2L/
In latest versions .attr is for the attributes which was defined in the HTML and .prop is mapped to the properties of the element which is dynamic and returns the current value.
http://jsfiddle.net/Dnd2L/1/
More information about attr and prop - https://stackoverflow.com/a/5876747/297641
You don't particularly need an if since your radio buttons are grouped and no multiple choices are possible.
You might want to use this instead:
$(".gender").change(function () {
$("#content").text($(this).val());
});
JSFiddle: http://jsfiddle.net/3Lsg6/
or if your radios don't have a class use
$("input[name='gender'][checked='checked']").val();
to get the value of the checked radio. To change which is checked, put the value of the cbx you want checked in val() i.e., ...val("male");
Related
How can I make a checkbox always be checked, with Jquery 1.4.2 ?
This is my html output from the struts application:
<input type="checkbox" name="helloThere" value="on">
I tried:
$(document).ready(function() {
$('#helloThere').attr('checked', 'checked');
});
JSFIDDLE
http://jsfiddle.net/96p4zg9w/ this shows the current code, I would need the checkbox to load checked.
The props property is not available in JQUERY 1.4.2
your jquery selector is wrong.
You are trying select an element with 'helloThere' id, but your input has not an id attribute.
You can add this attribute to your input field or change jquery selector.
Try one of this tow solutions:
<input type="checkbox" name="helloThere" id="helloThere" value="on">
or
$(document).ready(function() {
$("input[name='helloThere']").attr('checked', 'checked');
});
You need to put your JavaScript inside $(document).ready(). This ensures all of the content you might want to touch has been loaded before you try to change it.
In your scenario then, you would need:
$(document).ready(function() {
$('#helloThere').attr('checked', 'checked');
});
Edit: Your checkbox doesn't have an ID. You need to add an ID of "helloThere" for $('#helloThere') to pick it up. Your fiddle also needs to have jQuery loaded using the menu on the left. Here's a working version: http://jsfiddle.net/96p4zg9w/1/
Check this jsfiddle for a working example of how you can do it using javascript.
If you want to use versions of jQuery below 1.5, you need to do it this way:
$("#checkbox").attr("checked", true);
or
$("#checkbox").attr("checked", "checked");
If you want to select element using the name instead of id, use:
input[name='helloThere']
Hope it useful!
It can be done in three ways. You can use checked in input that will always stay checked.
<input id="myId" type="checkbox" name="name" checked>
Using prop and assume input id is myId
$(document).ready(function() {
$(#myId).prop('checked', true);
});
Before jQuery 1.6 using attr
$(document).ready(function() {
$(#ID).attr('checked','checked');
});
<lable>this will always be checked, even you try to uncheck</lable>:
<input type="checkbox" checked onclick="return false;">
I'm generating an HTML input with checked="false", however the checkbox is showing up checked.
I did the following in the javascript console and can't quite figure out whats going on. The resulting HTML after using .prop() to set the value to false looks the same except now the checkbox is not checked on the form.
> $(':input[checked]').prop('checked');
< true
> $(':input[checked]')
< [
<input type="checkbox" class="caseVal" checked="false">
]
> $(':input[checked]').prop('checked',false);
< [
<input type="checkbox" class="caseVal" checked="false">
]
I'm under the impression that I should just be setting checked="checked" OR not including the checked property at all if its false is that best practice? Either way I'd like to know what's going on in the above code.
Don't put checked="false"
You only put checked="checked" for valid XHTML, otherwise you'd do
<input type="checkbox" checked>
The browser doesn't care what value is assigned to checked attribute, as soon as it sees checked in the checkbox input tag, it's flagged as checked.
$(document).ready(function () { $(e).prop("checked", false);}
// "e" refers to button element
How to Uncheck in this case, example my code is: (see below)
if(previousHighlightedCheckbox!=null) {
console.log(sent.id, previousHighlightedCheckbox); // current checkbox and previous check box values are different.
document.getElementById(previousHighlightedCheckbox).checked = false; // still this does not uncheck previous one
}
Here is the documentation I'm looking at : Example Adding Radio Buttons
It says:
KO will set the element to be checked if and only if the parameter value equals the radio button node’s value attribute
Which I have done in this: jsfiddle
self.radioValue = ko.observable(1);
and the HTML:
<input type="radio" name="teloremail" value="1" data-bind="checked: radioValue" />
For me, this doesn't automatically set the radio to checked
Any reason for this?
The type of the radio button node’s value attribute is string, so you need to store the value as string also in your observable:
self.radioValue = ko.observable("1");
Demo JSFiddle.
The example also uses a string: "almond".
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.
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');
}