Please can you provide me some short help with my Javascript code. I have one input field which hides DIV element just if it is totally empty (without text):
if (search_value !== "") {
document.getElementById("frei").className = "frei1";
}
It does exactly what I want, the main problem is once the input field is activated by typing inside and when I start to erase the text until the input is empty, than my hidden DIV appear, even if the input contain no text (because I erased it). This function is good only on first page load, than when I type anything in input and erase it, my JavaScript code is not functional.
Please could you give me an advice how looks like Javasript code, which hide that DIV everytime input field contain no text? Even when the text was erased manually?
Thank you very much and apologize for that type of question. Iam not strong in basic Javascript.
That code will only execute on page load, yet you want it to run each time someone types into your input, to do that you can use the onkeyup event:
document.getElementById("yourInput").onkeyup = function () {
if (this.value !== "") {
document.getElementById("frei").className = "frei1";
}
else {
document.getElementById("frei").className = "";
}
};
DEMO
If you also need it to run on page load aswell however, extract it out to a function and then you can call the function on page load as well:
function setDisplay() {
if (document.getElementById("yourInput").value !== "") {
document.getElementById("frei").className = "frei1";
}
else {
document.getElementById("frei").className = "";
}
}
Then call it on page load:
setDisplay();
Then also attach it to the onkeyup event like we did in the first instance:
document.getElementById("yourInput").onkeyup = setDisplay;
document.getElementById("id").oninput = function() {
if (this.value !== "") {
document.getElementById("frei").className = "frei1";
}
}
or
document.getElementById("id").addEventListener('input',function() {
if (this.value !== "") {
document.getElementById("frei").className = "frei1";
}
}, false);
Related
I have a JS where I can verify if the a value is being entered and warn the user to change the input.
the script is working fine only if only that value exist in the text and if the value with some other text will not work.
$(function() {
const setup = function(fieldSelector) {
const field = $(fieldSelector);
const applyStyle = function() {
if (field.val() == 'urgent')
{
alert("Text not allowed!");
field.css({'background-color': 'red'});
} else {
field.css({'background-color': ''});
}
};
field.on('change', applyStyle);
applyStyle();
}
// Note: Change the ID according to the custom field you want to target.
setup('#issue_custom_field_values_17');
});
this code is under redmine issue tracker.
Any guidance will be much appreciated
I'm very unfamiliar with jQuery, but couldn't you just replace
if (field.val() == 'urgent')
with
if (field.val().includes('urgent'))
or even
if (field.val().indexOf('urgent')>-1)
I have a couple of forms on a site. On the first form I used the code below to add a border color if the input field is not blank and remove it if it is blank. This works just fine no issues. But I've found that when I try to use the same method on other forms, to do something else using the same logic, it does not work.
I have read through many forums and what I'm seeing is that the code is only read on page load. But I have forms that run the function after the page is far past loading. Can someone give some light to this? I'm really trying to understand the way this works fully.
Code that works on form:
var checkErrorIn;
jQuery(document).ready(function ($) {
checkErrorIn = setInterval(CheckErrorInput, 0);
});
function CheckErrorInput() {
if (jQuery('body').is('.page-id-6334')) {
// First Name, Last Name validation colors
var pasdFName = jQuery('#first_name').val();
var pasdLName = jQuery('#last_name').val();
if (pasdFName != '') {
jQuery('#first_name').addClass('formConfirm_cc');
} else {
jQuery('#first_name').removeClass('formConfirm_cc');
}
if (pasdLName != '') {
jQuery('#last_name').addClass('formConfirm_cc');
} else {
jQuery('#last_name').removeClass('formConfirm_cc');
}
if (pasdFName != '' & pasdLName == '') {
jQuery('#last_name').addClass('formError_cc');
} else {
jQuery('#last_name').removeClass('formError_cc');
}
if (pasdFName == '' & pasdLName != '') {
jQuery('#first_name').addClass('formError_cc');
} else {
jQuery('#first_name').removeClass('formError_cc');
}
}
}
Code that is not working:
if (jQuery('body').is('.woocommerce-page')) {
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
jQuery('.woo_login_form').on('input', function(){
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
if (checkActiveName =='') {
jQuery('.woo_login_form').removeClass('cdc_keep_active');
}
}
What I am trying to do is fix an issue with a form becoming hidden if not hovered over even when the input has characters. Based on my research I figured I'd do the .on to get the class added when the input got characters. That works but the removal of the characters isn't removing the class. The logic looks right to me. What am I missing?
Thank you in advance for your help and insight.
Update:
Ok so I ended up doing this:
jQuery('.woo_login_form').on('click', function () {
jQuery('.woo_login_form').addClass('cdc_keep_active');
});
jQuery('.custom-login-box > a').on('click', function () {
jQuery('.woo_login_form').toggle();
});
For some reason my class would not add with any of the methods suggested individually so I combined the logic. The first part adds the class that makes the form visible but then the form won't close if clicked out of regardless of the 'removeClass'. So I added a toggle (thank you commenters) method to the "hovered link" to allow users to close the box if not needed.
Would still like to understand why the first method worked in one instance but not the other. Any and all insight appreciated. Thank you.
In your current code example you immediately check for the value of the username field.
var checkActiveName = jQuery('.woo_login_form > form > #username').val();
The thing with this is that checkActiveName will never change, unless it is reassigned elsewhere in the code.
What you need to do is to check the current value after every input of the user. That means moving that line of reading the value of the input inside the input event listener.
if (jQuery('body').is('.woocommerce-page')) {
var $wooLoginForm = jQuery('.woo_login_form');
var $userName = jQuery('#username'); // This ID should only exist once, so no need for complex selectors.
$wooLoginForm.on('input', function() {
var checkActiveName = $userName.val();
if (checkActiveName =='') {
$wooLoginForm.removeClass('cdc_keep_active');
} else {
$wooLoginForm.addClass('cdc_keep_active');
}
});
}
On a sidenote: using setInterval to validate your form is a bad practice. This would basically run infinitely. It doesn't have to. You only have to check if a form is valid after the user enters a value.
Apply the same technique with the event listener like in your second code snippet.
var $document = jQuery(document);
$document.ready(function ($) {
/**
* It might even be better to listen for the input event on the form
* that has to be validated, but I didn't see it in your code.
* Right now it listens for input on the entire page.
*/
$document.on('input', CheckErrorInput);
});
I'm trying to add a disabled class to an input if the value of the input is empty and remove it if the input has content value. Here is my current take on this that doesn't work:
if ($("#assignment_name").val() == "") {
$(".to_description").addClass("disabled");
};
This adds the class on load but it doesn't remove the class if someone types in the field. How can I achieve this?
You could use removeClass binded to an event that triggers when user enters text, such as keyup, for example:
$("#assignment_name").on('keyup', function() {
if ($("#assignment_name").val() == "") {
$(".to_description").addClass("disabled");
} else {
$(".to_description").removeClass("disabled")
}
});
You're just adding the class when first loading it, besides that you need to add an "onChange" event handler to check further changes on this input.
if ($("#assignment_name").val() == "") {
$(".to_description").addClass("disabled");
$("#assignment_name").on("change", function() {
if($(this).val() == "") {
$(".to_description").addClass("disabled");
} else {
$(".to_description").removeClass("disabled");
}
});
};
I have an input, when the user enters something, my script sends the info over to a php script, which returns whether or not the entered text can be used.
If the text can not be used, it disables the submit button and adds a class to the reult text.
The problem have is strange, the ajax works, the result is returned, but the button disabling and adding of the class doesn't happen unless you focus and blur the input a second time.
Here is my code:
$('#alias').blur(function() {
if ($('#alias').val()) {
var aliascheck = $('#alias').val();
$(".aliascheck").load('checkalias.php?alias='+aliascheck);
var result = $('.aliascheck').text();
if (result.indexOf("Taken") != -1) {
$('#shorten').attr("disabled","disabled");
$('.aliascheck').addClass('error');
} else {
$('#shorten').removeAttr("disabled");
$('.aliascheck').removeClass('error');
}
}
});
The code is live here: http://markhenderson.ws/dev/tmtmu/
To replicate the "taken" event, enter "taken" as the alias. Any thing else will return available.
Does anyone know why this is happening?
Thanks
You need to put the code after the .load call into a callback function of the async call.
Something like:
$('#alias').blur(function() {
if ($('#alias').val()) {
var aliascheck = $('#alias').val();
$(".aliascheck").load('checkalias.php?alias='+aliascheck, function() {
var result = $('.aliascheck').text();
if (result.indexOf("Taken") != -1) {
$('#shorten').attr("disabled","disabled");
$('.aliascheck').addClass('error');
} else {
$('#shorten').removeAttr("disabled");
$('.aliascheck').removeClass('error');
}
});
}
});
Basically the same functionality as stackoverflow when posting a question, if you start writing a post then try to reload the page. You get a javascript alert box warning message.
I understand how to check if the form has been changed, although how do I do the next step.
I.E: How to I check this when leaving the page, on here you get "This page is asking you to confirm that you want to leave - data you have entered may not be saved."?
EDIT: found correct answer here to another question https://stackoverflow.com/a/2366024/560287
I'm very sure that if you search, 'jQuery detect form change plugin', you will find something much more usable than this semi-pseudo code i'm about to write:
formChanged = function(form) {
form.find('input[type="text"], textarea').each(function(elem) {
if (elem.defaultValue != elem.value) {
return true;
}
});
// repeat for checkbox/radio: .defaultChecked
// repeat for ddl/listbox: .defaultSelected
return false;
}
usage:
if (formChanged($('form')) { // do something }
Note that this is to detect changes against the original rendered value. For instance, if a textbox has a value = "x", and the user changes it to "y", then changes it back to "x"; this will detect it as NO change.
If you do not care about this scenario, you can just do this:
window.formChanged = false;
$(':input').change(function() {
window.formChanged = true;
});
Then you can just check that value.
Yes, it is JavaScript as HTML is just a markup language.
Yes, jQuery can be used for this. It's preferable over vanilla JavaScript as it makes things easier, although it does add some overhead.
There are a number of ways to check if any of a form's controls have changed.
To check for changes from the default, most can be checked against the defaultValue property. For radio buttons, you should always have one checked by default, so check if it's still selected or not. Similarly for selects, set the selected attribute for the default option and see if it's still selected, and so on.
Alternatively, if all your form controls have an ID or unique name, you can collect all their values onload and then check their values when the form is submitted.
Another method is to listen for change events on each form control, but that is a bit over the top.
Here's a POJS version that takes the same approach as rkw's answer:
/*
Check if any control in a form has changed from its default value.
Checks against the default value for inputs and textareas,
defaultChecked for radio buttons and checkboxes, and
default selected for select (option) elements.
*/
function formChanged(form) {
var control, controls = form.elements;
var tagName, type;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
tagName = control.tagName.toLowerCase();
type = control.type;
// textarea
if (tagName == 'textarea') {
if (control.value != control.defaultValue) {
return true;
}
// input
} else if (tagName == 'input') {
// text
if (type == 'text') {
if (control.value != control.defaultValue) {
return true;
}
// radio and checkbox
} else if (type == 'radio' || type == 'checkbox') {
if (control.checked != control.defaultChecked) {
return true;
}
}
// select multiple and single
} else if (tagName == 'select') {
var option, options = control.options;
for (var j=0, jLen=options.length; j<jLen; j++) {
option = options[j];
if (option.selected != option.defaultSelected) {
return true;
}
}
}
}
// Not really needed, but some like the return value to
// be a consistent Type
return false;
}
Note that you need to be careful with select elements. For a single select, you should always set one option to selected, as if there is no default selected, some browsers will make the first option selected and others wont.