computing result based on two different ajax request - php

i have a simple form with two fields whose data are being validated against a database on keyup with jquery. I am also having a button which is currently enabled or disabled based on the number of characters entered in these two fields. THe two jquery functions return an "accept" or "cancel" image for the two fields. I want to enable the button only if both the functions return the accept image or i can even make them return true along with it, which will not be a problem. I just wanna know how to compute a local result based on the returned value from two different ajax requests.
These are two functions that validate teh field against a database.
$("#agentName").keyup(function(){
var agentName = $("#agentName").val();
if(agentName.length > 3)
{
$("#agt-name-result").html(ajax_load).load(loadUrl, "val="+agentName+"&fld=agent_name");
}
else{
$("#agt-name-result").html("<img src=\"images/cancel.png\" />");
}
});
$("#agentSource").keyup(function(){
var agentSource = $("#agentSource").val();
if(agentSource.length > 9)
{
$("#agt-src-result").html(ajax_load).load(loadUrl, "val="+agentSource+"&fld=agent_url");
}
else{
$("#agt-src-result").html("<img src=\"images/cancel.png\" />");
}
});
This is the function that validates the button
$("#agentName,#agentSource").keyup(function(){
var validate;
var agentName = $("#agentName").val();
var agentSource = $("#agentSource").val();
if((agentName === "") || (agentSource === "") || (agentName.length < 3) || (agentSource.length < 10))
{
validate = false;
}
else { validate = true; }
if(validate === true) {
$("#addAgntBtn").removeAttr("disabled");
$("#addAgntBtn").removeClass("dialog-btn-disabled").addClass("dialog-btn");
}
else {
$("#addAgntBtn").attr("disabled", "disabled");
$("#addAgntBtn").removeClass("dialog-btn").addClass("dialog-btn-disabled");
}
});
Any ideas?

I would use a setInterval to poll a $.data() value in which the two ajax calls put their results. You have to pay attention to concurrent accesses, but it should work

Related

button will disable until all the input is not filluped is not working properly

Here above is my form input filled. I create a script if input filled is fillup then button will enabled until button is disabled.
But on Card Number input box it is not effected with other input. without card number button shows enabled but i want it must be disabled if all filled is not fillup..
Here is my jQuery script:
jQuery(document).on('change keyup', '.required', function(e){
let Disabled = true;
jQuery(".required").each(function() {
let values = this.value;
if ((values)&&(values.trim() !=''))
{
Disabled = false;
}else{
Disabled = true;
return false;
}
});
if(Disabled){
jQuery('#submit_button').prop("disabled", true);
}else{
jQuery('#submit_button').prop("disabled", false);
}
});
These card number input field is come from stripe payment api.
<div id="card-element" class="inputText gdcard">
<!-- a Stripe Element will be inserted here. -->
</div>
I can't use stripe card element input field with my .required class. Please sort me out this bug?
The recommended way to manage this is to listen to events on Stripe Elements. In particular, you could listen to the change event on a card element (doc) and inspect the value of event.complete to see if the form is filled out. If it is (and your other fields are too) you can enable the Pay button.
function checkIfCardComplete(elementsEvent) {
if (elementsEvent.complete) {
$("#pay-now").removeAttr("disabled")
} else {
$("#pay-now").attr("disabled", "disabled")
}
}
card.on('change', function(event) {
checkIfCardComplete(event);
});
You can see an example implementation of this here (which only looks at the card input being complete, it ignore the other fields): https://jsfiddle.net/nolanhawkins/dhjybsnr/3/
edit:
If, for example, you refactored your code to make the check on your custom fields a function:
function areAllMyFieldsValid() {
let Disabled = true;
jQuery(".required").each(function() {
let values = this.value;
if ((values)&&(values.trim() !='')) {
Disabled = false;
} else {
Disabled = true;
return false;
}
});
return !Disabled; // really you should invert your logic, not the result
}
then you could change the check in the event handler to just look at this additionally:
if (elementsEvent.complete && areAllMyFieldsValid()) { ...}
you could try this:
$("#card-element").prop(disabled, true);
jQuery(document).on('change keyup', '.required', function(e) {
//uncomment if this item has required class
//($("#card-element").removeClass(".required");
var isItOk = jQuery(".required").toArray().every((e) => $(e).val().trim() != '');
$("#card-element").prop(disabled, isItOk);
isItOk = isItOk && $("#card-element").val().trim() != '';
jQuery('#submit_button').prop("disabled", isItOk);
});
jQuery(".required").toArray().every((e) => $(e).val().trim() != ''); means all items which have the class .required are not empty

Building a form dynamically

I have a drop down menu, that a user selects a criteria from, based on the criteria a form gets built.
What I am trying to do now is make sure they cannot build the same for twice, so for example, if the users selects appearance from a dropdown, I do not want them to be able to select appearance from the dropdown, while that form is built.
Does that make sense? Currently here is my code,
$('img.toggleadd').live({
click: function() {
var rowCount = $("#advanced_search > table > tbody > tr").length;
f(rowCount < 3) {
$.ajax({
url: site_url + 'ajax/row/empty',
success: function(data) {
console.log($(this));
$('#advanced_search table').append(data);
}
});
}
}
});
and the PHP
public function row($name) {
if ($this->input->is_ajax_request()) {
return $this->load->view('search/rows/'.$name);
}
}
$name relates to the name of a view which contains the corresponding form elements for the selected value.
As Jared mentioned, the solution could be something as simple as a boolean value indicating whether or not a request is in progress...
Take this code for example -
var request_in_progress = false;
$("#selector").on('change',function(){
if (!request_in_progress){
request_in_progress = true;
$.ajax('/path_to_ajax_module.php',{'data':data},function(response){
// handle the AJAX response
request_in_progress = false; // AJAX request complete.
},'json');
}
});

Validate form fields in sequences

I have a multi-step order form built in this manner:
Step 1: Choose category via radio button
The "Next" button is just an image that has an onclick function hides the current div with the radio buttons, and displays a new div with the next step in the process.
Step 2: Textarea, checkbox -> Dynamic price
Contains a textarea, a dynamic price, and four checkboxes. The price changes depending on the number of characters in the textarea and the choices in the checkboxes. JQuery script is used in order to do that. Again, the "Next" button is just an image that upon activating the onclick function hides the current div, and displays the div containing the next step in the form.
Step 3: Personal Data
And here is my problem. Here where the user inserts name, email and so on. The "Next" button is again just an image that upon activating the onclick function hides the current div and displays the div containing the next step. How do i make the form fields in this step required in order to allow the user to advance to the next step. The code i have for hiding and showing the divs is as follows:
<script type="text/javascript">
function toggleDiv(id, flagit) {
if (flagit == "1") {
if (document.layers) document.layers[''+id+''].visibility = "show"
else if (document.all) document.all[''+id+''].style.visibility = "visible"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
}
else`if (flagit == "0") {
if (document.layers) document.layers[''+id+''].visibility = "hide"
else if (document.all) document.all[''+id+''].style.visibility = "hidden"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"`
}
}
//-->
</script>
That is a horrible (and wrong) piece of old code.
here is an update that actually still handles Netscape4 (the layers part)
You need to show me the rest of the script where you toggle. You need to add validation to
THAT part, not the toggle.
For example, using
<form onsubmit="return validate(this)">
and
<input type="image" src="next.png" />
you can do this (plain JavaScript, the show and hide in jQuery is shown elsewhere on the page):
var currentStep=1;
function toggleDiv(id,flagit) {
if (document.getElementById) document.getElementById(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.all) document.all(id).style.visibility = (flagit)?"visible":"hidden";
else if (document.layers) document.layers[id].visibility = (flagit)?"show":"hide";
}
function validate(theForm) {
if (currentStep == 1) {
if (theForm.category.value....) {
alert("Error in category");
return false;
}
currentStep++;
toggleDiv("part1",0);
toggleDiv("part2",1);
return false; // do not submit
}
if (currentStep == 2) {
if (theForm.price.value....) {
alert("Error in price");
return false
}
currentStep++;
toggleDiv("part2",0);
toggleDiv("part3",1);
return false; // do not submit
}
if (currentStep == 3) {
if (theForm.name.value....) {
alert("Error in name");
return false
}
return true; // submit
}
}
Well, since you have tagged your question with jQuery, why not actualy use it and let jquery handle all platform specific issues.
function toggleDiv(id,flagit) {
if( flagit ) {
$("#"+id).show();
} else {
$("#"+id).hide();
}
}
Let me know if this works.

javascript combo box

I have used this function to call the following page depending on the chosen option.
The First IF will direct me to the Monthly report while the second IF will direct me to the Daily report
<script type="text/javascript">
function ActionDeterminator()
{
var monthly = document.myform.duration.options[0].value;
var daily = document.myform.duration.options[1].value;
if (monthly == 0){
document.myform.action = 'month.php';
}
if (daily == 1) {
document.myform.action = 'day.php';
}
}
</script>
I have also another function which will execute a job depending on the option. The first IF will convert my report to excel doc while the second IF will direct me to view page to print.
<script type="text/javascript">
function ActionDeterminator()
{
if(document.myform.group[0].checked == true) {
document.myform.action = 'excel.php';
}
if(document.myform.group[1].checked == true) {
document.myform.action = 'view.php';
}
return true;
}
</script>
The Problem:
the problem is that it does not direct me to the correct page (whether monthly or daily)... it only directs me to view page or exporting to excel. Could anyone teach me the correct way to do this function?
Also, I want to ask the correct javascript for combo box.
What you'll want to do is get all the form elements into an array, loop, and evaluate for checked equals true
For example:
var elems = document.getElementsByName('group');
for (var i=0; i<elems.length; i++) {
if (elems.item(i).checked == true) {
break;
}
}
switch (i) {
case 0:
//action = 'excel.php';
break
//case etc...
}

Dynmaic checkboxs validation

I want to validate Checkbox in javascript, checkboxes is generating dynamically by PHP and name of checkboxes are like "checkbox1" , "checkbox2" ,"checkbox3" i.e. incrementing i++ and these numbers are coming from database, it might be first time only 2 rows fetched and next time 112 rows.
How i can make sure in javascript that atleast one checkbox must be selected.
// When you use jQuery... somehow like this
$('form').submit(function() {
if ($("input:checked").length == 0) {
alert('Please check at least one checkbox!');
return false;
}
});
If you do not want to use any js framework, then just give the same name attribute to the checkboxes
Assuming your checkboxes are named test
var chkBoxes = document.getElementsByName("test");
var chked=0;
for(var i=0;i<chkBoxes.length;i++)
{
if(chkBoxes[i].checked)
chked++;
}
if(chked===0)
alert("Please select a value");
Added as per the sample code specified in the comment
function isChecked()
{
var i=1;
var chkd=0;
var elem = "";
var chkForMoreChkBoxes=true;
do{
elem=document.getElementById("check_"+i);
try{
if(elem.checked)
{
chkd++;
}
i++;
}
catch(err)
{
chkForMoreChkBoxes=false;
}
}while(chkForMoreChkBoxes)
if(chkd===0)
{
alert("Please select a value");
return false;
}
}

Categories