Ignore placeholder values on ajax form submit - forms

I'm using the jQuery ajax form plugin in my WordPress plugin's settings page. Before I started using ajax, I had this script that compared text input values to placeholder values, and if they matched, set the text input value to null. But it no longer works now that I'm using ajax. With the jQuery ajax form plugin, I can pass arguments in a beforeSerialize function, or in a beforeSubmit function. I think it would need to be done in the beforeSerialize. Anyway, I'm not sure how to make this work. Here is the script that was working before I switched to ajax:
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('ssfa-placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
And here is my current script for the ajax form submit:
var svn = $("#ssfa-saving"),
bck = $("#ssfa-saving-backdrop"),
svd = $("#ssfa-settings-saved");
$("#ssfa-form").ajaxForm({
beforeSend: function() {
svn.fadeIn('slow');
bck.fadeIn('fast');
},
success: function(){
svn.fadeOut('slow');
svd.delay(1000).fadeIn('slow').delay( 2500 ).fadeOut('slow');
bck.delay( 4500 ).fadeOut('slow');
}
});
Any ideas on how I can get the ajax submit (either beforeSerialize or beforeSend ) to ignore placeholder values? This first script above was a really simple solution for regular post submit. I'm hoping I can find something just as simple for ajax.
UPDATE
I worked out a basic way of doing it but it involves calling each text field that has a placeholder, so it's not exactly elegant like the original script, but this is functional:
$("#ssfa-form").ajaxForm({
beforeSerialize: function() {
var permex = $('input#exclusions');
$('input[id^=bs]').each(function(){
var bs = $(this);
if (bs.val() === 'Display Name')
bs.removeAttr('value');
});
$('input[id^=custom_]').each(function(){
var cs = $(this);
if (cs.val() === 'classname1|Display Name 1, classname2|Display Name 2')
cs.removeAttr('value');
});
if (permex.val() === '.avi, My Embarrasing Photograph, .tif')
permex.removeAttr('value');
},
beforeSend: function() {
etc.
And since it's a placeholder text, the text doesn't actually disappear when the value attribute is removed, so no one is really the wiser. I'm not over the moon with this, but it works. If I had a much larger form, this wouldn't be workable.
Open to better ideas....

Well, I played around with it quite a bit more and found a way to get the original code to work with ajax submit. It's quite simple actually. I just had to specify the element within which to search for the placeholder attr. Here it is:
beforeSerialize: function() {
$("#ssfa-form").find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
},
etc.
To track the issue, see:
https://github.com/mathiasbynens/jquery-placeholder/issues/30
https://github.com/mathiasbynens/jquery-placeholder/issues/197

Related

Protractor element handling

I have a question regarding how protractor handles the locating of elements.
I am using page-objects just like I did in Webdriver.
The big difference with Webdriver is that locating the element only happens when a function is called on that element.
When using page-objects, it is advised to instantiate your objects before your tests. But then I was wondering, if you instantiate your object and the page changes, what happens to the state of the elements?
I shall demonstrate with an example
it('Change service', function() {
servicePage.clickChangeService();
serviceForm.selectService(1);
serviceForm.save();
expect(servicePage.getService()).toMatch('\bNo service\b');
});
When debugging servicePage.getService() returns undefined.
Is this because serviceForm is another page and the state of servicePage has been changed?
This is my pageobject:
var servicePage = function() {
this.changeServiceLink = element(by.id('serviceLink'));
this.service = element(by.id('service'));
this.clickChangeService = function() {
this.changeServiceLink.click();
};
this.getService = function() {
return this.service.getAttribute('value');
};
};
module.exports = servicePage;
Thank you in advance.
Regards
Essentially, element() is an 'elementFinder' which doesn't do any work unless you call some action like getAttribute().
So you can think of element(by.id('service')) as a placeholder.
When you want to actually find the element and do some action, then you combine it like element(by.id('service')).getAttribute('value'), but this in itself isn't the value that you are looking for, it's a promise to get the value. You can read all about how to deal with promises elsewhere.
The other thing that protractor does specifically is to patch in a waitForAngular() when it applies an action so that it will wait for any outstanding http calls and timeouts before actually going out to find the element and apply the action. So when you call .getAttribute() it really looks like
return browser.waitForAngular().then(function() {
return element(by.id('service')).getAttribute('value');
});
So, in your example, if your angular pages aren't set up correctly or depending on the controls you are using, you might be trying to get the value before the page has settled with the new value in the element.
To debug your example you should be doing something like
it('Change service', function() {
servicePage.getService().then(function(originalService) {
console.log('originalService: ' + originalService);
});
servicePage.clickChangeService();
serviceForm.selectService(1);
serviceForm.save();
servicePage.getService().then(function(newService) {
console.log('newService: ' + newService);
});
expect(servicePage.getService()).toMatch('\bNo service\b');
});
The other thing that I'm seeing is that your pageObject appears to be a constructor when you could just use an object instead:
// name this file servicePage.js, and use as 'var servicePage = require('./servicePage.js');'
module.exports = {
changeServiceLink: element(by.id('serviceLink')),
service: element(by.id('service')),
clickChangeService: function() {
this.changeServiceLink.click();
},
getService: function() {
return this.service.getAttribute('value');
}
};
Otherwise you would have to do something like module.exports = new servicePage(); or instantiate it in your test file.
When you navigate another page, the web elements will be clear, that you selected. So you have to select again. You can select all elements that is in a page of HTML. You can click that you see. So the protactor + Selenium can decide what is displayed.
You have a mistake in your code, try this:
expect(servicePage.getService()).toMatch('\bNo service\b');

How to fire place_changed event for Google places auto-complete on Enter key

The click seems to fire the event and set the cookies but pressing enter to submit doesn't set the cookies and instead the page redirects without the cookies.
function locationAuto() {
$('.search-location').focus(function () {
autocomplete = new google.maps.places.Autocomplete(this);
searchbox = this;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var thisplace = autocomplete.getPlace();
if (thisplace.geometry.location != null) {
$.cookie.raw = true;
$.cookie('location', searchbox.value, { expires: 1 });
$.cookie('geo', thisplace.geometry.location, { expires: 1 });
}
});
});
The .search-location is a class on multiple textboxes.
There is a submit button that takes the values from the cookies and redirects (server side)
Adapted from Jonathan Caulfield's answer:
$('.search-location').keypress(function(e) {
if (e.which == 13) {
google.maps.event.trigger(autocomplete, 'place_changed');
return false;
}
});
I've encountered this problem as well, and came up with a good solution. In my website I wanted to save the autocomplete.getPlace().formatted_address in a hidden input prior to submission. This worked as expected when clicking the form's submit button, but not when pressing the Enter key on the selection in the autocomplete's dropdown menu. My solution was as follows:
$(document).ready(function() {
// Empty the value on page load
$("#formattedAddress").val("");
// variable to indicate whether or not enter has been pressed on the input
var enterPressedInForm = false;
var input = document.getElementById("inputName");
var options = {
componentRestrictions: {country: 'uk'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
$("#formName").submit(function(e) {
// Only submit the form if information has been stored in our hidden input
return $("#formattedAddress").val().length > 0;
});
$("#inputName").bind("keypress", function(e) {
if(e.keyCode == 13) {
// Note that simply triggering the 'place_changed' event in here would not suffice, as this would just create an object with the name as typed in the input field, and no other information, as that has still not been retrieved at this point.
// We change this variable to indicate that enter has been pressed in our input field
enterPressedInForm = true;
}
});
// This event seems to fire twice when pressing enter on a search result. The first time getPlace() is undefined, and the next time it has the data. This is why the following logic has been added.
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// If getPlace() is not undefined (so if it exists), store the formatted_address (or whatever data is relevant to you) in the hidden input.
if(autocomplete.getPlace() !== undefined) {
$("#formattedAddress").val(autocomplete.getPlace().formatted_address);
}
// If enter has been pressed, submit the form.
if(enterPressedInForm) {
$("#formName").submit();
}
});
});
This solution seems to work well.
Both of the above responses are good answers for the general question of firing a question when the user presses "enter." However - I ran into a more specific problem when using Google Places Autocomplete, which might have been part of the OP's problem. For the place_changed event to do anything useful, the user needs to have selected one of the autocomplete options. If you just trigger 'place_changed', the if () block is skipped and the cookie isn't set.
There's a very good answer to the second part of the question here:
https://stackoverflow.com/a/11703018/1314762
NOTE: amirnissim's answer, not the chosen answer, is the one to use for reasons you'll run into if you have more than one autocomplete input on the same page.
Maybe not the most user friendly solution but you could use JQuery to disable the enter key press.
Something like this...
$('.search-location').keypress(function(e) {
if (e.which == 13) {
return false;
}
});

jquery disabled button not working with IE

In my code I disable the submit button with jquery and then do a check to enable it. It works fine but not in IE. Could some please help me out, Thanks
function checkPassword() {
$('input#password').mouseout(function(){
var password =$('#password').val();
//event.preventDefault();
//alert(password);
$.ajax({
type: "POST",
url: "ajax/pass.php",
cache: false,
datatype:"html",
data: "password="+ password,
success: function(msg){
if (msg) {
$('#feedbk').html(msg);
var name = $('#feedbk').text().length;
var valid = 'Valid Password.';
var n = valid.length
if (name == n) {
$('#submit').attr("disabled", false);
$('#feedbk').fadeOut(3000);
} else {
$('#submit').attr("disabled", true);
}
}
}
});
});
};
The solution is to use regular javascript
var el = document.getElementById(selectBoxCheckBoxOrButtonID);
el.removeAttribute('disabled');
I used straight JavaScript to sort out the problem
document.getElementById('selectBoxCheckBoxOrButtonID').removeAttribute('disabled');
Thanks #user843753 your solution work marvelously.
I am reiterating it here because I cannot comment at the moment and it looks so non- intuitive (What! not a jquery solution).
But why oh why is it not fixed in JQuery 1.6.2?
My original issues with IE include, re-enbled disable buttons, only be made visible on mouse-over.
In another case the re-enabled disabled buttons could not made visible with any user interaction.

jquery form plugin with hash change

currently im having problems with the jquery form plugin. Part of this because i need to change the hash value on form submit. Heres the basic of what im doing:
$(document).ready(function() {
$('#search').ajaxForm({
target: '#pageContent',
success: function() {
$('#pageContent'); //this is all i need to 'ajaxify' this form
var hash = 'query='+encodeURI(document.getElementById('query').value);
window.location.hash = hash;
}
});
});
Now what happens is i am able to change the hash value but my form no longer 'ajaxify's itself and instead i just get a blank page..
What am i doing wrong?
since no-one had a suitable answer i managed to hack my implementation of jquery.history.js to allow searching via ajax.. heres the code:
$(document).ready(function() {
// bind form using ajaxForm
$('#search1').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#pageContent',
// success identifies the function to invoke when the server response
success: function() {
$('#pageContent');
var hash = '#search.php?term='+($('#query').val()+'&submit=Submit').replace(/ /g, '+');
update(window.location.hash = hash);
}
});
});
i also replaced the spaces in the search to include + signs.. maybe this will help someone.
Try adding an actual hash, denoted by #:
$(document).ready(function() {
$('#search').ajaxForm({
target: '#pageContent',
success: function() {
var hash = '#query='+encodeURI($('#query').val());
window.location.hash = hash;
}
});
});

How to manipulate forms with Mootools

I'm trying to manipulate forms with Mootools. My purpose is to inject the response content of a form into a div element named result.
Here a code that works, but it replaces the content of the result div. This is not what I want : I want to ADD the form response content to the result div existing content. I just can't find on the web how to do this, and I've tried many things that are not working ... Please help
window.addEvent('domready', function() {
$('myform').addEvent('submit', function(e) {
e.stop();
var result = $('result').empty();
this.set('send',{
url: this.get('action'),
data: this,
onSuccess: function() {
result.set("html", this.response.text);
}
}).send();
});
});
If it's only text you want to add, just remove the empty method, and replace result.set() with result.appendText().
If you need to append an element tree, repeat the first step, and do:
onSuccess: function(){
Elements.from(this.response.text).inject(result);
}
Btw. It's all in the documentation - http://mootools.net/docs/core/Element/Element