Go to page based on input entry jquery - javascript

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>

Related

How do I add a second function to a button?

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.

why wouldn't either of document.location or window.location work?

This is the event handler I set up on a button:
$('.tabsTD').on('click', 'a.finalSave', (function () {
var returnStatus= finalSave(this, location);
if (returnStatus) {
if ($(this).text() == "Save and Continue") {
sessionStorage.carePlanReload = "true";
sessionStorage.activeTab = $('#tabs').tabs("option", "active");
window.event.returnValue = false;
document.location.reload(false);
}
else if ($(this).text() == "Save and Close") {
window.event.returnValue = false;
document.location = "MemberHome.aspx";
//setTimeout(function () { document.location = "MemberHome.aspx"; }, 500);
//return false;
//$('#aRedirectToHome')[0].click();
return false;
}
} /*END if*/
}));
In the else if condition, I need to redirect to "memberhome.aspx", but nothing seems to work. I also tried adding an anchor tag, like:
RedirectToHome
and then invoke a click on the anchor from else if, but it proved to be a failed attempt.
Please help.
You need to either pass a new value to the href property as in:
window.location.href = "MemberHome.aspx";
or, using assign method as in:
window.location.assign("MemberHome.aspx");

DOM not being manipulated from inside a function that is being triggered properly

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');
}
}
});

Form refresh after .submit() event

I am validating a form that's working fine but i don't know why the form not submit after all validations.
Here is validation code:
$('#coupon_options').submit(function(e){
e.preventDefault();
var name = $('input[name="coupon_name"]'),
code = $('input[name="coupon_code"]'),
value = $('input[name="coupon_value"]'),
valid = $('input[name="coupon_valid"]'),
status = true;
if( $.trim(name.val()) == "" ){
name.css('border-color', '#ff0000');
status = false;
} else { name.removeAttr('style'); }
if( $.trim(code.val()) == "" ){
code.css('border-color', '#ff0000');
status = false;
} else { code.removeAttr('style'); }
if( $.trim(value.val()) == "" ){
value.css('border-color', '#ff0000');
status = false;
} else { value.removeAttr('style'); }
if( $.trim(valid.val()) == "" ){
valid.css('border-color', '#ff0000');
status = false;
} else { valid.removeAttr('style'); }
if( status == true ){ return status; }
else { return false; }
});
As i know to stop the refresh after submit event i have used the return false but i am not sure return true works here or not?
I don't want to use Ajax, just want to submit after validation.
Is there something wrong in this code??
remove:
e.preventDefault();
it stopping the default action to occur even you return true;.
For example:
Prevent a submit button from submitting a form
Prevent a link from following the URL
e.preventDefault(); is the issue, but you should note that it's never a good sign when you have multiple functions that basically perform the same action for different elements, you can simplify your code to this:
$('#coupon_options').submit(function(e){
var status = true;
$('input[name="coupon_name"],input[name="coupon_code"],input[name="coupon_value"],input[name="coupon_valid"]').each(function(){
if($.trim($(this).val()) == ""){
$(this).css('border-color', '#ff0000');
status = false;
} else {
$(this).removeAttr('style');
}
});
return status;
});
And you could even use $('input[name^="coupon_"]') to select all inputs that start with that prefix.

trigger jquery key event only outside form element

Is it possible to trigger a key event only outside a form element?
Background: I have a code that loads the next page when the right key is pressed. But I don't want to trigger that event if somebody is using that key in a form element.
current code:
$(document).keydown(function(e){
if (e.keyCode == 37) {
var url = $('a#left').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
if (e.keyCode == 39) {
var url = $('a#right').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
});
If you have other fields outside your form this might be quite useful I hope
LIVE DEMO
document.onkeyup = function( ev ){
var key = ev.which || ev.keyCode ,
aID = { 37:"left", 39:"right" };
if( ! (/INPUT|TEXTAREA/i.test(ev.target)) && aID[key]) {
var url = document.getElementById( aID[key] ).getAttribute('href');
window.location = url;
}
};
Here is a basic example of the concept. Your simply adding an event handler to the document and checking that its target does not have a parent that is a form.
HTML
<form>
Inside form
<input/>
</form>
Outside form
<input />
Javascript
$(document).keyup(function(event){
if($(event.target).parents("form").length == 0){
alert("here");
}
});
Working POC: http://jsfiddle.net/48NYE/
This concept can be easily applied to the script you have provided.
Modification for your Script
$(document).keydown(function(e){
var outsideForm = $(e.target).parents("form").length == 0;
if (e.keyCode == 37 && outsideForm) {
var url = $('a#left').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
if (e.keyCode == 39 && outsideForm){
var url = $('a#right').attr("href");
if (url != '') { // require a URL
window.location = url; // redirect
}
return false;
}
});

Categories