I have an input that is empty after page load, and if a user suddenly fill a value on it the value of the two inputs on the if condition should change to.
My problem is when I fill an input, the if condition result doesn't changed in real time.
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
function emailName(){
if($('#emailCodeResult').val() != '' || $('#email').val() == ''){
clearInterval(countTimerEmailName);
}
$.ajax({
url:"view.php",
type:"GET",
data: { term : $('#email').val() },
dataType:"JSON",
success: function(result) {
}
});
};
});
Fire your function on change
$('#inputA, #inputB').change(function(){
if($('#inputA').val() != '' || $('#inputB').val() == '') {
alert("True");
}else{
alert("False");
}
})
You can use keyup like this:
$('#textboxID').on( 'keyup', function () {
//write your code here
});
For touch devices as rzr siad keyup won't occur.
You can write a function that is called every, say 1 sec or whatever, like this:
t1=window.setInterval(function(){foo()},1000);
function foo()
{
// write function definition here
}
or use blur as others suggested, if the you want to check value only after the user is done with that textbox and moves to next field.
var fieldcheck;
$(function() {
$("#input").focus(function() {
fieldcheck = setInterval(function() {
var innerValue = $("#input").val();
if (innerValue == "") {
// Your code
} else {
// Your code
}
}, 100);
});
$("#input").blur(function() {
clearInterval(fieldcheck);
});
});
Related
Say I have a standard HTML link like so:
<a href='https://whateverdomain.com/whatever.pdf' class='pdf-download'>
How can I both link to that .pdf and fire a jQuery function at the same time?
I've written this so far:
$('.pdf-download').addEventListener('click', function() {
$.getJSON('/documents/email', function(email) {
if (email.documentID && email.message == 'success') {
console.log('Sending email...');
};
},
false);
But that just prevents my button from being clickable. I should mention that that listener is part of a bigger function:
function checkForAnswers() {
var count = $('.pdf-checklist').filter(function() {
return $(this).val() !== "";
}).length;
var total = $('.pdf-checklist').length;
$('.pdf-download').addEventListener('click', function() {
$.getJSON('/documents/email_press_ad', function(email) {
if (email.documentID && email.message == 'success') {
console.log('Sending email...');
};
}, false);
if (count == total) {
$('.pdf-download').removeClass('disabled');
$('.pdf-download').removeAttr('disabled');
} else {
$('.pdf-download').addClass('disabled');
$('.pdf-download').attr('disabled', 'disabled');
}
console.log(count + '/' + total);
}
$('.pdf-checklist').on('keyup', checkForAnswers);
You could try just binding it with on
$(".pdf-download").on("click", function (e) {
e.preventDefault();
//do your stuff.
//navigate to a click href via window.location
window.location = $(this).attr('href');
});
So you cancel the click default event and manually force the url change after code is complete.
Editted according to comments.
I have written this function to validate that all form fields and check boxes in a form are filled out. The script automatically disables the submit button and then watches for the moment at which it can be re-enabled. My debugger statements are landing me in all of the proper places, but for some reason, the DOM element is not being updated. I'm sure I am just making a stupid mistake, but can't seem to find a solution. Thank you in advance for any help!
Specifically looking at this section:
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
Here is the whole script below.
$(document).ready(function() {
validateInput();
$('.validate').keyup(function(event){
validateInput();
});
$('[type=checkbox]').click(function(event){
validateInput();
});
function validateInput() {
var valid = 0;
var checkBox = $('[type=checkbox]');
var inputFields = $('input.validate');
var inputLength = inputFields.length + checkBox.length;
inputFields.each(function() {
if($(this).val() !== '') {
valid++ ;
}
});
checkBox.each(function() {
if($(this).prop('checked')) {
valid++ ;
}
});
if(valid === inputLength) {
updateBtnStatus('enable')
} else {
updateBtnStatus('disable')
}
}
function updateBtnStatus(status) {
var btn = $('input[type="submit"]');
if (status === 'enable') {
btn.removeAttr('disabled');
btn.removeClass('disabled');
} else {
btn.prop('disabled', true);
btn.addClass('disabled');
}
}
});
I want to combine each and change with jQuery.
This is my code:
$( document ).ready(function() {
$('.doetmee').each(function() {
var thisval = $(this).val()
if(thisval == 'ja')
{
$(this).parent().parent().find('.facebookadv').attr('disabled',false);
}
else
{
$(this).parent().parent().find('.facebookadv').attr('disabled',true);
$(this).parent().parent().find('.facebookadv').val('');
}
$('.doetmee').change(function(){
if(thisval == 'ja')
{
$(this).parent().parent().find('.facebookadv').attr('disabled',false);
}
if(thisval == 'nee' || thisval == 'leeg')
{
$(this).parent().parent().find('.facebookadv').attr('disabled',true);
$(this).parent().parent().find('.facebookadv').val('');
}
});
});
});
It only changes 1 time and after that it doesn't work.
How can I make sure it works everytime I make a change?
I have tried many things that I could find on stackoverflow or google but without success.
If the value is leeg or nee the select on facebook must be disabled.
You need to make each and change register the same function.
$( document ).ready(function() {
var updateFields = function() {
var thisval = $(this).val()
if(thisval == 'ja')
{
$(this).parent().parent().find('.facebookadv').attr('disabled',false);
} else {
$(this).parent().parent().find('.facebookadv').attr('disabled',true);
$(this).parent().parent().find('.facebookadv').val('');
}
};
$('.doetmee').each(updateFields);
$('.doetmee').change(updateFields);
});
In the above example, the function is stored in the variable updateFields (so the code is only written once) and is then registered to both each and change.
TL;DR - Anyone know why a click handler would only work on refresh?
If I have a function like so:
function selectState() {
$('#state-select').change(function(event) {
var state = $(this).val();
$("#vmap").find(("#jqvmap1_") + (state.toLowerCase(''))).click();
});
}
and I have that function run like so:
function setClickHandlers() {
$(document).on('click','a#reset_tracker',function(event) {
event.preventDefault();
$.get('decisiontree/reset_tracker/', function(data) {
window.location.reload();
});
});
if ($('#vmap').length !== 0) {
setTimeout(function(){
$('#vmap').bind('regionClick.jqvmap', function(event, code, region) {
$('#state-select').val(code.toUpperCase());
});
selectState(); //once the map loads, we should be able to select things, right
}, 500);
}
}
Which is then called by:
function setupSlide() {
setClickHandlers();
if ((typeof $.fn.vectorMap !== "undefined" && $.fn.vectorMap !== null) &&
$('#vmap').length !== 0) {
$('#vmap').vectorMap({
map: 'usa_en',
backgroundColor: null,
color: '#6a1912',
hoverColor: '#fdb33f',
selectedColor: '#fdb33f',
enableZoom: true,
showTooltip: true,
onRegionClick: function(event, code, region) {
event.preventDefault();
$('#state-select').val(code.toUpperCase());
}
});
}
}
Which is called by:
$(document).ready(function() {
setupSlide();
$(document).on('click','.prev', function(event) {
event.preventDefault();
loadSlide(prev_slide_url,{});
});
$(document).on('click','.next', function(event) {
event.preventDefault();
var answer;
if ($(this).hasClass('button') || $(this).hasClass('button-small')) {
answer = $(this).val();
} else if ($(this).hasClass('arrow')) {
answer = $('input[type=checkbox].answer:checked').val();
if (!answer && $('input[type=checkbox]').length > 0) {
$("p.inactive").addClass("error");
return false;
}
if ($("#vmap").length > 0) {
//for the map, the value is in the select
answer = $('#state-select').val();
if ($("#state-select").val().length === 0) {
$("p.inactive").addClass("error");
return false;
}
}
} else if ($(this).hasClass('navbutton')) {
answer = $(this).data('val');
}
loadSlide(next_slide_url,{answer: answer});
});
});
Why would the click method in SelectState only be invoked when the page that contains that function (namely, the page that has #vmap on it) is refreshed, rather than when the next or prev buttons (which have functionality defined in the document.ready block of code) are clicked? Is there something special about click handlers in this sort of context? I'm really unsure as to what is going on incorrectly.
One thing that I will add is that #jqvmap1_ refers to a path element in an SVG map, namely a map of the United States. But since it works on refresh, I don't think that it has to do with the fact that it is a path element.
Let me know if you need additional clarification for this problem. Apologies for the messy code.
I have a form which on submit should see if the text area has no text or the place holder text.
iif it does it shouldn't submit it. something like validation. I am not able to stop the form submission.
$(document).ready(function () {
var options = {
target: '.user-status',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse,
// post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
$('#updateStatus').submit(function () {
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
function showRequest(formData, jqForm, options) {
var textbox = $('#StatusMessageMessage').val();
if ((textbox == '') || (textbox == "What have you been eating ?")) {
alert(text);
return false;
} else {
$('#StatusMessageMessage').attr('disabled', true);
}
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
}
statusMEssagebox();
});
function statusMEssagebox() {
var textholder = $('#StatusMessageMessage').val();
$('#StatusMessageMessage').focus(function () {
if ($(this).val() == textholder) $(this).val("");
$(this).animate({
"height": "48px",
}, "fast");
$('.share').slideDown("fast");
$(this).TextAreaExpander(48, 75);
});
$('#StatusMessageMessage').blur(function () {
if ($(this).val() == "") {
$(this).val(textholder);
$('.share').slideUp("fast");
$(this).animate({
"height": "18px",
}, "fast");
}
});
}
I see that you are using the jquery form plugin to ajaxify your form. There's an example in the documentation illustrating how to achieve this in an elegant way. You don't need to subscribe for the .submit event of the form and manually submit it using .ajaxSubmmit. You could simply try this:
$(function() {
$('#updateStatus').ajaxForm({
beforeSubmit: function(formData, jqForm, options) {
var value = $('#StatusMessageMessage').val();
if (value == '' || value == 'What have you been eating ?') {
return false;
}
}
});
});
You are using equality operator rather than comparison.
This:
if ((textbox = '') || (textbox = "What have you been eating ?")) {
Problem -----^
Should be:
if (textbox == '' || textbox == "What have you been eating ?") {
You may also want to see how the submit form via Ajax using jQuery:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/