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.
Related
Hi, I have written a webSite on Shopify and I want to disable my button and add some customs CSS class to my input if the input is not filled on my 4steps form.
I've written a piece of code with what I remember from Jquery it's been a long time since I've used this language.
This is the jQuery funct:
$(document).ready(function () {
$("#submitButton, #btn0, #btn1, #btn2").click(function () {
ValidateForm();
});
function ValidateForm() {
var invalidForm = false;
var index = 0;
var button = document.querySelector("#submitButton, #btn0, #btn1, #btn2");
$("#form__form--stepForm-" + index + "input.form__form--input").each(function () {
if ($(this).val() < 1) {
invalidForm = true;
}
});
if (invalidForm === true) {
button.disabled = true;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationInvalid");
} else if (invalidForm === false) {
button.disabled = false;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationValid");
index++;
}
}
});
I made all my inputs like this one:
<div class="3/3 3/3--thumb 3/3--pocket grid__cell--center">
<input type="text" id="form__form--lastnameInput" name="contact[lastname]"
class="form__form--input form__form--validation" placeholder="Nom *" value required>
<div class="form__form--invalidFeedback">Veuillez saisir votre nom.</div>
</div>
And the button like this:
<button id="btn0" type="button" class="button button--primary form__form--button"
aria-label="SUIVANT" title="SUIVANT">
{% include 'icon-arrow-slider' %}
SUIVANT
</button>
As you can see it's a very basic function for the jquery and a classic HTML input but it doesn't block the button and doesn't make the CSS work either. I'd like to understand why and how to make it work for this site and the following thanks for your time and help, take care of yourself!
Your value checking is always false, consider using length function instead:
if ($(this).val().length < 1) {
invalidForm = true;
}
You may also need to prevent default behavior of your form. Instead of listening to the click, listen the submit event:
$("#form__form--contactWrapper").on('submit',function (e) {
e.preventDefault(); //the form is not sent yet
ValidateForm();
});
Then at the end of your function ValidateForm you can send it when you have all your needed validations done, like this:
$("#form__form--contactWrapper").submit();
I have get rid of all error by doing a big refacto of my code i share you my code
$(document).ready(function () {
$('[to-step]').on('click', function () {
var to_step = $(this).attr("to-step");
var current_step = $(this).closest('[stepform]').attr("stepform");
var form_error = false;
if (!($(this).hasClass("previous-btn"))) {
$('[stepform="' + current_step + '"] .form__form--input').each(function () {
if ($(this).val().length == 0) {
$(this).addClass("input--error");
form_error = true;
} else {
$(this).removeClass("input--error");
}
});
}
if (!form_error) {
if (current_step < 4 || $(this).hasClass("previous-btn")) {
$('[stepform').hide();
$('[stepform="' + to_step + '"]').fadeIn();
}
}
});
$("#submitButton").on("click", function (event) {
event.preventDefault();
if ($("#form__form--radioRgpd:checked").length == 1) {
$("#contact_form").submit();
} else {
$(".form__form--radioRgpdLabel").addClass("label--error");
}
});
});
this piece of code gonna check at what step i am in my 4 'pages' form and add the proper css class if the form is bad filled or not filled.
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 this form to redirect me to a page based on what is in the input fields. The problem is that i see the console.log but the page simply refreshes instead of taking me to the page i want to go
input has id="inputLink"
submit has onsubmit="submitPage()"
The function
var inputVal = $('#inputLink');
function submitPage(){
$(inputVal).on('keypress', function(event) {
if (event.keyCode == 13) {
if($(inputVal).val() == 'home'){
window.location.href = 'index.php';
console.log('1');
}else if($(inputVal).val() == 'services'){
window.location.href = 'services.php';
console.log('2');
}else if($(inputVal).val() == 'portfolio'){
window.location.href = 'portfolio.php';
console.log('3');
}else if($(inputVal).val() == 'about'){
window.location.href = 'about.php';
console.log('4');
}else if($(inputVal).val() == 'contact'){
window.location.href ='contact.php' ;
console.log('5');
}else{
alert('undefined');
console.log('6');
}
}
});
}
Change onsubmit to onsubmit="submitPage(); return false;". Also your logic can be greatly simplified by changing the home value to index and implementing the following.
$('#inputLink').on('keypress', function(event) {
if (event.keyCode == 13) {
var where = $('#inputLink').val();
window.location.href = where + '.php'
}
}
I would recommend adjusting your jquery to be prepared once the page has loaded -- you don't need to have it in it's own function since jquery is capable of listening for events on its own. I would also remove the onsubmit event attribute since a "submission" implies that you are submitting form data, but in this case, your input and accompanying button is acting as a dynamic link. You can also clean up the jquery a little by better utilizing your inputVal variable.
<script>
$(function() {
var inputVal = $('#inputVal').val();
$('#goLink').on('click', function(event) {
if (event.keyCode == 13) {
if(inputVal == 'home') {
window.location.href = 'index.php';
console.log('1');
} else if(inputVal == 'services') {
window.location.href = 'services.php';
console.log('2');
} else if(inputVal == 'portfolio') {
window.location.href = 'portfolio.php';
console.log('3');
} else if(inputVal == 'about') {
window.location.href = 'about.php';
console.log('4');
} else if(inputVal == 'contact') {
window.location.href ='contact.php' ;
console.log('5');
} else {
alert('undefined');
console.log('6');
}
}
});
})
</script>
And then you could use this HTML without a form:
<input id="inputLink" type="text"></input>
<input id="goLink" type="button">Go!</input>
I added a redirect function when refresh button or user try to exit the page they get redirected but what I want to happen is this function to be unload or not executed when they click my button
<a onClick="alert(you are going to tweeter);"href="http://twitter.com" class="tweetbutton" >I Like Twitter</a>
so what happens is it conflicts and two alerts shows up, what I was needing is when the tweetbutton button is click the onclick alert will the one to appear then get redirected to twitter.com without the function below being executed
(function() {
setTimeout(function() {
var __redirect_to = 'http://facebook.com';
var _tags = ['btn', 'input'],
_go, _i, _i2;
for (_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for (_i2 in _go) {
if ((_tags[_i] == 'input' && _go[_i2].type != 'btn' && _go[_i2].type != 'submit' && _go[_i2].type != 'image') || _go[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {
window.onbeforeunload = function() {};
}
}
}
window.onbeforeunload = function() {
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function() {
document.location.href = __redirect_to;
});
});
return 'you are leaving this page'
}
});
});
Update you code as follows:
<a "href="http://twitter.com" class="tweetbutton" >I Like Twitter</a>
Add this to your js
document.addEventListener('click', function (e) {
if (e.target.className == 'tweetbutton') alert('you are going to twitter');
});
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);
});
});