How can I make this username suggestion work in javascript? - javascript

I have an application that requires both first name and last name. I need to have the username field automatically fill up as the user types in their first and last names to suggest a username. Right now, it works to a degree. This is the function that executes on a keyup for the name fields.
suggestUsername: function() {
var username = this.$('#user_login_field').val();
var first = this.$('#user_first_name_field').val();
var last = this.$('#user_last_name_field').val();
if(first == '' && last == ''){
this.$('#user_login_field').val('');
} else {
this.$('#user_login_field').val(first+'.'+last);
}
},
This works unless the user adds something to the username manually and then goes back to one of the name fields and enters something else. In the case that that happens, whatever the user added manually disappears. Not sure how to go about fixing it

Add an jQuery focus handler to the #user_login_field that unbinds the keypress events from the first and last name fields. (http://api.jquery.com/focus/)
$('#user_login_field').focus(function (e) {
// Unbind the keyup events
$('#user_first_name_field').unbind('keypress');
$('#user_last_name_field').unbind('keypress');
});

you can add a
$('#user_last_name_field').blur(function(){
//do username suggestion
})

Related

How to detect Event Listeners and their actions on input fields

I have purchased a booking plugin (wordpress) to add to a site.
https://wpamelia.com/
I cannot show the site I am working on, but here a demo from plugin developers
https://sports.wpamelia.com/#book
Once you have chosen your date and time, you end up on a form with input fields.
I was able to pre-fill this form with data that I could pass via the URL.
My URL would look something like this: https://sports.wpamelia.com/?first=Jim&last=Tester&email=something%40something.com&phone=0222222222#book
But here is the problem:
Even though I managed to use jQuery to pre-fill the input fields of the form, as soon as I click confirm the fields' content is erased and the error "Please enter... " appears for each of them.
So again:
STEP 1: I open the booking page with an URL containing data in the query string
STEP 2: Using jQuery, I manage to pre-fill the form that appears after having chosen date and time (first name, last name ...)
STEP 3: I click "Confirm"
RESULT: all the fields are empty and for each one the error message "Please enter first name" (etc..) appears
I've messaged the plugin developers. Only answer was that there is indeed no functionality to take the data from the Query String into the form fields yet.
MY QUESTIONS:
1) How could I find out, with chrome inspector or other tools, why exactly the content I pre-fill into the form is ignored?
---> I've tried things like getEventListeners in the chrome inpector's console, but I don't really see how to get information out of that
2) Would anyone know what the issue is and/or how I could bypass it?
---> there is a lot of javascript from the plugin developers behind that and something is expecting manual entering of the data into the fields...
---> but even when trying to fake manual entering with things like $(this).trigger("change").val(function(i,val){return 'aaaa';}); this didn't solve the problem....
(If anyone is interested, I can post later my javascript/jQuery functionality to get the form fields pre-filled with data from Query String... interesting code as you have to wait until the fields appear for jQuery to recognise them..)
Thanks so much for any help!
cheers
Admino
#Admino - this may not be the best solution and I know this is an old question so you may not need it now but after not finding a better one it at least worked for me.
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function valueOutput(element) {
element.dispatchEvent(new Event('input'));
}
jQuery(function() {
jQuery(document).on('change', 'input', function(e) {
valueOutput(e.target);
});
// you may want to perform more validations here if needed
// just checking here if email is present (but not checking for valid email address)
var fname = getUrlVars()["first"];
var lname = getUrlVars()["last"];
var email = getUrlVars()["email"];
var phone = getUrlVars()["phone"];
var custom1 = getUrlVars()["custom1"]; // you know this field label is Order Number
if (email.length > 0) {
// run an interval until the elements are present on the page (form displayed)
var checkInputs = setInterval(function() {
if (jQuery('.amelia-app-booking label[for="customer.email"]').length > 0) {
var em = jQuery('.amelia-app-booking label[for="customer.email"]').closest('.el-form-item').find('.el-input__inner');
// this checks to see if an Amelia customer is already present
if (em.val() == '') {
em.prop('value', email).val(email).trigger('change');
jQuery('.amelia-app-booking label[for="customer.firstName"]').closest('.el-form-item').find('.el-input__inner').prop('value', fname).val(fname).trigger('change');
jQuery('.amelia-app-booking label[for="customer.lastName"]').closest('.el-form-item').find('.el-input__inner').prop('value', lame).val(lame).trigger('change');
jQuery('.amelia-app-booking label[for="customer.phone"]').closest('.el-form-item').find('.el-input-group__prepend').siblings('.el-input__inner').prop('value', phone).val(phone).trigger('change');
}
// for custom fields I check the label text to find the correct input
if (custom1 != '') {
jQuery('.amelia-app-booking label:contains("Order Number")').closest('.el-form-item').find('.el-input__inner').prop('value', custom1).val(custom1).trigger('change');
}
// form info is updated so clear the interval
clearInterval(checkInputs);
}
}, 500);
}
});
You may want to try a different method than url params to sync this info so it's not so public in the url string. This code may not need both the prop and val jquery setters but I just left them for you to try. Hope it helps (and to others I'm open to a better solution)!

is there a way to stop a form from processing based on true or false using java script

/*--------------------SUBMIT FORM -------------------*/
//Validate Form Fields
function FormValidation()
{
// validation fails if the input is blank
var verdba =document.getElementById('verdba').value;
if(verdba.value == "") {
alert("Error: VERDBA FIRST!");
verdba.focus();
return false;
}
// validation was successful
return true;
processForm();
}
function processForm() {
// window.alert("processForm Reached"); // (Stub)
// Collect Values from the Form
// First section and verification
var callback = document.getElementById('callback').value;
var verdba = document.getElementById('verdba').value;
var comments = document.getElementById('comments').value;
// Concatenate the Page Content
var pageBody = " CB#:"+callback+" "+verdba+comments;
pageBody += "";
window.clipboardData.setData('Text',pageBody);
//Hides table on submit
$("#forms").hide();
$(".myClass").hide();
//Copies pagebody to clipboard
var content = clipboardData.getData("Text");
document.forms["test"].elements["clipboard"].value = content;
}
// Hides table with clear button
function cleartable(){
$("#forms").hide();
$(".myClass").hide();
}
I have included a very bare bones example in a fiddle.
I noticed on the fiddle that it doesn't fully work but in the HTA I have it does work. What it does is collects input fields and option fields by id, concatenates them into what I call a note. It also copies the clipboard data to a text area.
What I want is to be able to click submit and have it collect the form data and check to see if two fields were used or not.
So in the phone number field I need to be sure a phone number is entered ( does not really matter to me if it checks that its a certain amount of digits or that it is digits at all as long as it isnt blank) and next check to see if the option box was selected, either yes or no, again not blank.
Upon discovering one or both were left blank or not selected I would like the process to stop and notify the user that it needs to be done. I would like it to give them a chance to fix it and then resubmit.
The problem I am having is that I can't get both to happen.
I have it where it collects the data and checks for the data, but the problem I ran into is that it doesnt care if its blank and you click ok, it still submits the request anyway and then clears the forms.
I just cant seem to figure out how to get both things working in one swing.
I hope someone can shed some light on this as it has been bugging me for days with endless online research and failed attempts.
https://jsfiddle.net/joshrt24/roqjoyhr/1/
At the end of your function FormValidation(),
// validation was successful
return true;
processForm();
}
You have put return true, before your function has chance to call the processForm, return will immediately exit your function.
Fix, just call processForm() first.
// validation was successful
processForm();
return true;
}

Search in mysql by Javascript

Good morning , I'm trying to do a check if the cpf entered already exists in the database , I'm using laravel , someone could help me in this function please ?
In my controller I seek and I list all cpfs in bank :
$cpfduplicado = UsuarioEsic::lists('doc', 'id')->all();
foreach ($cpfduplicado as $cpf)
if ($cpf == $request->cpf)
$cpf = 'verdadeiro';
// return redirect('/Esic/CadastroFisica');
return redirect('/Esic/Sucesso');
I'm not sure how to make a function in javascript to get this data and set a custom browser validity , I did something like this:
$(function cpfdupli(input) {
$('.btnCadastroo').on('click', function (json){
if (json.cpf === 'verdadeiro'){
document.getElementById('cpff');
input.setCustomValidity('Cpf já existe.');
} else {
input.setCustomValidity('');
}
});
});
I am beginner in the field and do not really know how to do this work, I just wanted the cpf existed already setasse one CustomValidity in the browser and not let him continue with the registration , if anyone can help me or give me other ways of how solve this I would be very grateful!
PS: Any questions about the code will be available to provide.
ok i will attempt to try and do what your looking for:
Say the html input is something like:
<input type="text" value="" id="cpff" />
Then we have some js to get the details within the above input box, the below does this on each lette typed into the input so its constantly checking as the user types then giving a visual reposnse as the user types so they now if its taken or not as typing:
$('input#cpff').on('keyup', function(evt){
//-- get for value on keyup
var inputValue = this.value;
//-- call to the controller to check
$.ajax({
url : '/check/cpff/',
type: 'POST',
data {cpffValue : inputValue},
success : function(res){
console.log(res);
if(res === 'succcess'){
//-- output a tick icon to let the user know all is ok so far
} else {
//-- output an red x to sai no its been used
}
},
error : function(msg, x){
console.log(msg);
}
})
});
So for each letter typed in the input box the code sends the value to the route /check/cpff and then this returns a boolean / string back to see if its ok or not, hopefully your still with me?
Route:
Route::post('/check/cpff', ['uses' => 'ControllerName#checkCPFF']);
Controller
Class ControllerName extends Controller {
public function checkCPFF(Request $request){
//-- get the ajax data variable -- cpffValue
$formValue = $request->get('cpffValue');
//-- lets chec to see if we have an entry with those values
$doesItExsist = ModelName::where('field_name',$formValue);
//-- if we have a result from the DB then return not allowed
return ($doesItExsist) ? 'not-allowed' : 'allowed'
}
}
SO the above controller takes the data value that the form submits, then checks the required db table and does a search for that value, if it cannot then the user has a valid entry if there is a value found then the user must change their entry etc
its a bit crude and i have nothing to test this with etc so might / will need better working / writing to work as such, you can always change the js to do the same on submitting the form instead etc,
here is a link to test out the input section. to veiw the result open the console up so you can see the values being typed. Example of keyup
i hope it gives your a sort of starting base for help...

How to effectively add additional custom JQuery function to Submit Button on Forms with SilverStripe

I am using SilverStripe 3.0 with the silverstripe-userforms submodule.
This is really difficult to explain so please be patient.
I want to add a custom function (check textarea word count) to a Form, however I am unsure of how best to attach the function as I dont want to hack the core validation js files.
$('button[type="submit"]').entwine({
onclick: function () {
var $this = $('textarea.max-words');
var wordcount = getWords($this);
if (wordcount > maxWords) {
if ($this.next().is("span")) {
$('#maxwords-error').html(function () {
return spanText(wordcount, maxWords);
});
}
else {
$this.after(function () {
return "<span id='maxwords-error' class='required message'>" + spanText(wordcount, maxWords) + "</span>"
});
return false;
}
}
}
})
Silverstripe uses the entwine library so I have tried to do the same.
My problem is this
When run, the user is first prompted to complete the required word count as per the function above.
Once this condition is met, other additional validation be run as per the module (e.g. need to add a valid email address to the email field) form fields.
The user can complete the word count as per custom function, but if another part of the validation fails (e.g. the email field does not contain a valid email) the user can add an email, but then change the word count and submit successfully. Once the function is successful it never seems to run again.
How do I get my custom function to run each time the submit button is pushed, irrelevant of if the word count was correct or incorrect previously.
I think you should also cancel the click event so that it doesn't get propagated. Something like this (simplified):
$('button[type="submit"]').entwine({
onclick: function (evt) {
if(wordCountValidationFailed){
evt.preventDefault();
evt.stopPropagation();
evt.stopImmediatePropagation();
return false;
}
}
});
This ensures that execution of the event pipeline will stop, as soon as your word-count check fails. This should prevent the submission of the form if all form fields – except the word-count – are valid.

Disable Inputs on Dropdown Change

So I'm working on a webform right now and I need to disable all forms of input once one has a specific value. Is there an easy way to handle as soon as that dropdown gets to that value?
Currently I'm doing this:
setInterval('check()', 5000);
function check() {
// Disable all fields if the answer was no.
if ($("#has_contract").val() == 0) {
disable();
}
function disable() {
$("#inputs *").prop('disabled', true);
alert("There is no contract, please get a contract.");
}
has_contract is my element, and #inputs contains all of the inputs I would like to disable if #has_contract's value is 0.**
But this isn't ideal.
Is there a better way to do this rather than constantly checking every X amount of seconds?
Instead of checking for the value every 5 seconds, you can check the value on change.
// collect elements
var $hasContract = $("#has_contract");
var $inputs = $("#inputs input");
// on change, check the input
$hasContract.on('change', checkForm);
// Checks the hasContract input for a value
// of 0. If it does, disable the form.
function checkForm() {
if($hasContract.val() == 0) {
$inputs.attr('disabled', true);
}
}
Also, when you use setTimeout, or setInterval you don't have to use a string. Javascript supports passing functions as variables. See below.
// Do NOT do this
setInterval('check()', 5000);
// Do this instead
setInterval(check, 5000);
// or this
setInterval(function() {
//preform the check...
}, 5000);
I'm not completely certain that I understand your requirements, but would this work for you?
The below assumes that #has_contract is a <select> element:
$("#has_contract").change(function() {
if ($("#has_contract").val() == 0) disable();
});
First off, you should cache the elements as a variable and then run the function against that variable.
var myInputs
$(document).ready(function(){
myInputs = $("#inputs input"); // or '#inputs *' if you're excited about the asterix
});
Second thing, if I'm reading your setup correctly, you're going to pop an alert box every 5 seconds until the user has selected 'yes' to the contract. That will get QUITE annoying and they probably won't want to open a contract with you after that.
Without actually seeing your page, I'd imagine a better solution would be to check for the contract=yes when the click a submit button of some sort on the page.
$('#mySubmitButton').click(function(){
if ($("#has_contract").val() == 0) {
disable();
}
});
But maybe go one step further, what you really want to do is give them access to the form once they agree to the contract. So you should have the form disabled by default (coded into the html that everything is disabled), and attach a function to the 'yes' button that enables the form. Additionally, you can attach a function to the 'no' button that re-disables it, if they had previously clicked 'yes'.
$('#myYesBtn').click(function(){
myInputs.prop('disabled', false);
});
$('#myNoBtn').click(function(){
myInputs.prop('disabled', true);
});

Categories

Resources