Unable to disable a button element using JavaScript - javascript

I am unable to disable a button using the getElementById() method. I am looking for inspiration as to what I am doing wrong because I use it to enable a button but I cannot seem to be able to disable it.
I have tried calling the method in different ways:
document.getElementById('wsSubmit').disabled = false;
document.getElementById("wsSubmit").disabled = false;
document.getElementById('#wsSubmit').disabled = false;
document.getElementById("#wsSubmit").disabled = false;
document.getElementById(buttons[0]).disabled = false;
Button in question:
<input class="button" type="button" id="wsSubmit" onclick="closeWindowDWSC();" value="Submit" disabled>
I want the button to become enabled.

You need to remove the attribute.
document.getElementById('wsSubmit').removeAttribute('disabled');
As mentioned in the comments, a duplicate Id would case this functionality to fail.

Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state.
A small demo:
<!-- Checkbox enables/disables the button -->
<label for="checkbox"><input type="checkbox" id="checkbox" label="Enable button" onclick="document.getElementById('buttRemove').disabled = ! this.checked">Enable/Disable the button</label>
<hr>
<button id="buttRemove" label="Remove All" disabled="true">Button</button>
Back to your example. The first 2 example of code which is really same, if I don't consider the '' and "".. You want it to be set as true, when want to enable them like:
document.getElementById('wsSubmit').disabled = true;
document.getElementById("wsSubmit").disabled = true;
This should work. If doesn't work, then probably your page has duplicate ID to another element which comes after this <button> element in the DOM.

Related

How to inspect any data change in one composed popup

I have one notification on the web, when I click on it, it will open new popup, the save button is default disable, this popup is one kind of window that composed from many elements (list of radio check boxes of many id of goods have just imported to my shop, from that I can choose one or multiple id to attach them to one shelf, and I can do the second time to attach other/others to another shelf, the name of shelf will display under the name of kind of ids...and many others elements).
Question is, how can I inspect that there is any data change (there is any id already attached or cancel attach) in order to enable the button again by Javascript.
.
Thank you!
if what you want is to "enable" the button just add the code to the onClick event of the "list radio check" controls, something like:
<form action="">
<input type="radio" onclick="activate()" name="good1" value="1">12345746<br/>
<input type="radio" onclick="activate()" name="good2" value="2">456548765<br/>
<input type="radio" onclick="activate()" name="good3" value="3">54654654546<br/>
<button id="saveButton" disable> save</button>
</form>
<script>
function activate(){
document.getElementById("saveButton").disabled = false;
//the code that enable your button, what ever serve you better...
</script>
or add an event listener to the click event on all the radio buttons, which will do the same (because is "the same")
let rb = document.getElementsByTagName("input");
for(let idx=0; idx<rb.length; idx++){
if(rb[idx].getAttribute("type") == "radio"){
rb[idx].addEventListener("click", function(){
document.getElementById("saveButton").disabled = false;
}
}
}
which again, do the same ;)
Hope it helps.

On checking "Mr." radio button it should select "Male" radio button. Please tell me what went wrong? Its not selecting Male radio button [duplicate]

With HTML a checkbox is created like this:
<form>
<input type="checkbox" id="category1">Category1<br>
</form>
With javascript we can check the checkbox like this:
$("#category1")[0].checked = true
Now I am trying to create the same page with jquery-mobile. The checkbox looks like this:
<form>
<label>
<input name="checkbox-0 " type="checkbox">Check me
</label>
</form>
Why is there is no id here? Is the name the id? Should I delete the attribute name and create one with the name id?
How can I check this checkbox here with Javascript/jQuery?
I tried the code above, but it doesn't seem to work for this checkbox.
You need to refresh it after changing its' .prop, using .checkboxradio('refresh'). This is the correct way to check checkbox/radio in jQuery Mobile.
Demo
$('.selector').prop('checked', true).checkboxradio('refresh');
Reference: jQuery Mobile API
You can do:
$('input[name="checkbox-0"]').prop("checked", true).checkboxradio('refresh'); //sets the checkbox
var isChecked = $('input[name="checkbox-0"]').prop("checked"); //gets the status
Straight from the jQ Mobile docs:
$("input[type='checkbox']").attr("checked",true);
With the solution from #Omar I get the error:
Uncaught Error: cannot call methods on checkboxradio prior to initialization; attempted to call method 'refresh'
I actually had a flipswitch checkbox:
<div class="some-checkbox-area">
<input type="checkbox" data-role="flipswitch" name="flip-checkbox-lesson-complete"
data-on-text="Complete" data-off-text="Incomplete" data-wrapper-class="custom-size-flipswitch">
</div>
and found the solution was:
$("div.ui-page-active div.some-checkbox-area div.ui-flipswitch input[type=checkbox]").attr("checked", true).flipswitch( "refresh" )
Notes
I don't usually specify ids for page content as jQuery Mobile loads multiple div.ui-page content into a single HTML page for performance. I therefore never really understood how I could use id if it might then occur more than once in the HTML body (maybe someone can clarify this).
If I use prop rather than attr the switch goes into an infinite flipping loop! I didn't investigate further...

How to retrieve submit button with getElementsByTagName

I would like to get the a submit button using getElementsByTagName but I must be doing something wrong.
<p id="ptag">Want to find out if this works</p>
<button>The Button</button>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
<input type="checkbox" name="yes" value="yes">A checkbox<br>
<input type="submit" value="Login">
</form>
in the above HTML snippet, If I use the below function, getting the button works yet getting the submit button does not.
window.onload = theFunction;
function theFunction(){
document.getElementsByTagName("BUTTON")[0].setAttribute("onclick", "theOtherFunction()");
document.getElementsByTagName("INPUT")[3];.setAttribute("onclick", "theOtherFunction()");
}
What am I doing wrong?
function theOtherFunction(){
document.getElementById("ptag").style.color = "blue";
}
I added theOtherFunction() to my question because all my little experiment is doing is changing that <p> color to blue. With the button, it stays blue. With the submit button, it quickly turns blue and then goes back to black. What is the difference and how can I use the submit button to retain changes?
Take a look at your last line of code document.getElementsByTagName("INPUT")[3];.setAttribute("onclick", "theOtherFunction()");
There is a ; you don't want there right after the [3].
Hope this helps.
jQuery becomes very useful here
$('input[type="submit"]')
This will allow you to make html changes with immunity and support older browsers that still have 1% usage.
Your 2nd example should work without the ; in the middle of the line. However not all browsers support getElementsByTagName.
Update using no ready made libs.
If you are a build it yourself person, who wants to make his own lib.
function getElementsByAttrib(attrib) {
return document.querySelectorAll('[' + attrib + ']');
}
var elements = getElementsByAttrib('type="submit"');
MySubmit = elements[0]';
It's not practical to target/retrieve specific input elements with getElementsByTagName.
We gotta use the right tool for the right job and in this case it's the query selector like this...
var S=document.querySelectorAll('input[type=submit]');
S[0].style.background='red'; // do something to the first button
NB: Code above assumes you only have one submit button or you'll have to loop through the array "S" to target all submit buttons.

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/

How do I make a checkbox unclickable *without* it being greyed out in the browser?

How do you create an HTML checkbox that is unclickable, but not greyed out? I used the disabled=disabled tag, but that makes it greyed out (in Chrome). Otherwise it works well. Working in jQuery and Rails...
Thanks.
Usability concerns aside:
$("input:checkbox").click(function() { return false; });
For example: http://jsfiddle.net/nKwRj/
Use jQuery.on with false as the callback:
$(":checkbox").on("click", false);
Fiddle
I had the same issue where i wanted the user to check the box but not the client the client was supposed to see the checked box only and not to make changes so
in html just add a css pointer event style
<input name='test' type='checkbox' style="pointer-events: none;"/>
Prevent checkboxes from being changed by ID or by Class.
/* by class */
$(".nochange").click(function () {
return false;
});
/* by ID */
$("#nochange").click(function () {
return false;
});
<input name='test' type='checkbox' class='nochange' checked='checked' />
<br />
<input name='test' type='checkbox' id='nochange' checked='checked' />
http://jsfiddle.net/mjames757/nX64E/1/
Why do you want to make a unclickable checkbox appear to be clickable? To fool the users?
If you really want to fool the users, you could place a div with 0.01 opacity above it using absolute positioning (no script required). But I still wonder why you feel the need to do this prank on your users... ;)
EDIT: If what you really need is to include a value the user should not change but you don't want what you probably are considering "an ugly disabled checkbox", you should use input type hidden, which is completely invisible.
If you want to indicate that something is preselected but not changeable or something like that, use a disabled checkbox to indicate this (or an image of a pretty checkbox if you like), but beware that the value of a disabled checkbox is not submitted. Use a hidden field to include the the data needed.
Just add onclick="return false" in your HTML code.
Example:
<input type="checkbox" onclick="return false" class="checkbox" checked >
I ran into this post in search of an answer to the initial question - and found the opposals to non-grayed disabled checkboxes convincing, so instead i made a td-tag containing this: <%if rs("yes/no value") = -1 then response.write("√")%> (wing is a &radic). Then i get a clean info wing not inviting to click.

Categories

Resources