editing input fields together instead of separately - javascript

Current Scenario :
Right now I have a form in which you can edit and save each records of input fields. i.e. firstName, lastName, email etc..
I do not get any errors and everything is working fine.
Requirement :
Now what I want to save & edit firstName and lastName input fields together instead is to edit and save firstName and lastName input field separately.
Right now they are all different input id's.
Question :
How can I achieve this by calling the same class for firstName and lastName if I want to edit them at the same time with a button ?
Is this a way to do it ? Thanks...
Code :
$("#inputFirstName,#inputLastName,#inputEmailAddress,#inputPassword,#inputZipCode").on('keypress',function(e){
if(e.which == 13) {
var field = $(this).attr("id");
var data = {};
data['ajax']=true;
data[$('#'+field).attr('name')]=$('#'+field).val();
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][firstName]') {
$('#userfirstname').text($('#'+field).val());
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][lastName]') {
$('#userlastname').text($('#'+field).val());
}
});
$('#'+field+'-edit').show();
$('#'+field+'-save').hide()
$('#'+field).attr('disabled',true);
}
});

first of all. save on every keypress is bad and will exhaust your server.
I recommennd you use onChange or make a submit button
submit button is a better solution.
lets assume that we have this html:
<form id="updateForm">
<input type="text" id="firstN" name="firstName" data-val="Ris" value="Ris">
.
.
.
<input type="button" value="submit" id="goBtn">
</form>
first set a data-val equal to the value
then in your javascript
$("#goBtn").click(function(){
var data = {};
data["ajax"] = true;
$("#updateForm input").each(function(){
var $this = $(this);
var type = $this.attr('type');
if(type != "button" && $this.val() != $this.attr("data-val"))
data[$this.attr("name")] = $this.val();
});
if(data.length > 0){
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
} else {
$.each(data, function(index, value){
$('updateForm input[name="'+index+'"]').attr("data-val", value);
});
}
// then do things
});
}
});
first it checks every input for changes (data-val is holding the original value) and it adds it to data if there is any changes at all it calls the ajax and if it was successful it updates the data-vals of each changed value else it leave it for another submission

Related

jQuery ajax input field event, options list and setting a value

I am trying to create an AJAX function to autocomplete the input field.
The user starts typing in location/city name, and it should trigger an AJAX call for lookup, presenting suggestions of matching city names list to the input field. Then the user selects one value and that is set to that input field. The below code doesn't even trigger events, I do not see request activity on the network. How to accomplish this?
$(function() {
$('#locationName').keyup(function() { //tried keyup, input
alert('Ok'); // to test event
$.ajax({
type: 'POST',
url: '/locationsearch',
data: {
'search_text': $('#locationName').val()
},
success: searchSuccess,
dataType: 'text'
});
});
});
function searchSuccess(data) {
locationName.val = 'data';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="locationName" id="locationName">
Your example does not seem complete. It's not clear where locationName is defined. Consider the following snippet.
$(function() {
function searchLoc(txt) {
var result = "";
$.post("/locationsarch", {
"search_text": txt
}, function(data) {
result = data;
});
return result;
}
$('#locationName').keyup(function() {
var q = $(this).val();
if (q.length >= 3) {
$(this).val(searchLoc(q));
}
});
});
It's not clear what the resulting data will be, I am assuming text or HTML.

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

jquery required field validator issue

I have a form with multiple input fields and a select field. I have an attribute of required for multiple fields. I have created a validation code snippet which should check all required fields and display a message when field is empty.
However the problem is that it works only when first input field is empty. I would appriciate a hint.
Code for the function:
function lisa_a() {
//validator
var req = $(":input[required]").val();
var reqfield = $(":input[required]");
if (req == ""){
$(".error").remove();
var reqtxt = "<span class='error'>Nõutud</span>";
reqfield.each(function(){
$(this).after(reqtxt);
});
$("div#status").html("Please fill...");
//validator
}else{
var data = $("form#lisa_a_vorm").serialize();
$.ajax({
url : "/var_dump.php", //for testing
method: "POST",
data : data,
success:function(data) {
$("div#status").html(data);
}
});
$("form#lisa_a_vorm :input").each(function(){
$(this).val('');
});
$(".error").remove();
}
}
EDIT:
Searched some more and discovered .filter looping through fields. Adjusted my code:
function lisa_a() {
//validator
var emptyfields = $(":input[required]").filter(function(){
return $.trim($(this).val()).length === 0;
}).length > 0;
$(".error").remove();
if (emptyfields){
$(":input[required]").after("<span class='error'>Nõutud</span>");
$("div#status").html("Palun täida kõik nõutud väljad!");
}else{
var data = $("form#lisa_a_vorm").serialize();
$.ajax({
url : "/wp-content/themes/origin/TCDB/php/var_dump.php",
method: "POST",
data : data,
success:function(data) {
$("div#status").html(data);
}
});
$("form#lisa_a_vorm :input").each(function(){
$(this).val('');
});
$(".error").remove();
}
}
It's not perfect as i don't quite understand .filter basics. Am i correct if i say that the filter function returns the number of trimmed required input fields that have the value 0, which means that they are empty. If the number of those fields is greater than 0, then it returns true, else it returns false. EDIT: i think i just got the point. The solution came from this answer.

Email Validation in Javascript Before AJAX

So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.

issue in preventing user from entering empty string in ajax post

I have a jquery ajax post and when a user inputs some text and presses enter in a textbox this ajax will trigger and show the value of text box in a <pre> html element. http://jsfiddle.net/LQg7W/2133/ obviuosly this jsfiddle does not show anything because I haven't put the ajax post inside it. But when the user writes nothing and presses enter this ajax is triggered and returns something. But how can I catch the empty strings from user?
This is located in my view:
if(e.keyCode == 13) {
var currentLine = $('#terminal').text();
var inputData = $(e.currentTarget).val();
$('#terminal').text(currentLine + "\r\n" + inputData + "\r\n"); //show the current and previous value
$("#textInput").val(" $> ");
AjaxPost(inputData);
}
and this ajax post is in model:
AjaxPost : function(dataAttribute, view, cacheId) {
console.log(cacheId);
var that = this;
if(dataAttribute === ""){
view.showMessage( " " , true);
}
$.ajax({
type : "POST",
url : "/api/user" ,
datatype : "application/json",
contentType: " text/plain",
data : dataAttribute,
success : function(data) {
console.log(data);
},
error : function(error) {
},
My problem is that my input data has default value of "$>" so I cannot check this condition if (inputdata === "" ) because it is always full! Have any ideas?
if the input value defaults to "$>" then you only need to check that too, and return to avoid the ajax call:
if(dataAttribute === "" || dataAttribute === "$>") {
view.showMessage( " " , true);
return;
}
var m = inputdata.match(/\s*\$\>\s*/)
if (inputdata === m[0]){
console.log('empty')
}
else{
console.log('not empty')
}

Categories

Resources