How to dynamically enable/disable a button - javascript

Based on the answer here, I tried to create a similar validation function:
<html>
<head>
<script>
$("#my_name_id").on("change", function() {
if (!$("#my_name_id").val()) {
$("#button_id").attr("disabled", "disabled");
} else {
$("#button_id").attr("enabled", "enabled");
}
});
</script>
</head>
<body>
<form action="" name="test_form" id="test_form_id" method="post">
<input type="text" name="my_name" id="my_name_id" placeholder="Type your name"/>
<button type="submit" id="button_id">My button</button>
</form>
</body>
</html>
In this example, I would like to continually check to see if the input box contains any characters. If it does, then the button should be enabled (clickable). If the input box does not contain any text, then the button should be disabled.
However, in my case the button always remains enabled. What am I doing wrong here?

You should use prop, not attr. After all your code will become simpler:
$("#my_name_id").on("change keyup", function() {
$("#button_id").prop("disabled", !this.value);
})
.trigger('change');
Also note how you can use trigger in order to run initial check on page load automatically. I also included keyup event for this to work as you type.
Demo: http://jsfiddle.net/7nywe/

No enabled attribute in HTML for , so manipulate the disabled attribute:
<script>
$("#my_name_id").on("change", function () {
if (!$("#my_name_id").val()) {
$("#button_id").attr("disabled", "disabled");
} else {
$("#button_id").removeAttr("disabled");
}
}).trigger('change');;
</script>

You should use prop()
$("#button_id").prop("disabled", true); // disabled
$("#button_id").attr("disabled", false); // enabled
You should use prop when you are dealing with boolean types.

Related

Reset all inputs of a form to default values without reloading

I want to reset all the values of my inputs that I have within a form (textboxs, selects, checkboxs, radiobuttons,...) like if I reload the web, but when I touch a button.
$("#button").click(function () {
//Here the code that I need
});
You can reset a form using JavaScript built-in reset() function:
$("#otra").click(function () {
$("#yourFormId")[0].reset();
});
Working demo:
$("#otra").click(function () {
$("#yourFormId")[0].reset();
return false; // prevent submitting
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="yourFormId">
<input type="checkbox" name="myCB"/>
<input type="text" name="myTB" value=""/>
<button id="otra">Reset</button>
</form>
You can do it this way
$('input, textarea').val('');
$('select').find('option').prop("selected", false);
you can reset the complete form using this code
$('#myForm').trigger("reset");
Try this:
$('form[name="myform"]')[0].reset();
My page preserves fields during post back, reset() doesn't remove them.
This helped me:
https://stackoverflow.com/questions/6364289/clear-form-fields-with-jquery
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], textarea").val("");
});
Other types can be added.

clear radio buttons when click on text input

I have a group of 4 radio buttons followed by a text input, when users click on the text input field I am trying to clear all radio inputs. here is my code so far.
<input type="radio" name="radio"><label for="radio1">1</label>
<input type="radio" name="radio"><label for="radio2">2</label>
<input type="radio" name="radio"><label for="radio3">3</label>
<input type="radio" name="radio"><label for="radio4">4</label>
<input type="text" id="textInput">
<script>
$('#textinput').click(function () {
radio.checked = false;
});
</script>
You can use .prop() to set checked property of input rabio buttons. Also you have misspelled textInput while event binding
<script>
$('#textInput').click(function () {
$('input[name="radio"]').prop("checked", false);
});
</script>
DEMO
<script>
$('#textInput').click(function () {
$('input[type=radio]').removeAttr("checked");
});
</script>
Or you can try attr() method
$('#textInput').click(function () {
$('input[name="radio"]').attr('checked',false);
});
DEMO
I think the best way to modify your script block (without changing your html) is first by ensuring that the code runs on document ready, and also you should probably ensure that the event is focus, not click, in case someone is using a keyboard or alternate navigation:
$(function() {
$('#textInput').focus(function () {
$('input[name=radio]').prop("checked", false);
});
});
Though it's probably more likely that you want to only clear other selections if they actually enter some data in that field, you might want to instead do:
$(function() {
$('#textInput').on('input', function () {
if($(this).val().length > 0) {
$('input[name=radio]').prop("checked", false);
}
});
});

Proper handling of input change event

It may be a correct behavior of change event, but the below behavior is bit annoying. When the value is updated from the field history (see explanation below), the event is not triggered.
Please see example code below. the result input field is updated with the change in input field 'input1'. The form and submit button is not fully relevant, but needed to submit a form to make the browser keep the history of field values.
To test:
enter any input in the field (say ABC)
Submit the form
enter first character of input from 1 (A)
use the down arrow to select the previous value + Enter
or use the mouse to select the previous value from the history
No input change is detected.
Which event/ how should this code should modify so that an event is generated whenever the input value is changed.
thanks.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
Result:<input type="text" id="result" readonly></input>
<form method="post" action="">
<input type="text" id="input1" />
<button type=submit>Submit</button>
</form>
<script >
$(document).ready(function() {
$('#input1').change(
function(){
$('#result').val($('#input1').val());
});
});
</script>
</body>
</html>
I think this has nothing to do with jQuery.
A change event should be dispatched when the content of a control has changed and the control loses focus. In practice, the implementation of the change event is inconsistent in browsers, e.g. Firefox dispatches a change event when radio buttons are clicked on rather then when they lose focus. Also in IE, selecting a value from a list of previous values then causing a blur event doesn't fire a change event.
Note that for form controls to be successful, they must have a name attribute with a value. A simple test case is:
<form action="#">
<input type="text" name="input1" onchange="alert('changed');">
<input type="submit">
</form>
One solution is to use the blur event instead and compare the control's current value to its defaultValue - if they're different, perform whatever it is you were going to do for the change event. If the value may be changed a number of times, after the first time you need to compare with the last value onblur rather than the defaultValue.
Anyhow, here's a function that can be called onblur to see if a text input has changed. It needs a bit of work if you want to use it with other types of form control, but I don't think that's necessary.
<form action="#">
<input type="text" name="input1" onblur="
var changed = checkChanged(this);
if (changed[0]) {
alert('changed to: ' + changed[1]);
}
">
<input type="submit">
</form>
<script type="text/javascript">
// For text inputs only
var checkChanged = (function() {
var dataStore = [];
return function (el) {
var value = el.value,
oValue;
for (var i=0, iLen=dataStore.length; i<iLen; i+=2) {
// If element is in dataStore, compare current value to
// previous value
if (dataStore[i] == el) {
oValue = dataStore[++i];
// If value has changed...
if (value !== oValue) {
dataStore[i] = value;
return [true, value];
// Otherwise, return false
} else {
return [false, value];
}
}
}
// Otherwise, compare value to defaultValue and
// add it to dataStore
dataStore.push(el, value);
return [(el.defaultValue != value), value];
}
}());
</script>
Try the keyup event:
$(document).ready(function() {
$('#input1').keyup(
function(){
$('#result').val($('#input1').val());
});
});
http://jsfiddle.net/kaptZ/7/
It seems like it's definitely a browser bug. Not much you can do besides implement your own change handler with focus and blur. This example is not very reusable, but it solved the problem and can be used as inspiration for something reusable.
http://jsfiddle.net/kaptZ/9/
var startValue;
var input1 = $('#input1');
input1.focus(function(){
startValue = this.value;
});
input1.blur(function(){
if (this.value != startValue) {
$('#result').val(this.value);
}
});
A dirty alternative is to use autocomplete="off"
It looks like this bug which was supposed to be fixed in November 2009.
In modern browsers you can use the input event and update as you type. It can be bound either to the text input:
$('#input1').bind('input', function(){
$('#result').val($('#input1').val());
});
Or to the form:
$('#input1').closest('form').bind('input', function(){
$('#result').val($('#input1').val());
});

checkbox property using jquery

i m a beginner.
i want that when a checkbox is checked then it should allow user to write something in a txtbox. initially the txtbox is disabled. what i should write inside the function using jquery
<input type="checkbox" id="cb" />
<label for="cb">label for checkbox</label>
<input type="text" id="txt" disabled="disabled" />
<script type="text/javascript">
$(document).ready(function() {
var checkbox = $('#cb');
var textfield = $('#txt');
checkbox.click(function() {
if (checkbox.is(':checked')) {
textfield.removeAttr('disabled');
}
else {
textfield.attr('disabled', 'disabled');
}
});
});
</script>
working example with visibilty
working example with disabled-state
additionally:
as you are working with asp.net, your assignments should look like, eg:
var checkbox = $('#<%= this.cb.ClientID %>');
you should be aware of the way how the server-controls get rendered either (to choose an appropriate selector).
furthermore: you should also be aware of the fact, that disabled-inputs won't get posted, whereas readonly-inputs are no problem to handle...
$('#mycheckbox').click(function()
{
$("#mytextbox").attr('disabled','');
}
);
$(document).ready(function()
{
//To Disable the Check box on page Load
$('#TextBox').attr('disabled', 'disabled');
//On Click of the Check Box
$('#CheckBoz').click(function()
{
if($('#CheckBoz').is(':checked'))
{
$('#TextBox').removeAttr('disabled');
}
else
{
$('#TextBox').attr('disabled', 'disabled');
}
});
});
I Hope this code works perfectly for you and u jst need to paste it in your page and check the Component name according to it.

properly disabling the submit button

this is the code that I use to disable the button
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
and this is my submit button
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here?
If it's a real form, ie not javascript event handled, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
$(yourButton).attr("disabled", "true");
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
That should stop the button acting like a button.
Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
$('#btnSubmit').unbind('click').click( function() { return false; } );
You'd have to add the click handler's again when (if) you re-enable the button.
You need to process Back/Prev button into browser.
Example bellow
1) Create form.js:
(function($) {
$.enhanceFormsBehaviour = function() {
$('form').enhanceBehaviour();
}
$.fn.enhanceBehaviour = function() {
return this.each(function() {
var submits = $(this).find(':submit');
submits.click(function() {
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = this.name;
hidden.value = this.value;
this.parentNode.insertBefore(hidden, this)
});
$(this).submit(function() {
submits.attr("disabled", "disabled");
});
$(window).unload(function() {
submits.removeAttr("disabled");
})
});
}
})(jQuery);
2) Add to your HTML:
<script type="text/javascript">
$(document).ready(function(){
$('#contact_frm ).enhanceBehaviour();
});
</script>
<form id="contact_frm" method="post" action="/contact">
<input type="submit" value="Send" name="doSend" />
</form>
Done :)

Categories

Resources