I have a function that enables or disables form elements based on which radio item is checked. It is working ok. However, I wish that one of the radio buttons to be checked at page load with the appropriate form elements already disabled or enabled.
Right now on page load, I have one of the radio buttons checked on the form itself but the javascript will fire when there is a change.
Here is the javascript
<script type="text/javascript">
function customerChoice() {
if (document.getElementById('radio1').checked) {
document.getElementById('company').disabled = false;
document.getElementById('onetime').disabled = true;
document.getElementById('span1').style.color = '#cccccc';
document.getElementById('span2').style.color = '#000000';
}
if (document.getElementById('radio2').checked) {
document.getElementById('company').disabled = true;
document.getElementById('onetime').disabled = false;
document.getElementById('span1').style.color = '#000000';
document.getElementById('span2').style.color = '#cccccc';
}
}
window.onload = customerChoice();
</script>
And here are the two radio buttons.
<input type="radio" name="type" id="radio1" value="C" onclick="customerChoice()" checked />Current Customer<br />
<input type="radio" name="type" id="radio2" value="O" onclick="customerChoice()" />One Time Customer<br />
Need help figuring out what to change in order to make the javascript fire upon loading. Thank you.
Try:
window.onload = customerChoice;
The way you have it runs the function immediately, and sets the onload handler to the result (which is undefined, since the function doesn't return anything), rather than to the function itself. It's not working because it runs before the DOM is loaded.
try putting the customerChoice() function inside an anonymous function:
window.onload = function() {
customerChoice();
};
Related
I have a simple piece of javascript embedded into my html form, not a separate file, that is supposed to disable the submit form button until a certain checkbox has been checked but it doesn't seem to be working.
<script>
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (disclaimer.checked) {
submitButton.disabled = false;
}
</script>
which I wrote and seems simple and effective but I'm not getting the results I'm looking for. After researching I see results such as
$('#check').click(function(){
if($(this).attr('checked') == false){
$('#btncheck').attr("disabled","disabled");
}
else
$('#btncheck').removeAttr('disabled');
});
Now obviously the variable names and such are named differently but this doesn't even look remotely similar to the javascript code I've provided above and I'm having a hard time getting useful tips from the apparently working code below that does the same thing. Could someone break down the code segment below such that I might be able to fix my code above?
This is the snippet of code with the two HTML id's in question,
<label style='font-size: smaller;'>
<input type='checkbox' name='disclaimer' id='disclaimer' required='required' />
I understand that by submitting this form,
I am transferring any copyright and intellectual property rights to the form's owner,
that I have the right to do so,
and that my submission is not infringing on other people's rights.
</label><br/>
<script>
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (disclaimer.checked) {
submitButton.disabled = false;
}
</script>
<div class='vspace'/>
<input type='submit' id='submit' name='came-from-form'/>
Edit: Tons of great answers below that were very informative for letting me know what I'm working with. The issue I'm now facing is implementing these things. In the snippets below this seems very easy to implement but as I try to implement each answer below I'm not seeing any results which clearly means I'm doing something wrong somewhere else in my form. I've attached a larger snippet of the code in question if it helps. Otherwise it might be best to ask a new question.
I believe you trying to find the solution in vanilla JavaScript.
You have to attach the event to the check element like the following way:
var disclaimer = document.getElementById("disclaimer");
document.getElementById("submit").disabled = true;
disclaimer.addEventListener('click', function(){
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (this.checked) {
submitButton.disabled = false;
}
});
<form>
<input type="checkbox" id="disclaimer"/>
<button id="submit">Submit</button>
</form>
Update:
In your code, the script is executing before the DOM is fully loaded. Hence you get a error:
Uncaught TypeError: Cannot set property 'disabled' of null
You can either place the script at the end or wrap your code with
DOMContentLoaded
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
<label style='font-size: smaller;'>
<input type='checkbox' name='disclaimer' id='disclaimer' required='required' />
I understand that by submitting this form,
I am transferring any copyright and intellectual property rights to the form's owner,
that I have the right to do so,
and that my submission is not infringing on other people's rights.
</label><br/>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var disclaimer = document.getElementById("disclaimer");
document.getElementById("submit").disabled = true;
disclaimer.addEventListener('click', function(){
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
if (this.checked) {
submitButton.disabled = false;
}
});
});
</script>
<div class='vspace'/>
<input type='submit' id='submit' name='came-from-form'/>
Quick Explantion
Here's a quick explanation of the code, which is heavily reliant on the JavaScript library, jQuery:
// click() is called every time the element `id="check"` is clicked
$('#check').click(function(){
// if element with `id="check"` has an attribute called *checked* set to false or it is null, then perform the if-block, otherwise perform the else-block
if($(this).attr('checked') == false){
// set disabled attribute of element with `id="btncheck"` to value of `disabled`
$('#btncheck').attr("disabled","disabled");
}
else
// remove disabled attribute of element with `id="btncheck"`
$('#btncheck').removeAttr('disabled');
});
anything in $() is selecting the element in the DOM, primarily using CSS-like selectors
.attr() is a method that gets/sets the element HTML attribute
.removeAttr() is a method that removes the HTML attribute
Vanilla JS
What you want to accomplish can be done with vanilla JS.
const disclaimer = document.querySelector("#disclaimer");
const submit = document.querySelector("#submit");
submit.disabled = true; // default setting
const clickHandler = (event) => submit.disabled = !event.target.checked;
disclaimer.addEventListener('click', clickHandler ); // attach event
<form>
<input type="checkbox" id="disclaimer"/>
<button id="submit">Submit</button>
</form>
Hope this will work for you
$('#disclaimer').click(function(){
if($(this).attr('checked') == false){
$('#submit').attr("disabled","disabled");
}
else
$('#submit').removeAttr('disabled');
});
Here if condition indicates the action which should be done if the disclaimer is not chcked. Button will be enable if the disclaimer is checked.
If you want jQuery, use prop (is not wrong to use attr too but I prefer prop instead).
For checkbox, use change event instead of click. I'd do like:
$('#check').on("change", function(){
var isChecked = $(this).is(':checked');
$('#btncheck').prop("disabled", !isChecked);
});
The only significant difference between the 2 code samples you posted is that the second one wraps the button disabling in the click event.
First one says : Straight when page is loaded, if the checkbox is checked, enable the button. (hint: happens only once)
Second one says : For each click on the checkbox, if the checkbox is checked, enable the button.
Something like this should work (haven't tested) :
<script>
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
function disableSubmitIfDisclaimerNotAccepted(){
submitButton.disabled = true;
if (disclaimer.checked) {
submitButton.disabled = false;
}
}
disclaimer.onclick = disableSubmitIfDisclaimerNotAccepted; // everytime the checkbox is clicked
disableSubmitIfDisclaimerNotAccepted(); // on page load
</script>
You must listen to input events in order to make changes when something change, like checking an checkbox.
var disclaimer = document.getElementById("disclaimer");
var submitButton = document.getElementById("submit");
submitButton.disabled = true;
disclaimer.addEventListener('change', function() {
if (this.checked) {
submitButton.disabled = false;
} else {
submitButton.disabled = true;
}
})
More about events: https://developer.mozilla.org/en-US/docs/Web/Events
Submit button disabled by default in HTML :
<input type="checkbox" id="disclaimer">
<label for="disclaimer">Disclaimer</label>
<input type="submit" id="submit" disabled>
Simplest solution using ES6 syntax without JQuery :
let disclaimerCheckbox = document.getElementById('disclaimer'),
submitButton = document.getElementById('submit');
disclaimerCheckbox.onchange = () => submitButton.disabled = !disclaimerCheckbox.checked;
JSFiddle
NOTE : no need to use the DOMContentLoaded event if the script has the defer attribute.
<input type="radio" id="Svar0" name="Svar" value="Yes">
<input type="radio" id="Svar1" name="Svar" value="No">
<input type="radio" id="Svar2" name="Svar" value="MayBe">
User can choose only once.
As per requirement, if the user has selected a radio, he can not select another one. Means that if the user has answered YES (clicked on YES), then he can not change the answer to NO or MayBe.
Workarounds:
If I disable the radio after single click then it is not submitted to the server.
There is no option for readonly.
I tried onchange handler returning false, but it makes the user answer disappearing.
<script>
$('input[type = "radio"]').change(function () {
this.checked = false;
});
</script>
I am thinking of weird options like transparent div before radio buttons.
I do not want to prefer hidden fields as I have above 60 questions and I find it difficult to manage them.
Please help me any code in Jquery or Javascript.
If the user selects one answer in radio, then the page should not allow him to select another answer and so the first selected answer should be the one that gets submitted.
Another simple option (disable all, except selection, on selection of any). This allows the selected value to be posted back:
$(':radio').change(function(){
$(':radio').not(this).prop("disabled", true);
});
JSFiddle: http://jsfiddle.net/9n8v4heo/
Update (delay before disable):
It does not appear to be a good user experience to allow radio selection then freeze it immediately, as mistakes do happen.
The following example will allow a 2 second delay after any selection, before making them disabled, so you can keep clicking but after two seconds you cannot select again:
var tme;
$(':radio').change(function(){
var t = this;
clearTimeout(tme);
tme = setTimeout(function(){
$(':radio').not(t).prop("disabled", true);
}, 2000);
});
JSFiddle: http://jsfiddle.net/9n8v4heo/1/
try
$("[type=radio][name=Svar]").change(function () {
if (!$("[type=radio][name=Svar]").filter("[clicked]").length) {
$(this).attr("clicked", "true")
} else {
$(this).prop("checked", !this.checked);
$("[type=radio][name=Svar]").filter("[clicked]").prop("checked", true)
}
});
DEMO
use preventDefault() with click event as #JotaBe said
$("[type=radio][name=Svar]").click(function (e) {
if (!$("[type=radio][name=Svar]").filter("[clicked]").length) {
$(this).attr("clicked", "true")
} else {
e.preventDefault();
}
});
DEMO
You can disable the other buttons when one gets selected, this way the selected one will get sent when the form is submitted.
jQuery("input[name=Svar]").change(function() {
jQuery("input[name=Svar]").prop("disabled", "disabled");
jQuery(this).prop("disabled",false);
});
You can attach an event handler that disables the default action for the click to all the radios, and do whatever you need to do instead ofteh default action. Tod so so, attach a handler that simply includes a call to: event.preventDefault(), and your own code.
See jquery docs for event.preventDefault()
$(document).ready(function() {
var allowChoose = true;
$('input').click(function(e) {
if (allowChoose) {
allowChoose = false;
} else {
e.preventDefault();
}
});
});
As you can see, you can use a flag like 'allowChoose' to allow the default action on the first click, and then change the flag and avoid the default action (checking the radio) on the next calls.
See the fiddle here.
Quick solution: You can disable the others radio buttons and the selected value remains enabled.
var $Svars = $('input[name="Svar"]');
$Svars.change(function () {
$Svars.not(this).prop("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="Svar0" name="Svar" value="Yes" /> Yes
<input type="radio" id="Svar1" name="Svar" value="No" /> No
<input type="radio" id="Svar2" name="Svar" value="MayBe" /> Maybe
Solution 2: Another solution will be to add a class or a data attribute to exclude the others, like below.
var $Svars = $('input[name="Svar"]');
$Svars.change(function () {
var $this = $(this);
if($this.val() == $this.data('selected') || $this.data('selected') == undefined) {
$Svars.data('selected', $this.val());
} else {
$Svars.val([$this.data('selected')]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="Svar0" name="Svar" value="Yes" /> Yes
<input type="radio" id="Svar1" name="Svar" value="No" /> No
<input type="radio" id="Svar2" name="Svar" value="MayBe" /> Maybe
My code is only let checkbox checked,I want it also do onclick event.
<input type="checkbox" name="list" id="mycheckbox" onclick="check_marker(this)" />
document.getElementById(mycheckbox).checked = true;//I want also do onclick event.
function check_marker(input_var){
var carId;
carId = input_var.id;
alert(carId);
}
Changes made through javascript do not trigger handlers. You will need to call it yourself after making the change:
http://jsfiddle.net/F2J37/
var cb = document.getElementById("mycheckbox");
cb.checked = true;
cb.onclick(); // call the click handler directly
How to prevent second click on radio button if it is already checked so that javascript event can be prevented.
As I am doing many things onclick of radio button
<input name="EnumEvent" type="radio" value="Open" onclick="show_event()"/>
javascript
function show_event()
{
document.getElementById("radio-btns-div1").style.display="block";
document.getElementById('invited').style.display="none";
document.getElementById('invited').value = '';
document.getElementById('invite_1').value='';
}
You could use change event instead of click
<input name="EnumEvent" type="radio" value="Open" onchange="show_event()"/>
DEMO
Add the disabled attribute
function show_event()
{
document.getElementByName("EnumEvent").setAttribute("disabled", "disabled");
...
}
Don't forget to remove the attribute when/if you want the user to be allowed to select another option.
var clicked = false;
$('input:radio.yourclass').click(function(event){
if (clicked){
event.preventDefault();
}
clicked = true;
});
function Clicked() {
if (document.getElementById("radio-btns-div1").checked) {
document.getElementById("radio-btns-div1").disabled = true;
}
Refer to Disable radio button according to selected choice
I have a set of radio buttons that I am testing with, will be used to change theme. Html code is straight forward
<div id="options">
<input type="radio" name="imm" id="themea" value="a" /> Theme 1
<input type="radio" name="imm" id="themeb" value="b" /> Theme 2
</div>
How when I click on a radio item, the first time around the following code will show alert once, second time it will display twice, third time third and so on. What is going on, I reckon I need to destroy something but not sure what.
Here is my backbone code:
events: {
"click input[type=radio]": "onRadioClick"
},
onRadioClick: function (e) {
// e.stopPropagation();
var self = this
_.bindAll(self)
$("input:radio[name=imm]").click(function (){
var somval = $(this).val();
alert(somval)
});
This is how I initialize the view:
initialize: function(state) {
var self = this
_.bindAll(self)
self.state = state
self.setElement('#options')
self.elem = {
imm: self.$el.find('#imm')
}
}