Disable and enable function in Jquery - javascript

I have a text input in html that is affected by a function exectued by .change() events from different radios and checkboxes. I'm trying to make it so that if a user types into the input, this function will no longer run when a .change() event happens in the aforementioned radios and checkboxes (the user must still be able to use these radios and checkboxes). However, if the user leaves the input blank and clicks away, the script will run again. I hope is possible.
Here is my take on this so far:
Using.prop('diabled' isnt viable because it completely disables the input, making the user unable to type in it, so I need another solution.
$(function() {
$('#burger-navn').on('input', function() {
$("#burger-navn").prop('disabled', true);
});
//When the input (#burger-navn) is typed into it should be "disabled"
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#burger-navn").prop('disabled', false);
}
});
//But if its clicked out of while its blank, it should be able to run again.
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if (!$("#burger-navn").not(':disabled')) { //condition that tests
navngenerator();
}
});
});

To solve this I simply created a separate input tag that I could add and remove disabled attribute from, and check if it has that attribute.
So in html:
<input id="burger-navn" type="text"/>
<input id="toggle" disabled="disabled" style="display:none"/>
jQuery:
var previousValue = $("#burger-navn").val();
$("#burger-navn").keyup(function(e) {
var currentValue = $(this).val();
if(currentValue != previousValue) {
previousValue = currentValue;
$("#toggle").prop('disabled', false);
}//This function will remove disabled from #toggle, when a user types into #burger-navn
});
$('#burger-navn').focusout(function() {
if ($(this).val().length == 0) {
$("#toggle").prop('disabled', true);
}
});
if ($("#toggle").is(':disabled')) {
navngenerator();
}
$("#okseinput, #laksinput, #kyllinginput, #vegetarinput").change(function() {
if ($("#toggle").is(':disabled')) {
navngenerator();
}
});

$(selector).on('change', function(event){
event.preventDefault();
event.stopPropagation();
// the selected field no longer does anything on change
});
is that what you are looking for?

Related

Enable form and Disable another one at the same time

I am facing a problem and I want your help please.I have created two individual forms.The 1st has two input text and the 2nd has some checkboxes.I want on load page the 2nd to be disabled and when a checkbox is checked then the form will be enabled and the 1st will be disabled.If there isn't checkbox checked then the 1st is enabled and the 2nd disable.I hope you understand.My English isn't perfect..
Here is the jQuery I use:
//eksargirwsh is the 2nd form (with checkboxes)
//prosthiki is the 1nd form (with two input text)
$(document).ready(function() {
$('#eksargirwsh :not([type=checkbox])').prop('disabled', true);
});
$(":checkbox").change(function(){
if (this.checked) {
$('#eksargirwsh :not([type=checkbox])').prop('disabled', false);
$('#prosthiki').prop('disabled', true);
}
else{
$('#eksargirwsh :not([type=checkbox])').prop('disabled',true);
$('#prosthiki').prop('disabled', false);
}
}) ;
ERRORS
On load page the 2nd isn't disabled as expected
If I checked two or more checkbxes in row and unchecked them in the opposite way the 2nd form becomes disabled fact I don't want
This is the solution I found:
$(document).ready(function() {
$('#eksargirwsh :not([type=checkbox])').removeAttr('disabled');
});
$(":checkbox").change(function(){
//if (this.checked){
if ($('form input[type=checkbox]:checked').size()>=1){
$('#eksargirwsh :not([type=checkbox])').removeAttr('disabled');
$('#prosthiki').prop('disabled', true);
}
else{
$('#eksargirwsh :not([type=checkbox])').prop('disabled',true);
$('#prosthiki').removeAttr('disabled');
}
});
And I put this on input :
disabled="disabled"
.prop('disabled',false) is not the right way to remove the disabled attribute. Please use .removeAttr('disabled') instead.
First of all, remember to init event handlers inside $(document).ready function
Secondly, to improve performance, remember to cache selectors.
Then, to make it cleaner to understand, move disable/enable logic to separate function:
$(document).ready(function() {
var $eksargirwsh = $('#eksargirwsh');
var $prosthiki = $('#prosthiki');
var $eksargirwshElements = $eksargirwsh.find('input:not([type=checkbox]), select, textarea, button');
var $prosthikiElements = $prosthiki.find('input, select, textarea, button');
$eksargirwsh.on('change', 'input[type=checkbox]', onCheckboxChange);
disableElements($eksargirwshElements, true);
function onCheckboxChange(){
if( $eksargirwsh.find('input:checked').size() == 0 ){ // no checked inputs
disableElements($eksargirwshElements, true); // disable #2
disableElements($prosthikiElements, false); // enable #1
} else {
disableElements($eksargirwshElements, false); // enable #2
disableElements($prosthikiElements, true); // disable #1
}
}
function disableElements($elements, state){
$elements.attr('disabled', state);
}
});
if you don't care so much for readability onCheckboxChange can be shortened to
function onCheckboxChange(){
var zeroChecked = $eksargirwsh.find('input:checked').size() == 0;
disableElements($eksargirwshElements, zeroChecked);
disableElements($prosthikiElements, !zeroChecked);
}

How to validate a memorized value in an input box

I have the following code:
$(":input").bind("keyup change", function(e) {
var comboVal = $('.emailrequerido1').val()+$('.emailrequerido2').val()+$('.emailrequerido3').val()+$('.emailrequerido4').val()+$('.emailrequerido5').val();
if(comboVal == 'nullnull' || comboVal == ""){
$("#enviarForm").attr('disabled', true);
}else{
$("#enviarForm").removeAttr('disabled');
}
});
What I am trying to accomplish is that when you select a memorized value from the input box by double clicking in the box a history of inputs shows (these values are saved by the browser (I believe)) and if you choose one of these and the field has that text you selected the button should enable.
Here is a JSFiddle example: JSFiddle example
In the example I added a value to the first field since these dont memorize as I expalined before to show a demonstration of what I mean.
I have cleaned up the code a bit: http://jsfiddle.net/kam5B/1/
I've swapped the classes and ids so that the ids are unique, and the classes are common.
Here is a checkEmails function that runs the validation and enables/disables the checkbox.
checkEmails is run every time an input changes, and when the page loads the first time:
$(document).ready(function () {
function checkEmails() {
var nonempty = $('form .email_contactopadrino').filter(function() {
return $(this).val() != '';
});
if (nonempty.length) {
$('#enviarForm').removeAttr('disabled');
}
else {
$('#enviarForm').attr('disabled', true);
}
};
$('form').on('keyup change', '.email_contactopadrino', checkEmails);
checkEmails();
});

Global click event blocks element's click event

This should happen
If the user clicks on one of the two input boxes, the default value should be removed. When the user clicks elswhere on the webpage and one text field is empty, it should be filled with the default value from the data-default attribute of the spefic element.
This happens
When somebody clicks somewhere on the page and the field is empty, the field will be filled with the right value, but when somebody clicks in the field again the text isn't removed. It seems like the $(document) click event is blocking the $(".login-input") click event, because the $(".login-input") is working without the $(document) click event.
JSFiddle
A sample of my problem is provieded here: JSFiddle
Tank you for helping!
When you click on the input, the script is working, but since the input is in the document, a click on the input is a click on the document aswell. Both function will rune, document is the last one.
That is called event bubblingand you need to stop propagation :
$(document).ready(function () {
$(".login-input").click(function (e) {
e.stopPropagation()
$(this).val("");
});
});
Fiddle : http://jsfiddle.net/kLQW9/3/
That's not at all how you solve placeholders, you do it like so :
$(document).ready(function () {
$(".login-input").on({
focus: function () {
if (this.value == $(this).data('default')) this.value = '';
},
blur: function() {
if (this.value == '') this.value = $(this).data('default');
}
});
});
FIDDLE
Preferably you'd use the HTML5 placeholder attribute if really old browsers aren't an issue.
EDIT:
if you decide to do both, check support for placeholders in the browser before applying the javascript :
var i = document.createElement('input'),
hasPlaceholders = 'placeholder' in i;
if (!hasPlaceholders) {
// place the code above here, the condition will
// fail if placeholders aren't supported
}
Try below code
$(document).ready(function () {
$(".login-input").click(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").each(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
Check fiddle
Why not to use focus and blur events?
$(document).ready(function () {
$(".login-input").focus(function () {
$(this).val("");
});
});
$(document).ready(function () {
$(".login-input").blur(function () {
if ($(this).val() === "") {
$(this).val($(this).attr("data-default"));
}
});
});
http://jsfiddle.net/kLQW9/5/
P.S. In yours, and this code, on focus all data fro input will be cleared. If you need to clear only default text, add proper condition for that.

Keeping the submit button disabled until a change is made

In my VB.NET project, I have a UI with some text input fields and a save/submit button. I want the save button to be in a disabled state on page load, and remain that way until a change is made to one of the inputs. And the save button should get disabled again if the values entered by the user are the same as they were at page load. So basically, the save button should be enabled only when there is an actual change.
How can I do this using jquery?
$(':input').change(
function(){
$("#submitButtonId").prop("disabled",false);
}
);
since you said it is dynamic, use on.
$(document).on("change", ":input",
function(){
$("#submitButtonId").prop("disabled",false);
}
);
You can handle that in the change event
$('input[type="text"]').on('change', function() {
// Change event fired..
$('input[type="submit"]').prop('disabled', false);
});
//This will bind all existing and dynamically added selects onChange to the handler
$(document).on('change', function(e) {
onChangeHandler();
}
// handle the event
function onChangeHandler() {
if (checkValues()) {
$('#yourButtonId').prop("disabled", false);
}
else {
$('#yourButtonId').prop("disabled", true);
}
}
// check all values against originals - data-* attributes are a good way to store data on
// an element. So have you can have:
<select id="id1" data-originalvalue="myValue"></select>
// compare the current value to the original value - if any one of them differ, return
// true
function checkValues() {
$.each($('select[data-originalvalue]'), function() {
if ($(this).val() !== $(this).attr(data-originalvalue){
return true;
}
return false;
});
}

Check if input was not changed

It is possible to check if a input was not changed using change() event?
I'm working with <input type='file' /> and i want to warning the user that no changes was made on his own action.
Right now, i just made a normal change() event:
// fire the thumbnail (img preview)
$("#file-input").on("change", function () {
readURL(this); // create the thumbnail
});
what i'm missing ?
Prev Solutuib:
well, i found a workaround for this, the real problem is that i give a option to the user to hide the thumbnail, and if he wants, open again...
but the thumbnail will only open when the user select a image, that's the problem, because the change event fire this option to open, so, if no change, no thumbnail open.
so, when i hide the thumbnail, i change the input file for a new one, making the change event always fire.
Use a variable to store the last value of the input, and compare to the current value on change event, if they are the same, no change was made :
var last_value = $("#file-input").val();
$("#file-input").on("change", function () {
if (this.value === last_value) alert('no change');
last_value=this.value;
});
EDIT: Or you can always just replace the input tag with another, like this SO answer suggest :
var $c = $("#container");
var $f1 = $("#container .f1");
function FChange() {
alert("f1 changed");
$(this).remove();
$("<input type='file' class='f1' />").change(FChange).appendTo($c);
}
$f1.change(FChange);
<input type="file" id="file-input" data-url="intial-value" />
$("#file-input").on("change", function () {
if($(this).val() != $(this).data('url'){
//value has changed
$(this).data('url', $(this).val())
}
else{
return false;
}
});
$("#file-input").on("change", function () {
if($(this).data('last-val')){
// do something
} else {
$(this).data('last-val',$(this).val());
//do something else
}
});

Categories

Resources