How to call a jQuery function when textbox is edited - javascript

In my code there is one text box which is disabled. when user click on edit pencil icon textbox is enabled for edit something. and when user edit the textbox it must check whether edited value is already exit or not. for that i have call checkOwnerId method. but there is no any call goes to that function.
This is my jQuery code
var parcel = $('#parcel_no').val();
$('#pin-edit').click(function () {
$('#owner_id_txt').removeAttr("disabled");
$("#pin-edit").hide();
$("#save-pin").show();
oldOwnerId = $('#owner_id_txt').val();
});
$('#save-pin').click(function () {
if ($("#owner_id_txt").val() == "") {
displayErrorMessage('Please enter owner Id');
$("#owner_id_txt").focus();
$('#owner_id_txt').val(oldOwnerId);
return;
}
$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true)
$("#save-pin").hide();
var data = { 'owner_id': $("#owner_id_txt").val(), 'parcel_no': parcel };
BlockUI();
var urlstring = "#Url.Content("~")Parcel/UpdateOwnerId";
$.post(urlstring, data, function (result) {
UnblockUI();
if (result.success == true) {
displaySuccessMessage('Owner Id updated successfully!');
}
else {
displayErrorMessage('There was an error while updating Owner Id!');
}
});
$('#owner_id_txt').change(function () {
//alert("Check Exist or Not");
var data = { 'owner_id': $("#owner_id_txt").val() };
var urlString = "#Url.Content("~")Parcel/CheckOwnerId";
urlString = sanitize_url_path(urlString);
$.post(urlString, data,
function (result) {
if (result) {
displayErrorMessage("Owner Id already exists");
$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true);
$("#save-pin").hide();
}
});
})
});

Your '$('#owner_id_txt').change(function () {' is called inside ' $('#save-pin').click(function () {' so its not getting called once you type the text box. Put the function outside of it, then it will check the value. Refer the below jsfiddle sample
code: JS
$(document).ready(function() {
$('#pin-edit').click(function () {
$('#owner_id_txt').removeAttr("disabled");
$("#pin-edit").hide();
$("#save-pin").show();
oldOwnerId = $('#owner_id_txt').val();
});
$('#save-pin').click(function () {
if ($("#owner_id_txt").val() == "") {
$("#owner_id_txt").focus();
$('#owner_id_txt').val(oldOwnerId);
return;
}
$("#pin-edit").show();
$('#owner_id_txt').attr("disabled", true)
$("#save-pin").hide();
});
$('#owner_id_txt').change(function () {//alert("Check Exist or Not");
console.log($(this).val());
});
$('#owner_id_txt').attr("disabled", true);
});
code: HTML
<input type="text" id="owner_id_txt" >
<div id="pin-edit">edit</div>
<div id="save-pin">save</div>
https://jsfiddle.net/pitchiahn/fr6gdeyd/

this can be archived using jquery change :
$( "'textboxid" ).change(function() {
// Check input( $( this ).val() ) for validity here using ajax call
});

Related

How to use defined variable out of function in javascript

I have a one signal javascript code and an ajax form, that give me a Player Id of the user in one signal,
so I want to use this code in my ajax login form and add the Player id to login form data, but i can't use a defined variable in one signal function, out of that and receive not defined message
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
var userid = userId;
});
});
var options = {
url: "{{CONFIG ajax_url}}/auth/login?hash_id=" + getHashID(),
beforeSubmit: function () {
$('#output-errors').empty();
$("#btn-submit").text("{{LANG Please wait..}}");
},
success: function (data) {
$("#btn-submit").text("{{LANG Login}}");
if (data.status == 200) {
if ($('#page').attr('data-page') != 'home' && $('#page').attr('data-page') != 'forgot' && $('#page').attr('data-page') != 'reset') {
$('#main-header').html(data.header);
$('#login_box').modal('hide');
if (Amplitude.getActiveSongMetadata().price >= 0) {
location.href = window.location.href;
} else {
ajaxRedirect();
}
} else {
location.href = window.location.href;
}
} else if (data.status == 400) {
var errros = data.errors.join("<br>");
$('#output-errors').html(errros);
}
},
// here i add the one signal id
data: {
OSid: userid
}
};
$('#login-form').ajaxForm(options);
There are a couple ways you can solve this, here's one approach:
OneSignal.push(function() {
OneSignal.getUserId(doAjax);
});
function doAjax(userId) {
var options = {
url: "{{CONFIG ajax_url}}/auth/login?hash_id=" + getHashID(),
beforeSubmit: function () {
$('#output-errors').empty()
...
}
$('#login-form').ajaxForm(options);
}
The function OneSignal.getUserId() takes a function as an argument, so my solution declares a function doAjax that will take the userId as an argument, and then we pass that function to the getUserId function.
Simplest way I suggest is:
Var userid;
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
userid = userId;
});
});

How can I call my validate function before sending my ajax when a button is clicked?

Hello everyone I have a table that's dynamically generated from database.
This is the table.
I have all the code that works fine,but I only need proper timing of execution
1) Check if all mandatory fields are populated on button click, if not don't send ajax.
2) When all mandatory fields are populated on button click then call ajax and send proper values to c# and later to database.
First I need to check if all mandatory fields are filled in(check Mandatory column(yes or no values):
$(function () {
$("#myButton").on("click", function () {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
})
});
If not don't call ajax and send values. If all fields are populated then call ajax to send values to c#.
This is the ajax code that takes values from filed and table and send's it to c# WebMethod and later to database.
$(function () {
$('#myButton').on('click', function () {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
});
});
I need code to execute first mandatory fields and when they are all filled in then call ajax part of the code!
Can anyone please help !
If you need more explanation just ask !
Thanks in advance !
Update Liam helped allot me but ajax is not working on button click.
function validate() {
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
if (!isNaN($(el).text())) {
return;
}
// Get the value
var val = $(el).text().toUpperCase();
var isRequired = (val === "TRUE") ? true :
(val === "FALSE") ? false : undefined;
// Mark the textbox with required attribute
if (isRequired) {
// Find the form element
var target = $(el).parents("tr").find("input,select");
if (target.val()) {
return;
}
// Mark it with required attribute
target.prop("required", true);
// Just some styling
target.css("border", "1px solid red");
}
});
}
function sendAjax() {
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
$('#MainContent_gvKarakteristike tbody').find('tr:gt(0)').each(function (i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(3)').children()))
});
});
console.log(myCollection);
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
('Selected text:' + $('option:selected', control).text());
return $('option:selected', control).text();
}
}
var lvl = $('#MainContent_txtProductConstruction').val()
if (lvl.length > 0) {
$.ajax({
type: "POST",
url: "NewProductConstruction.aspx/GetCollection",
data: JSON.stringify({ 'omyCollection': myCollection, 'lvl': lvl, 'ddl': ddl }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (parseInt(response.d) > 0)
alert("Saved successfully.");
else
alert("This object already exists in the database!");
console.log(response);
location.reload(true);
},
error: function (response) {
alert("Not Saved!");
console.log(response);
location.reload(true);
}
});
}
else {
alert("Please fill in the Product Construction field!")
}
}
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
})
});
If you want to execute these in order why don't you just add one click handler that calls each function:
function validate(){
// Loop all span elements with target class
$(".IDMandatory").each(function (i, el) {
// Skip spans which text is actually a number
....etc.
}
function sendAjax(){
var ddl = $('#MainContent_ddlBusinessCenter').val()
var myCollection = [];
..etc.
}
$(function () {
$('#myButton').on('click', function () {
validate();
sendAjax();
}
});
Seems it would make sense if your validate function actually returns true or false if your form was valid too. then you could:
$(function () {
$('#myButton').on('click', function () {
if (validate()){
sendAjax();
}
}
});
I'm not really sure why your doing this:
// Mark it with required attribute
target.prop("required", true);
when you validate? If you just add this into your HTML it will handle required. adding it here seems a bit strange. I'm guessing your not actually submitting the form? It'd make more sense to add the validation message yourself rather than use this attribute.
Your codes not working because your not returning anything from your validate function. It's not 100% clear to me what is valid and what isn't so I can't alter this. But you need to add return true; for valid cases and return false;for invalid cases for the if statement if (validate()){ to work.

Validate the input I'm focus on, no matter what is the status of the others?

I'm having this issue I need to solve... What I want to do is to validate exactly the input user is filling in the moment, no matter if the first one or any other input are empty, and the other is not send the ajax post request if every single input has been validated.
This is the code i have so far:
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
return false;
}
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
Try this one.
function sendInfo() {
//variables
var name = $("input#name").val();
var surname = $("input#surname").val();
var error = false;
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
error = true;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
error = true;
}
if (error) return false;
//Manage server side
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
You can do this by adding a bool variable isValid. Your code should be like this
function sendInfo() {
//variables
var isValid = true;
var name = $("input#name").val();
var surname = $("input#surname").val();
//inputs validation
if (name == "") {
$("input#name").focus();
$("input#name").parent().find('span').addClass('err').text('you have to fill the name');
isValid = false;
}
if (surname == "") {
$("input#surname").focus();
$("input#surname").parent().find('span').addClass('err').text("you have to fill the surname");
isValid = false;
}
//Manage server side
if(isValid){
$.ajax({
type: 'POST',
url: '/path',
data: {name, surname},
success: function (result) {
//all ok, do something
},
error: function (err) {
//something wrong, do other stuff
}
});
}
}
Try to validate the inputs onfocus() AND before the post.
var checkInput = function(input) {
if (input.val() == '') {
input.parent().find('span').addClass('err').text('you have to fill the name');
return false;
}
return true;
}
function sendInfo() {
var validForm = false;
$('input').each(function(){
validForm = checkInput($(this));
});
if (validForm) {
alert('ok - do the post');
} else {
alert('fill the fields');
}
}
$( document ).ready(function() {
$('input').on('focus',function() {
checkInput($(this));
});
});
Add a certain class to every field you want validated. Then bind an event on the elements with that class that will validate the fields upon change. If it's validated correctly store this info on the element.
For example you'd have your fields like this
<input type='text' id='some-text-1' class='validated-field'>
<input type='text' id='some-text-2' class='validated-field'>
<input type='text' id='some-text-3' class='validated-field'>
Then a script which binds the events
$('.validated-field').on('input', function(){
validate($(this));
});
Note: This will "fire" basically after each keypress, not only after you finish editing.
Note2: Depending on how you create the elements, if you want to call this after document.ready then you'll have to bind this to an element which is indeed ready at the time.
Your validate function should perform the necessary validations and then mark the element with in a certain way, for example
function validate($element){
var value = $element.val();
// var isValid = your validation here
$element.data("valid", isValid);
}
This will produce elements for example like these
<input type='text' id='some-text-1' class='validated-field' data-valid=true>
<input type='text' id='some-text-2' class='validated-field' data-valid=false>
<input type='text' id='some-text-3' class='validated-field'>
The first one validated correctly, the second one is incorrect and the third isn't validated yet, because user hasn't filled it out yet.
With this you can check if every one of these elements is validated
validateElements(className){
var elements = $('.' + className);
for(var i=0; i<elements.length; i++){
if(!$(elements[i]).data("valid") === true){
return false; //at least one isn't validated OK
}
}
return true; //all good
}
I hope I understood your question correctly. If you have any other questions, feel free to comment.

jQuery $.post not executing, how to fix

I am working on a Plugin for WordPress and am having issues with the js code below executing the $.post.
The js is called, form validation takes place, the form inputs are serialized into post data correctly, the $.post just doesn't execute.
The form is being posted from the Admin, currently I can't get the .submit action to work so am using .click to execute the js function. This may be related to the issue, I am not sure... The form will load without submitting if I use the .submit action, versus using the .click action... never had this issue before and it is pretty frustrating to say the least.
Here is the code:
jQuery(document).ready(function($) {
$("#edit_member_submit").click( function() {
// define
var numbers = /^[0-9]+$/;
var referrer_id = $("#referrer_id").val();
// Validate fields START
if( !referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
// Define a data object to send to our PHP
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
var data = $("#edit_member_form").serializeObject(); //the dynamic form elements.
//alert(JSON.stringify(data));
data.action = "edit_member_info"; //the action to call
data._ajax_nonce = custajaxobj.nonce; // This is the name of the nonce setup in the localize_script
// Define the URL for the AJAX to call
var url = custajaxobj.ajaxurl;
//alert( JSON.stringify( data ) );
//alert( JSON.stringify( url ) );
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
return false;
});
});
Seems like the last section is having issues:
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
$.post( "ajax/test.html", function( data ) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(data);
});

jQuery UI AutoComplete: Only allow selected valued from suggested list

I am implementing jQuery UI Autocomplete and am wondering if there is any way to only allow a selection from the suggested results that are returned as opposed to allowing any value to be input into the text box.
I am using this for a tagging system much like the one used on this site, so I only want to allow users to select tags from a pre-populated list returned to the autocomplete plugin.
You could also use this:
change: function(event,ui){
$(this).val((ui.item ? ui.item.id : ""));
}
The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.
Don't know if that matters to you or not.
I got the same problem with selected not being defined. Got a work-around for it and added the toLowerCase function, just to be safe.
$('#' + specificInput).autocomplete({
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
$(ul).addClass('for_' + specificInput); //usefull for multiple autocomplete fields
return $('<li data-id = "' + item.id + '">' + item.value + '</li>').appendTo(ul);
};
},
change:
function( event, ui ){
var selfInput = $(this); //stores the input field
if ( !ui.item ) {
var writtenItem = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val().toLowerCase()) + "$", "i"), valid = false;
$('ul.for_' + specificInput).children("li").each(function() {
if($(this).text().toLowerCase().match(writtenItem)) {
this.selected = valid = true;
selfInput.val($(this).text()); // shows the item's name from the autocomplete
selfInput.next('span').text('(Existing)');
selfInput.data('id', $(this).data('id'));
return false;
}
});
if (!valid) {
selfInput.next('span').text('(New)');
selfInput.data('id', -1);
}
}
}
http://jsfiddle.net/pxfunc/j3AN7/
var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";
$('#ac').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function() {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
This is how I did it with a list of settlements:
$("#settlement").autocomplete({
source:settlements,
change: function( event, ui ) {
val = $(this).val();
exists = $.inArray(val,settlements);
if (exists<0) {
$(this).val("");
return false;
}
}
});
i just modify to code in my case & it's working
selectFirst: true,
change: function (event, ui) {
if (ui.item == null){
//here is null if entered value is not match in suggestion list
$(this).val((ui.item ? ui.item.id : ""));
}
}
you can try
Ajax submission and handling
This will be of use to some of you out there:
$('#INPUT_ID').autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'data':'" + $('INPUT_ID').val() + "'}",
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (data) {
console.log('No match.')
}
});
},
change: function (event, ui) {
var opt = $(this).val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: autocompleteURL,
data: "{'empName':'" + name + "'}",
dataType: 'json',
success: function (data) {
if (data.d.length == 0) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
} else if (data.d[0] != opt) {
$('#INPUT_ID').val('');
alert('Option must be selected from the list.');
}
},
error: function (data) {
$(this).val('');
console.log('Error retrieving options.');
}
});
}
});
I'm on drupal 7.38 and
to only allow input from select-box in autocomplete
you only need to delete the user-input at the point,
where js does not need it any more - which is the case,
as soon as the search-results arrive in the suggestion-popup
right there you can savely set:
**this.input.value = ''**
see below in the extract from autocomplete.js ...
So I copied the whole Drupal.jsAC.prototype.found object
into my custom module and added it to the desired form
with
$form['#attached']['js'][] = array(
'type' => 'file',
'data' => 'sites/all/modules/<modulname>_autocomplete.js',
);
And here's the extract from drupal's original misc/autocomplete.js
modified by that single line...
Drupal.jsAC.prototype.found = function (matches) {
// If no value in the textfield, do not show the popup.
if (!this.input.value.length) {
return false;
}
// === just added one single line below ===
this.input.value = '';
// Prepare matches.
=cut. . . . . .
If you would like to restrict the user to picking a recommendation from the autocomplete list, try defining the close function like this. The close function is called when the results drop down closes, if the user selected from the list, then event.currentTarget is defined, if not, then the results drop down closed without the user selecting an option. If they do not select an option, then I reset the input to blank.
//
// Extend Autocomplete
//
$.widget( "ui.autocomplete", $.ui.autocomplete, {
options: {
close: function( event, ui ) {
if (typeof event.currentTarget == 'undefined') {
$(this).val("");
}
}
}
});
You can actually use the response event in combination to the change event to store the suggested items like so:
response: function (event, ui) {
var list = ui.content.map(o => o.value.toLowerCase());
},
change: function (event, ui) {
if (!ui.item && list.indexOf($(this).val().toLowerCase()) === -1 ) { $(this).val('');
}

Categories

Resources