I'm trying to implement a javascript code for the html5 form that will responsible for disabling/enabling the button until the select element is not selected. Here is the codes:
HTML:
<form name="courseForm" id="courseForm">
<select name="coursetype" id="coursetype" onchange="enableStartBtn()">
<option value="0" selected="selected">Select here...</option>
<option value="1">CourseName 1</option>
<option value="2">CourseName 2</option>
<option value="3">CourseName 3</option>
</select>
<button type="button" id="startBtn" disabled="disabled" onclick="Test()">Start</button>
</form>
and JavaScript:
function enableStartBtn() {
$('#startBtn').removeAttr('disabled');
}
function Test() {
var form = $('#courseForm');
var course = $('#coursetype', form).val();
if (course == '0') {
alert('Select the course first!');
} else if (course == '1') {
alert('CourseName 1 is selected!');
} else if (course == '2') {
alert('CourseName 2 is selected!');
} else if (course == '3') {
alert('This course is not implemented yet');
}
}
I'm using JQuery 1.9.1 in my code, everything looks like ok, but the when value is selected the button is not enables. Any help would be appreciated.
UPDATE: Sorry guys forgot to mention that I'm also using JQuery Mobile 1.3.0, so without including jquery mobile it works, but with jquery mobile not. Here is the jsfiddle version: http://jsfiddle.net/dozent/UVQ4m/
How do you disable button until all fields are entered? Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.
To disable a button using only JavaScript you need to set its disabled property to false . For example: element. disabled = true . And to enable a button we would do the opposite by setting the disabled JavaScript property to false .
You can just add "disabled" to your button, and then when the user locks in their answer, enable it again. Additionally, it's not best practice to split your JavaScript into a bunch of different script tags. Put them all in one place.
<form name="courseForm" id="courseForm">
<select name="coursetype" id="coursetype">
<option value="0" disabled>Select here...</option>
<option value="1">CourseName 1</option>
<option value="2">CourseName 2</option>
<option value="3">CourseName 3</option>
</select>
<button type="button" id="startBtn" disabled>Start</button>
</form>
And do :
var courses = ['1','2']; // available courses
$('#coursetype').one('change', function() {
$('#startBtn').prop('disabled', false);
});
$('#startBtn').on('click', function() {
var val = $('#coursetype').val(),
msg = $.inArray(val, courses) != -1 ? 'CourseName '+val+' is selected!' : 'This course is not implemented yet';
alert(msg);
});
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With