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>"
Related
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();
});
});
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>';
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.
Currently, I display a category once I check to see if the category id exists, if id is null , document.write. Is there a way to write each category just once without using id?
Here is the JSON:
var foods = {
"category":{
"Meats":[
{
"product":"NY Strip",
"price":20.00,
"cost":14.00,
"total sold": 3
},
{
"product":"Ribeye",
"price":20.00,
"cost":14.00,
"total sold": 6
}
],
"Vegetables":[
{
"product":"Kale",
"price":4.00,
"cost":2.00,
"total sold": 10
},
{
"product":"Sunchokes",
"price":3.20,
"cost":1.00,
"total sold": 5
}
]
}
}
Here is the code:
for(var key in foods.category) {
foods.category[key].forEach(function(item, index) {
// check if the id exists, if not write the category with id
if(document.getElementById(key) === null){
document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
}
document.write("<li>" + item.product + "</li>");
});
}
Here's the result:
Meats
NY Strip
Ribeye
Vegetables
Kale
Sunchokes
assuming category values are unique, the following should produce the same result.
for(var key in foods.category) {
document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
foods.category[key].forEach(function(item, index) {
document.write("<li>" + item.product + "</li>");
});
}
Not sure if you were just trying to eliminate the ID querying via the document object or not, but this just queries via a string being built.
var output = "";
for (var key in foods.category) {
if (output.indexOf("<h4 id='" + key + "'") < 0) {
output += "<h4" + " id='" + key + "'" + ">" + key + "</h4>";
}
foods.category[key].forEach(function (item, index) {
// check if the id exists, if not write the category with id
output += "<li>" + item.product + "</li>";
});
}
document.querySelector('#output').innerHTML = output;
http://jsfiddle.net/phh7nsnv/1/
Dynamically generating rows by jquery
$("#showbtn").on("click", function() {
var tblRow;
$.getJSON('multimob.action', $("#mobileno").serialize(), function(data) {
if (data.mobileno === null) {
alert("Wrong Mobile No.,please Check");
} else {
$.each(data.ls, function(index, value) {
var count = index;
tblRow = $("<tr><td> <input type='radio' id='chk' name='chk' onclick='copyrecord('" + count + "');'/></td><td id='fidrow" + count + "'>" + value.id + "</td>"
+ "<td>" + value.name + "</td>" + "<td>"
+ value.mobileno + "</td>" + "<td>" + value.addres + "</td></tr>");
alert(count + tblRow.toString());
$("#farmTable tbody").append(tblRow);
});
});
The data rows are dynamically created ,Once I select the radio button, it should take the data from that row and it has to be copied to the textfields in the same page .
Help me to get rid of this iisue.
Try this example
Use class
<input type='radio' id='chk' name='chk' class="chk"/>
HTML
$(document).on('click','.chk',function(){
var text=[];
$(this).parents('tr').find('td:not(:first)').each(function(){
console.log($(this).text())
text.push($(this).text())
});
$('#name').val(text[0]);
$('#no').val(text[1]);
$('#add').val(text[2])
});
DEMO
As per your comment: I can change the id and name as 'chk"+count+"' something like this. But how can I copy the row data on selecting the row by radio button
You can get it this way:
$("#farmTable").on('change', '[id^="chk"]', function(){
var tblVals = $("#farmTable tr").map(function(){
return $(this).find('td:not(:first)').text();
});
console.log(tblVals);
});