check Multiple Word in Input Field textbox using javascript - javascript

I am having textbox Input field and in that i have to check Multiple words. I am able to check single Word but not able to check multiple words. A list of word is stored in xml and from that i have to check. Need Help.
Here MyName is Input Field Id and lblMyName is Label Id.
if ($("#MyName").val() != '') {
$.ajax({
type: "GET",
url: "Xml/Badwords.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('Badwords').each(function () {
var flag = true;
$(this).children().each(function () {
var tagName = this.tagName;
var val = $(this).text();
if (val.toLowerCase() == $("#MyName").val().toLowerCase()) {
$("#lblMyName").css("display", "block");
$("#lblMyName").text("Please refrain from using profanity.");
$(".postermyname").text('My Name);
flag = false;
return false;
}

You'll have to split the input value on word boundaries and then compare that against the "bad" words.
Note that profanity filters is in generally a really bad idea, and will usually cause more issues than they solve
if ( $("#MyName").val().trim() != '' ) {
$.ajax({
type: "GET",
url: "Xml/Badwords.xml",
dataType: "xml",
success: function(xml) {
var input = $("#MyName").val().toLowerCase().split(/\b/),
flag = true;
$(xml).find('Badwords').each(function() {
$(this).children().each(function() {
var val = $(this).text().toLowerCase;
if (input.indexOf(val) !== -1) {
$("#lblMyName").css("display", "block")
.text("Please refrain from using profanity.");
flag = false;
}
});
});
});
});
}

Related

search in JSON with AJAX

I have to search inside a json file with a value from my input, everything is fine capturing the value and the event, but when I iterate something unexpected happens for me.
How can I select an object based on this search?.
the problem is that when doing .each it goes through all the records, even those not found.
$( document ).on('turbolinks:load', common_events)
function common_events(){
$('.rut-input').on('change', function(event){
$rut = $(this).val();
var searchField = $rut;
var expression = new RegExp(searchField, "i");
event.preventDefault();
$.ajax({
type: "GET",
url: '/companies/',
dataType: 'JSON',
success: function(companies){
$.each(companies, function(i, company) {
if (company.rut.search(expression) > -1){
console.log(company.id);
$('.name-input').empty();
$('.name-input').val(company.name);
$('.name-input').addClass('disabled-input');
$('.form-group').removeClass('hide');
console.log(company.address);
if (company.address == null ){
$('.address-input').removeClass('disabled-input');
};
}
else {
console.log('no encuentra');
console.log(company);
$('.form-group').removeClass('hide');
$('.form-control').removeClass('disabled-input');
};
});
},
error: function(companies){
console.log('A ocurrido un error')
},
});
});
}
when executing the event, both the if and else are executed at the same time.
Seems like you don't really want to iterate the companies array with each. You want to find a matching company, and then do something with that record.
success: function(companies){
const company = companies.find(c => c.rut.search(expression) > -1);
if (company) {
console.log(company.id);
$('.name-input').empty();
$('.name-input').val(company.name);
$('.name-input').addClass('disabled-input');
$('.form-group').removeClass('hide');
console.log(company.address);
if (company.address == null ){
$('.address-input').removeClass('disabled-input');
}
} else {
console.log('no encuentra');
console.log(company);
$('.form-group').removeClass('hide');
$('.form-control').removeClass('disabled-input');
}
},

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 form and some inputs at same time

Here I have a form and I need to validate form. I have select2 input fields and this fields I cant validate with parsley plugin so I write my code...
Problem is how to at same time check if validate = true and select2 inputs ===null...
I write:
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
if ( $(this).parsley('validate') ) {
if ($("#parcele").select2("data")== null || $("#vrsta_rada").select2("data")== null) {
$('#parerror').show();
console.log('nema dalje');
} else {
var zemljiste = $("#parcele").select2("data").naziv;
var id_parcele = $("#parcele").select2("data").id;
var vrsta_rada = $("#vrsta_rada").select2("data").text;
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: { naziv:$("#naziv").val(),parcele:zemljiste,vrsta_rada:vrsta_rada,opis:$("#opis").val(),pocetak:$("#pocetak").val(),zavrsetak:$("#zavrsetak").val(),status:$("#status").val(),id_parcele:id_parcele,}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#myModal').modal('hide');
drawVisualization();
console.log('USPEH');
console.log(data);
},
error: function (data) {
console.log(data);
console.log('GRESKA NEKA');
}
});
}
}
});
});
but as you can see my code first check form validation after that select2 inputs so how I can at same time check form and select2 inputs fields?
By using && operator you can check both condition at the same time
if ( ($(this).parsley('validate')) && ($("#parcele").select2("data") === null)) {
}

Passing checkbox values as JSON in Jquery

I have an input form which has three text fields and a checkbox input section where the user can select more than one value. I also have an ajax request which sends a POST request to an api. I have written a function to iterate over the form inputs and parse them to JSON, however, it has come to my attention that this wont work for checkbox values. Here is my function:
<script>
console.log(document);
var form = document.getElementById("myform");
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var info = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
info[input.name] = input.value;
}
addPerson(info);
}
}
function addPerson(info) {
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
I've been trying to get the checkbox values into JSON using
$.each($('input[id="data[i].id"]:checked'), function() {
var value = $(this).val();
qualifications.push(value);
});
but I cant figure out how to add these values to the JSON that is being posted to the server, can anyone help?
Have tried .serialize() and I THINK it is working-
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('myform').submit(function() {
$('#result').text(JSON.stringify($('myform').serializeObject()));
return false;
});
});
function addPerson(result){
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(result),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
If anyone has thoughts/ comments as to how effective the above is, or if there is a better way of doing it, I would like to hear them?
Try this:
var input = form[i];
if (input.name) {
if(input.tagName.toLowerCase() === 'input' &&
(input.type.toLowerCase() === 'checkbox' || input.type.toLowerCase() === 'radio') &&
input.checked)
info[input.name] = input.value;
else
info[input.name] = input.value;
}
addPerson(info);
EDIT:
I suggest using jQuery form.serialize() method as #Drixson OseƱa mentioned.

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