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

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

Related

How can I have a checkbox as selected in Javascript?

I have some items to be selected,they are checkboxes with their certain titles in a table. I want to onclick on an item(I mean each "td") then the function do its job but besides I want the checkbox of that selected "td" t be checked. How can I do it with javascript?
note:I am learning javascript so please don't answer with a jquery solution.
the code below is an example of each items
<td id="1" onclick="chb('1')" ><input type="checkbox" />title</td>
This is pure JS to select a check box. You need to give your check box an Id (for example 'check1') and run the below code inside the function you call in the click event.
document.getElementById("check1").checked = true;
Actually I didn't understand what you told. But i think you want the checkbox to be checked already. Then use checked in <input> Like this : <input type="checkbox" checked>or You can use document.getElementById("check1").checked = true;

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.

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

How to change a radio button value [duplicate]

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');

Radio button on/off trigger works only one way

So this is the dumbest thing I've struggled with in awhile. I cannot get the state of a simple radio button set to toggle something on the page.
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" id="completeSw" name="completeSw" value="0" checked="checked"/>No<br/>
So you can see here an extremely simple yes/no radio button set to toggle an action. It needs to serve two purposes: to flag a yes/no value (1/0) in the POST data, and ideally trigger an action on the page using JS/jQuery. I'm having trouble with the latter.
The default state is "No"; if I click "Yes" I can retrieve an onchange or onclick event state and make something happen. However, this is a one-way switch; I cannot retrieve a state going back to the "No" selector once I've gone to "Yes". What I need to be able to do is show / hide an element on the page depending on what choice they've made in this radio set. If I click "Yes", I can trigger the action and see the page change. Once I click "No", however, it acts as if there was no state change and I cannot perform an action i.e. hide the element again.
I've tried variations on retrieving the "checked" state, the radio pair value, etc, e.g.
$("#completeSw").change(function(e){
alert( $(this).attr("checked") ); // only triggers when "Yes" is selected
});
Perhaps I should not be using a yes/no radio pair, but instead be using a single checkbox? Seems more user-friendly and elegant this way (radio buttons) to me.
IDs must be unique, so it will only ever find the first one on your page. Use a class instead.
Really, ID's must be unique, but you don't need 2 ID's. You'll only monitor changes in one radio. For example - "Yes" value
<label for="completeSw"><span>Completed?</span></label>
<input type="radio" id="completeSw" name="completeSw" value="1"/>Yes
<input type="radio" name="completeSw" value="0" checked="checked"/>No<br/>
And the you'll process the checked attribute of only this element. True - "Yes", False - "No"
Some browsers don't do anything when alert(message), message=null. And since an unchecked field has no checked-attribute, that could be the thing :).
Try:
alert('Checked: '+$(this).attr("checked"));
This is separate, but you're kinda using the label wrong also. The label is meant to extend the click area so someone could click on the word 'Yes' and the radio button will activate. Hopefully this helps you out a little.
<span>Completed?</span>
<input type="radio" id="completeSwYes" name="completeSw" value="1"/><label for="completeSwYes">Yes</label>
<input type="radio" id="completeSwNo" name="completeSw" value="0" checked="checked"/><label for="completeSwNo">No</label><br/>
<script type="text/javascript" charset="utf-8">
// If the radio button value is one then this evaluates to true.
var completeSW;
jQuery("input[type='radio'][name='completeSw']").change(function() {
completeSW = (jQuery(this).val() == 1);
alert("completeSW checked? " + completeSW);
});
</script>

Categories