jQuery/JavaScript operator equal SQL LIKE %Example% - javascript

Is there any way to search a specific part on my input with Javascript/jQuery?
Tried to do with 2 different ways, but no results for that
<script type="text/javascript">
$("#button").click(function () {
$("#DivToToggle").toggle();
var campo = document.getElementById('FieldToSearch');
if (campo.contains("Test")) {
document.getElementById('FieldToWrite').value = "123";
}
else {
document.getElementById('FieldToWrite').value = "456";
}
});
and
<script type="text/javascript">
$("#button").click(function () {
$("#DivToToggle").toggle();
var field = document.getElementById('FieldToSearch');
if (field.match(/Test.*/)) {
document.getElementById('FieldToWrite').value = "123";
}
else {
document.getElementById('FieldToWrite').value = "456";
}
});
#EDIT
Thanks to #TalhaAbrar, found the correct way to do it.
<script type="text/javascript">
$("#button").click(function () {
var field = document.getElementById('FieldToSearch').value;
if (field.indexOf("Test")) {
$("#DivToToggle").toggle();
document.getElementById('FieldToWrite').value = "123";
}
else {
$("#DivToToggle").toggle();
document.getElementById('FieldToWrite').value = "456";
}
});

Try to fetch the value of search field like document.getElementById('FieldToSearch').value and then use function indexOf in your if statement, that should work for you.
example code:
var field = document.getElementById('FieldToSearch').value;
if (field.indexOf("value_to_check")) {
// true if exists
} else {
// false if doesn't
}

I think you need to check the value of the field, e.g.
var campo = document.getElementById('FieldToSearch').value;
...
And then use includes(), e.g.
if (campo.includes("Test")) {
...

Related

How to successfully call the submit when all validations are true

I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});

Specifying validation for specific form in some page

I have a javascript function that validate a popup form before submit it. Unfortunately it's created to handle one popup form per page only.
In my case, i have two different popup forms, so i want to specify what to do and also for which one.
$.fn.goValidate = function() {
var $form = this,
$inputs = $form.find('input:text');
var validators = {
email: {
regex: /^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/
}
};
var validate = function(klass, value) {
var isValid = true,
error = '';
if (!value && /required/.test(klass)) {
error = 'This field is required';
isValid = false;
} else {
klass = klass.split(/\s/);
$.each(klass, function(i, k){
if (validators[k]) {
if (value && !validators[k].regex.test(value)) {
isValid = false;
error = validators[k].error;
}
}
});
}
return {
isValid: isValid,
error: error
}
};
var showError = function($input) {
var klass = $input.attr('class'),
value = $input.val(),
test = validate(klass, value);
$input.removeClass('invalid');
$('#form-error').addClass('hide');
if (!test.isValid) {
$input.addClass('invalid');
if(typeof $input.data("shown") == "undefined" || $input.data("shown") == false){
$input.popover('show');
}
}
else {
$input.popover('hide');
}
};
$inputs.keyup(function() {
showError($(this));
});
$inputs.on('shown.bs.popover', function () {
$(this).data("shown",true);
});
$inputs.on('hidden.bs.popover', function () {
$(this).data("shown",false);
});
$form.submit(function(e) {
$inputs.each(function() {
if ($(this).is('.required') || $(this).hasClass('invalid')) {
showError($(this));
}
});
if ($form.find('input.invalid').length) {
e.preventDefault();
$('#form-error').toggleClass('hide');
}
});
return this;
};
$('form').goValidate();
I'm pretty sure that it's all about this line:
$('form').goValidate();
Let's say that the first form id is form_1 and the second form_2.
What should i put in this line?
Something like this i guess:
$('form['form_1]').goValidate();
Hope it was clear, thanks !
You can use form id to target your form.
ex. if your first form has id form1 then you can write.
$('#form1').goValidate();
and same as second one.

How to deliver value from popup.js to background.js

I hope to deliver the value from popup.js to background.js so that I can open the website as what i expect. I use the localStorage variable as my json's value. But when found that the value I have delieverd to background.js in the argument input of the function openTab(input) is always the string "localStorage.input" itself. How can I solve it?
popup.js
window.onload=function()
{
localStorage.input=document.getElementById("search").value;
document.getElementById("submit").onclick=function()
{
chrome.extension.sendMessage({command:"start",input:localStorage.input});
}
}
background.js
chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse)
{
switch(request.command)
{
case "start":
openTab(request.input);
break;
}
return true;
}
);
var openTab=function(input)
{
chrome.windows.create
(
{
url:"http://www.baidu.com/s?wd="+input,
}
);
};
try this out
var lStore = localStorage.input || '';
window.onload=function()
{
var search = document.getElementById("search");
search.value = lStore
document.getElementById("submit").onclick=function()
{
// var input = search.value; //try this as well
var input = lStore;
chrome.extension.sendMessage({command:"start",input:input});
}
}

How to retrieve input value before submit

I have to retrieve three input values before submitting so I can use ajax to fill in the form depending on the information inside these boxes.
I first check that the three boxes have text using this script:
<script>
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
var direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
});
});
</script>
What I need is that when these three fields have a value to retrieve that value so I can pass it through a URL in PHP before submitting (ajax maybe?)
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
$value would be the variable (direccion) which is in the script.
If you need more information please let me know.
You need to set the variable as global to access it outside.due to declaring it in change, the scope of variable remains within change function only. so declare the variable outside change event.like this:
<script>
jQuery(document).ready(function () {
var flag = false;
var direccion="";//declare variable
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');//define variable on every on change
}
});
});
</script>
On your form you can add an onsubmit attribute which will define an action to take when the form is submitted.
eg :
<form method='GET' action='' onsubmit='doAjax();return false;'>
<input type='text' id='inp_name' value='hello'/>
</form>
<script>
function doAjax(){
alert("this form won't be posted!");
return false;
}
</script>
you need to make a ajax call to the url which is constructed
jQuery(document).ready(function () {
var flag = false;
jQuery(".validation").change(function () {
flag = true;
var direccio="";
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#calle").val();
var municipio = jQuery("#municipio").val();
var provincia = jQuery("#provincia").val();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
}
$.ajax({
url: "target.php",
data:{'value':direccion},
success: function(response) {
//process the data received from server script
});
});
});
PHP CODE(target.php):
$value=$_POST['value'];
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$value .'&sensor=false';
//further processing of data at server end and finally echo the data to client
You need to do it with your last desired input tag. Suppose you want data up to the 3rd input tag then you need to Call your custom function in the 3rd input tag with onkeyup="myFunction()"
In myFunction() you can check if the fields are populated or not and can also do the ajax to transfer the data to server

setTimeout not working

My setTimeout seems to be working for logging in, but not for submitting data. :
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup({async:false});
function Validate_submit(form) {
var Address1_input = form.address1.value;
var Address2_input = form.address2.value;
var City_input = form.city.value;
var State_input = form.state.value;
$.post('../scripts/submit_check.php', {address1php: Address1_input, address2php: Address2_input, cityphp: City_input, statephp: State_input},
function(output) {
$('#submit_msg').html(output).fadeIn(500);
if (output == 'Submitting...') {
var timeoutID = window.setTimeout(function () {location.reload();}, 1000);
} else {
$('#submit_msg').html('something went wrong').fadeIn(500);
}
}
);
}
The same code works in my log-in popup window:
<script type="text/javascript" src="../scripts/jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup({async:false});
function Validate_login(form) {
var Email_input = form.email.value;
var Password_input = form.password.value;
var Rememberme_input = form.remember_me.checked;
$.post('../scripts/login_check.php', { emailphp: Email_input, passwordphp: Password_input, rememberphp: Rememberme_input},
function(output) {
$('#login_msg').html(output).fadeIn(500);
if (output == 'Logging in...') {
var timeoutID = window.setTimeout(function () {location.reload();}, 1000);
}
}
);
}
When I click the submit button in the submit form, it shows 'Submitting...' for a split second, but not for the whole second (like in the login-popup). Can someone help me?
You'll probably need to cancel the actual <form>'s submission. return false from the onsubmit handler after you call Validate_submit.

Categories

Resources