I made an autocomplete for a form input field that allows a user to add tags to a list of them. If the user selects any of the suggestions, I want the page to use add the new tag to a section of tags that already exist without the page reloading.
I want this to happen with 3 scenarios:
The user types in the tag, ignores the autocomplete suggestions and presses enter.
After typing in any part of a query, the user selects one of the autocomplete suggestions with the arrow keys and presses enter.
After typing in any part of a query, the user clicks on one of the autocomplete suggestions with the mouse.
I have been able to make scenario 1 work flawlessly. However, scenarios 1 and 2 make the page reload and still doesn't even add the tag to the list.
Scenarios 1 and 2 are both called by the same function:
$j("#addTag").autocomplete({
serviceUrl:'/ac',
onSelect: function(val, data){
addTag(data);
}
});
And here is the code for addTag():
function addTag(tag){
var url = '/addTag/' + tag;
//Call the server to add the tag/
$j.ajax({
async: true,
type: 'GET',
url: url,
success:function(data){
//Add the tag to the displayed list of already added tags
reloadTagBox(data);
},
dataType: "json"
});
//Hide the messages that have been displayed to the user
hideMessageBox();
}
Scenario 1 code:
function addTagByLookup(e, tag){
if(e && e.keyCode == 13)
{
/*This stops the page from reloading (when the page thinks
the form is submitted I assume).
*/
e.preventDefault();
//If a message is currently being displayed to the user, hide it
if ($j("#messageBox").is(":visible") && $j("#okayButton").is(":visible")){
hideMessageBox();
}
else{
//Give a message to the user that their tag is being loaded
showMessageBox("Adding the tag <strong>"+tag+"</strong> to your station...",'load');
//Check if the tag is valid
setTimeout(function(){
var url = '/checkTag/' + tag;
var isTagValid = checkTag(tag);
//If the tag is not vaid, tell the user.
if (isTagValid == false){
var message = "<strong>"+tag+"</strong>"+
" was not recognized as a valid tag or artist. Try something else.";
//Prompt the user for a different tag
showMessageBox(message, 'okay');
}
//If the tag is valid
else{
addTag(tag);
}
}, 1000);
}
}
}
I know I used the e.preventDefault functionality for a normal form submit in scenario 1, but I can't seem to make it work with the other scenarios and I'm not even sure that is the real problem.
I am using pylons as the MVC and using this tutorial for the autocomplete.
So in case anyone wants to know, my problem was had an easy solution that I should have never had in the first place.
My input tag was embedded in a form which submitted every time the input tag was activated.
I had stopped this problem in scenario 1 by preventing the default event from occurring when the user pressed enter. But since I didn't have access to this event in the jQuery event .autocomplete(), I couldn't prevent it.
Related
I have a multi-page form created with gravity forms. It's form I use for lead generation, with the last step asking for the user's name, email, and phone number.
In the second last step before asking for user's personal info, there is a page with a "loading" gif spinner and the animated text "searching for a quote".
I need help to set up a javascript code for the second last page for when the user is on that page with the loading gif after 6.5 seconds it will automatically click the hidden page next button to take the user to the last page asking for their personal info.
I'm using the code below, which works only when the user manually clicks using the mouse or mousepad and click on the third last page. If the user enters details in the third last page and hits the enter or return key on the keyboard the code doesn't fire.
I'm not too familiar with Javascript. Just getting started learning.
I understand there's a gravity forms javascript gform_page_loaded, but that seems to fire the code on every single page rather than just when the second last page is in the user's viewport. Please help.
SEE CODE BELOW
<script type="text/javascript">
const btnSearchMortgage = document.getElementById("gform_next_button_13_16");
btnSearchMortgage.addEventListener("click", function () {
setTimeout(function () {
document.getElementById("gform_next_button_13_9").click();
}, 6500);
});
</script>
The gform_page_loaded is the way to go. You can use the currentPage parameter it passes to only trigger code on a given form page.
jQuery( document ).on( 'gform_page_loaded', function( event, formId, currentPage ) {
if ( currentPage == 2 ) {
// bind your custom event
}
} );
I am implementing my own Like/Unlike system for my website. The PHP part is already done and all working, but I'm trying to make the Like/Unlike process all asynchronous with jQuery's AJAX methods.
What I'm trying to achieve is let an user press the like button and then the like button will become yellow (like being pressed) and the URL will change to unlike and when clicked, the user will basically unlike the item and the button will get its original color again.
The liking part is already working, but I'm failing to toggle between these two.
This is what I've been trying:
HTML/TWIG:
<li><span class="glyphicon glyphicon-thumbs-up" {% if S_IMAGE_LIKED == true %}style="color: #f0c36d;" title="Unlike"{% else %}title="Like"{% endif %} data-placement="right"></span></li>
jQuery:
$('[data-image-action="likeUnlike"]').click(function(e){
var likeHref = $(this).attr('href');
var likeUnlike = (likeHref.indexOf('unlike') != -1) ? 'unlike' : 'like';
var unLikeUrl = likeHref.replace(!likeUnlike, likeUnlike); // This is wrong, but how else do I do this?
var thumbColor = (likeUnlike == 'like') ? '#f0c36d' : '#eee';
$(this).attr('href', unLikeUrl);
$('.image-options .glyphicon-thumbs-up').attr('data-original-title', ucfirst(likeUnlike));
$('.image-options .tooltip-inner').text(ucfirst(likeUnlike));
$('.image-options .glyphicon-thumbs-up').css('color', thumbColor);
$.ajax({
type: 'GET',
url: likeHref,
success: function(data){
// console.log(data); return;
var response = $.parseJSON(data);
if ('error' in response)
{
display_alert(response.error, 'danger', 3000, 'top');
return;
}
$('.likeCount').text(response.likeCount);
}
});
e.preventDefault();
return false;
});
After refreshing the page, the logic works great enough with the Twig if statements, but I want to achieve the same without having to reload the page.
So again in summary:
User clicks Like
Glyphicon turns yellow, title changes to Unlike and URL changes to unlike
User now clicks Unlike
Glyphicon turns light greyish, title changes to Like and URL changes to like
How can I achieve this? What's wrong in my code?
// This is wrong, but how else do I do this?
likeHref.replace(!likeUnlike, likeUnlike);
Basically you want to replace the current state with its reverse (which is not what the boolean NOT does for us :-) ). The current is likeUnlike, so do
var unlikeLike = (likeUnlike == 'like') ? 'unlike' : 'like';
Now, since replace does take a regular expression, we can simply match both possible wordings and replace them with the new:
var unlikeHref = likeHref.replace(/(un)?like/g, unlikeLike);
There's a lot happening in your code. Try to isolate the bits and pieces.
Firstly, your problem does not seem to have anything to do with the ajax request, unless that's throwing an exception for some reason. Changing the link url and the icon style when a user clicks on it should be simple though.
My suggestion on how proceed in debugging, step by step:
Check the browser console (eg. firebug) for any js exceptions
Ignore the ajax request and just focus on toggling the link url and icons style in the click event.
Check the value of the href attribute and all the other variables that are being set.
What is returning ucfirst, upper case first string?
Also, you will want to prevent the user clicking on the like/unlike link while the ajax request is in progress.
I hope I could help with this.
I've got a PHP file with 5 tabs (jquery ui). Tab four and five contain
forms. Forms and tab work fine - expect to this: I submit the form (POST
method not XHR), then click the right mouse button (Firefox and IE behave
identical) and select back and then select tab five in the page by mouse
click the entered form data is still available.
I try to build a link, that is more convenient for the user.
<a href="#" onClick='history.back();$("#tabs").tabs("select","4");'>modify</a>
If click on my modify link, it still jumps back to tab one and the form fields in tab five are empty.
I read several posts about jQuery UI tabs and the back button, but all seem not to address my problem.
Where is my fault and is the difference between doing this steps by hand and my link with JS?
Javascript stops executing once you leave the page that it's running on -- the second half of your onClick handler never runs.
Following from the comments here is a function that will remember what your last tab was that you selected. It does rely on you using a set "Back" button.
The problem you will find, as far as I can see, is that you can't intercept a user clicking the browser back button. I have found that creating an obvious and clear back button on the site does the job and the feedback I have had so far on our sites seem to back that up.
The function is:
$(function() {
var $previousTab = 0;
var $backButtonUsed = false;
// Initialise tabs
$("#tabs").tabs();
$("#tabs").bind("tabsselect", function(event, ui) {
if ($backButtonUsed)
{
$backButtonUsed = false;
} else {
$previousTab = $("#tabs").tabs('option', 'selected');
}
return true;
});
$("#back").live('click', function() {
$backButtonUsed = true;
$("#tabs").tabs({ selected: $previousTab });
return true;
});
});
I have also included this in a JSFiddle, so you can see it in action with the HTML and jQuery UI Tabs.
Let me know what you think.
I have the following problem. I want to move the user to another page when a certian condition is met. For example, I have a text input field where a user enters a URL. I want to move the user to this url, without him pressing any kind of submit form. I'm using AJAX to achive this. I have a function that checks for the pattern the user entered, if it is found to be a valid url, the page will change to this url. and if it's not a valid url, it will write error.
I have a <div id='url'></div> that the AJAX updates with error message (on 1st load, before user entered anything) and this message continues until it a valid url was entered. when a valid url was entered, the following will be written to this DIV:
<script type="text/javascript">
window.location.href="http://google.com"; // google.com is just an example
</script>
this doesn't seem to work. but if I put the page change code instead of the error message, it is working.
Why doesn't it work after a valid URL was entered?
I don't see any need for AJAX, just normal javascript. When you find that the entered text is a valid website and you want to load it, just use window.location = "http://google.com"; // google.com is just an example directly - no need to insert it into the document.
Why do you write JS to DIV instead of just calling window.location.href="http://google.com"; ?
For example
$.ajax({
url: 'answercheck.php',
success: function( data ) {
if (data=="correct"){
window.location.href="http://google.com";
}
else
{
//show error message
}
}
});
I want to check the value of a hidden field triggered by a "h ref onClick" javascript function. If it is"empty", I want to prompt the user to rate my page using a ratings form (thereby staying on the same page and ignoring the h ref target page. If the value is "rated", I want to simply allow the user progress to their intended page.
Here is some code I've developed so far but doesn't really work that well:
function ratings_prompt(){
var checkIfRated = document.getElementById("hidden_rating");
if (checkIfRated.value == "empty")
{
alert("The Field is set to empty - please rate the form!");
checkIfRated.value=="rated";
}
}
Edit: Sorry but I cannot seem to get all the code into the codeblock.
GF
can't really help out all that much w/out seeing more code and also you didn't really say what the problem is..."doesn't really work that well" is kind of vague...but basically you would have in your link onclick your function call, and you should pass a "this" reference to the function, and you should have return false; in your onclick as well. Then in your function, if the hidden field is not empty, do like location.href = that.href
link
<script type='text/javascript'>
function yourFunction(that) {
if (document.getElementById("hidden_rating").value != "empty") {
location.href = that.href;
} else {
// didn't rate
}
}
</script>