Wait for button click event before continue loop Javascript - javascript

I have a code loop that adds options to a popup modal, with buttons alongside each option.
In a search loop, sometimes when the search returns multiple items, we must show the modal, and the user selects which part.
I want to pause the loop and wait for the user to choose an item, before continuing.
MY LOOP
$.each(rows, function (index, item) {
SearchItems(item.split('\t')[0], item.split('\t')[1]);
});
SEARCH ITEM FUNCTION
function SearchItems(searchedPart, quantity) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "OrderFormServices.asmx/GetItemInfoAdmin",
data: "{'itemname':'" + searchedPart + "','quantity':'" + (quantity || 1) + "', 'guid':'" + custGuid + "' }",
dataType: "json",
success: function (result) {
result = result.d;
if (result.length > 1) {
var htmlString = "";
$.each(result, function(index, item) {
item.PartNumber = (item.PartNumber != "") ? item.PartNumber : item.ItemName;
htmlString += "<tr><td>"
+ "<input type=\"hidden\" name=\"ItemID\" value=\"" + item.ItemID + "\">"
+ "<input type=\"hidden\" name=\"ItemCode\" value=\"" + item.ItemCode + "\">"
+ "<input type=\"hidden\" name=\"Price\" value=\"" + item.Price + "\">"
+ "<input type=\"hidden\" name=\"Quantity\" value=\"" + item.Quantity + "\">"
+ "<input type=\"hidden\" name=\"CustomerReference\" value=\"" + searchedPart + "\">"
+ "<input type=\"hidden\" name=\"PackQuantity\" value=\"" + item.PackQuantity + "\">"
+ "<input type=\"hidden\" name=\"FreeStock\" value=\"" + item.FreeStock + "\">"
+ item.PartNumber + "</td><td>"
+ item.ManufacturerName + "</td><td>"
+ item.ItemName + "</td><td>"
+ item.ItemDescription + "</td><td><input type='button' name=\"selectPopup\" onclick=\"ChoosePopup($(this).closest('tr'));\" class='btn btn-primary btn-xs' value='Select'></td></tr>";
});
$("#tbodyPopupContent").html(htmlString);
$("#PopUpNormalProduct").modal();
modalfix();
$("#divPopupWindow").parent("").addClass("quicksearchpopup");
//////////////////////////////////////////////////////////////////////////
//////////////// WAIT FOR BUTTON CLICK AND PERFORM CODE///////////////////
//////////////////////////////////////////////////////////////////////////
$("#partNumber").prop("disabled", false);
} else if (result.length < 1) {
$("#partNumber").prop("disabled", false);
$('#partNumber').focus();
}
else {
///////
}
}
});
}
The popup item buttons fire a ChoosePopup() function.
function ChoosePopup(row) {
var $hidden_fields = row.find("input:hidden");
var $tds = row.find("td");
var newItem = {
ItemID: parseFloat($hidden_fields.eq(0).val()),
ItemCode: $hidden_fields.eq(1).val(),
ItemDescription: $tds.eq(3).text(),
ItemName: $tds.eq(2).text(),
Price: parseFloat($hidden_fields.eq(2).val()),
Quantity: parseFloat($hidden_fields.eq(3).val()),
CustomerReference: $hidden_fields.eq(4).val(),
PackQuantity: parseFloat($hidden_fields.eq(5).val()),
FreeStock: parseFloat($hidden_fields.eq(6).val())
};
AddNewRow(newItem, true);
$("#PopUpNormalProduct").modal("hide");
}
How can I wait for this ChoosePopup() function to complete, before continuing the loop?

I think you should re-think the way you are approaching the problem. You should fire your ChoosePopup function with a callback to do the rest of the work based on the user input.
You might consider passing the rows array into the SearchItems function, so that you can setup your callback to iterate through the remaining items in rows.
Here's an example that doesn't require duplicated code.
const items = [1, 2, 3, 4, 5]
//main function which writes buttons from an array
function makeButtons(array) {
//copy the array so we can keep track of which items are left to process after click event
var unProcItems = array.slice()
$.each(array, function(index, item) {
var exit = false
//remove the item from the processed array
unProcItems.splice(unProcItems.indexOf(item), 1)
//make our button
var button = document.createElement('button')
button.innerHTML = `Button ${item}`
//if something then hook up a click event with callback
if (item == 3) {
button.onclick = function(event) {
//call our makeButtons function in the callback passing in the unprocessed items array
makeButtons(unProcItems)
//remove the click event so it can't be fired again
event.target.onclick = null
}
exit = true
}
document.getElementById('content').append(button)
//exit the loop if our flag was set
if (exit)
return false;
})
}
makeButtons(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
</div>

Define global variables and based on what the pop up asks for, move the rest of your code to ChoosePopup() Function.

Related

ajax - Why onclick doesn't work with checkboxes

I am currently creating tables and checkboxes using ajax communication.
After it was created, it was confirmed that the checkbox function was working normally,
Even if I include checked while creating it, the onclick function doesn't fire.
success:function(data){
for (var key in data) {
feature = data[key]
head = feature[0].split(" ")
tail = feature[1].split(" ")
type = feature[2]
name = feature[3]
$('#pharmacophore_table').append("<tr>" +
"<td>" + name + "</td>" +
"<td> <label><input type='checkbox' name='ligand_feature' onclick='show_ligand_feature(this, " + '"' + feature + '"' + ");' ></label>" +
"</tr>");
$("input[name='ligand_feature']").attr( "checked", true);
}
},
error:function(data){
alert(data.status)
}
How can I solve this?
I solved it.
Just add click event
complete: function(){
var chck = document.getElementsByName('ligand_feature')
for (var l=0; l<chck.length; l++){
chck[l].click();
}

Add custom object as option inside dropdownlist

I'm having some kind of a bad time where i need to append some json objects as selectlistitems inside a dropdownlist that is different from where i display these json objects.
I managed to retrieve all data, but i dont know how to translate all the information from one kind of element to another. Currently i set up something like this:
All objects that come from my JsonResult method in controller comes like this:
Jsonresult
and the current format for my dropdownlist is as follows:
Dropdownlist selection from controller
For right now I have come to the current state:
i created an array that stores all my objects and convert them to tags, but as i went debugging my array looks like this:
Array from ajax as option tags
My Ajax Request is working as follows:
function GetContratosFiltro() {
$("#id_contrato_aplicativo").empty();
$("#ckSelecionarTdsContratosFiltro").removeAttr("disabled");
var array_sistema = $('#id_sistema').val();
var array_build = $('#id_build_verus').val();
$.ajax({
type: "POST",
url: '#Url.Action("GetContratosFiltros")',
dataType: "json",
//data: "{ 'id_sistema': '" + array_sistema + "'," + "'id_build_verus': '" + array_build + "'}",
data: JSON.stringify({ id_sistema: array_sistema || null, id_build_verus: array_build || null }),
contentType: "application/json; charset=utf-8",
success: function (contratos) {
console.log(JSON.stringify(contratos));
var formoption = [];
content = contratos;
$.each(contratos, function (index, element) {
console.log(element);
var xx = $('<div class="checkbox">' +
'<input value="' + element.id_contrato + '" type="checkbox" name="' + element.contrato + '" class="form-check-input" id="' + index + '" checked>' +
'<label class="form-check-label" for="' + index + '">' + element.contrato + '</label>' +
'</div >');
$('#id_contrato_aplicativo').append(xx);
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " < option value = '" + element.id_contrato + "' id='" + element.id_contrato + "' > " + element.contrato + "</option >";
}
});
array = formoption;
$("#ckSelecionarTdsContratosFiltro").prop('checked', true);
console.log('formoption: ' + formoption);
console.log('array: ' + array);
console.log(content);
},
error: function (ex) {
//alert('Failed to retrieve states.' + ex);
}
});
}
My output on the filter modal is, for example:
Modal filter
On this code: id_contrato_aplicativo is a div where i store all the results from jsonresult query and displays them as checkboxes divs with input and labels, by this bootstrap documentation Checkboxes. My HTML consists into a modal with the filter options with two fields that send information to controller and the main dropdown just gets all information from regular query in controller, but i'm using a custom class called select2 which create the layout for my application and generate the multiselect dropdownlist as a element with each new showing as a block inside dropdown selection, like the image below:
Dropdown result
This code is where i generate all tags for each item from ajax call and below is the function that i am testing right now.
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " < option value = '" + element.id_contrato + "' id='" + element.id_contrato + "' > " + element.contrato + "</option >";
}
$('#btnTransf').click(function () {
console.log('clicou no botão!')
for (var i = 0; i < array.length; i++) {
array[i].appendTo('#id_contrato select');
$('#id_contrato').select();
//appends to select if parent div has id dropdown
//return !$("#id_contrato_aplicativo :checked").remove().appendTo('#id_contrato');
}
//return !$("#id_contrato_aplicativo :checked").remove().appendTo('#id_contrato');
});
UPDATE:
i have managed to locate the correct element and turn out that i only need to pass all elements already formated array variable with all elements as tags inside id_contrato element.
Removed useless info
I've managed to get it to work by making an event bind on a button that gets each element of my array of already formatted objects and with its ids as values from tags.
Array Structure example ( from ajax call):
array = []; //external variable
//put this susccess inside your call from ajax, considering a JsonResult as your controller method
success: function (contratos) {
console.log(JSON.stringify(contratos));
var formoption = [];
content = contratos;
$.each(contratos, function (index, element) {
console.log(element);
var xx = $('<div class="checkbox">' +
'<input value="' + element.id_contrato + '" type="checkbox" name="' + element.contrato + '" class="form-check-input" id="' + index + '" checked>' +
'<label class="form-check-label" for="' + index + '">' + element.contrato + '</label>' +
'</div >');
$('#id_contrato_aplicativo').append(xx);
for (var i = 0; i < contratos.length; i++) {
formoption[index] = " <option value='" + element.id_contrato + "'selected> " + element.contrato + "</option>";
}
});
array = formoption;
$("#ckSelecionarTdsContratosFiltro").prop('checked', true);
console.log('formoption: ' + formoption);
console.log('array: ' + array);
console.log(content);
}
Code:
$('#btnTransf').click(function () {
console.log('test to check if click successful!')
$.each(array, function (index, element) {
console.log(element);
$('#id_contrato').append(element);
$('#id_contrato').select();
});
});

How to restrict the selection of one Radio Button in C#?

This is my code to select one item at a time.
But both the options are getting selected. How can I solve this issue?
function initializehrm__documentidRadiobuttonlist(documentid) {
debugger
ajaxCall("/Client/SysType/GetSysTypeByTypeGroupCodeAndSyslevel", { "typeGroupCode": sysTypeGroupCodeEmployeeImmigrationDocument }, "POST", "callback_initializehrm__documentidRadiobuttonlist", documentid);
}
function callback_initializehrm__documentidRadiobuttonlist(data, documentid) {debugger
data = data.data;
var hrm__documentidRadiobuttonlisthtml = "";
$.each(data, function (index, item) {
item = removeVirtualObjectPropertiesFromJsonObject(item);
hrm__documentidRadiobuttonlisthtml += "<div><input type='radio' id='documentid" + index + "' value=" + item.id + " /><span>" + item.title + "</span></div>"
});
$("#rdohrm__documentid").html(hrm__documentidRadiobuttonlisthtml);
}
Multiple radio buttons must share the same name (the value of the name attribute), so that it is treated as a group, and only one selection is allowed.
Modify your < input > tag something like below:
"<div><input type='radio' id='documentid" + index + "' value=" + item.id + " name='documents' /><span>" + item.title + "</span></div>"

Shopify: If cart has one item and price is below 10, set quantity of item to 0. Can't quite get it

Currently have a modal cart pop-up in my store. When a user adds an item to their cart, they are presented with the option to add a "Special Bundle" upsell which is a discounted item below $10. Unfortunately, some people are removing the original item, and checking out only the discounted upsell. My goal is that if an item is removed from the cart, a check is made to determine if there is only a single item in the cart, and if the value of that single item is under $10, to then set its quantity to 0, which will remove it from the cart.
==============================================================================*/
function ajaxSubmitCart() {
$cart = $("#cart");
$.ajax({
url: '/cart.js',
dataType: 'json',
type: 'post',
data: $cart.serialize(),
success: function (data) {
refreshCart(data);
//updateCartIconNumber(data);
}
});
}
function refreshCart(cart) {
$cartBtn = $(".icon-cart");
if ($cartBtn) {
var $cartCount = $cartBtn.find('.cart_count');
var value = $cartCount.text() || '0';
var cart_items_html = "";
var newCart = $("#cart ul").empty();
var $cart = $("#cart ul");
var cartNumber = 0;
var product_ids = [];
$cart.find('li:not(:first)').remove();
if (cart.item_count == 0) {
// This removes the upsell item OPT-IN / Call To Action if the cart has no cart items. The problem is removing the upsell item after a customer has added it to the cart, and they then remove the full priced item.
$("#hero-offer").fadeOut(0,function() { $("#hero-offer").remove(); });
$cart.append('<li class="mm-label empty_cart"><img class="empty-cart-image" src="https://cdn.shopify.com/s/files/1/1442/0084/t/7/assets/Cart-Empty-TF2.png"><div class="cart-empty-text"></div></li>');
} else {
// Believe I need another if statement here that checks qty to determine if there is only one item in cart, and then checks if its price is less than $10, and if yes, sets its item qty to 0, which effectively removes the upsell item that is on its own
$.each(cart.items, function(index, item) {
cart_items_html += '<li class="cart_item">' +
'<a href="' + item.url +'">';
if (item.image) {
cart_items_html += '<div class="cart_image">' +
'<img src="' + item.image.replace(/(\.[^.]*)$/, "_medium$1").replace('http:', '') + '" alt="' + htmlEncode(item.title) + '" />' +
'</div>';
}
cart_items_html += '<div class="item_title">' + item.title +'</div></a>' +
'<div class="price"> ' + Shopify.formatMoney(item.price, $cart.data('money-format')) + '</div>' +
'<div class="quantity_selector">' +
'<span class="minus">-</span><input type="number" min="0" class="quantity" name="updates[]" id="updates_' + item.id + '" value="' + item.quantity + '" /><span class="plus">+</span>' +
'</div>' +
'</li>';

How to apply style sheet on dynamic generate radio button?

here, I am using form wizard. Using ajax to load the data and data are append in html.
ajax code :
$.ajax({
url: '<?php echo base_url(); ?>booking/listSiteUrl',
type: 'post',
dataType: 'json',
success: function (response) {
if (response.success == 1) {
var row = '';
var i = 1;
$.each(response.row_data, function (index, value) {
row += "<tr><td>" + i + "</td><td>" + value.url + "</td><td>" + value.p1_name + "</td><td hidden>" + value.id + "</td><td hidden>" + value.f_n + "</td><td><div class='radio-list'><label><input type='radio' id='f_n_val' name='select_val' data-url='" + value.url + "' data-pub='" + value.p1_name + "' data-id='" + value.id + "' data-follow='" + value.f_n + "' required='required'></label></div></td></tr>";
i++;
});
$("#results").html(row);
// $("input[type=radio]").uniform();
} else {
var row = '';
row += "<tr><td colspan='4' class='text-center'>No Records Found</td></tr>";
$("#results").html(row);
}
}
});
How to apply style sheet on a radio button? you can show in image very clearly...
When I am using uniform style i.e. ($("input[type=radio]").uniform();) work fine and radio button style is applied bt problem in when I am checking validation that time it will look like in below image :
Please help me to find out the way to solve this.
You can create your class in css as
.myradio{
// your code here
}
and then
$("input[type=radio]").addClass('myradio');

Categories

Resources