selected checkboxes(dynamically created) values should be set to destination text field - javascript

For destination text field, based on the input, the auto suggestion will be displayed as checkboxes. I can select one or more values and my requirement is to get these selected values on the controller side, Once I click on the search button. How can I achieve this for dynamic checkboxes, please provide any suggestions.
jquery:
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
HTML:
<form method="post" id="searchForm" action="someAction/showStatistics" id="ems">
<label>Destination</label>
<input type="text" id="destinationName" name="destinationName" value="${someForm.destinationName}" class="field" />
<div class="dest"></div>
<input type="submit" class="button" value="search" />
</form>

Try this
$(document).ready(function () {
var dynamicCheckbox = [];
$("#destinationName").autocomplete({
source : function(request, response) {
$.ajax({
url: "${pageContext.request.contextPath}/showDestinations",
type: "POST",
data: { term : request.term },
dataType: "json",
success: function(data) {
$('.dest').html("");
$.each(data, function(i, record) {
$('.dest').append("<br/><input class= 'src' type='checkbox' id='chk-" + i + "' name='" + record + "' /> " + record);
});
};
});
}
});
$('.button').on('click', function (event) {
event.preventDefault();
$('.dest input:checked').each(function() {
dynamicCheckbox.push($(this).attr('name'));
});
console.log(dynamicCheckbox);
});
});
Here in dynamicCheckbox you will get the names of the checked checkboxes.
Hope that's what you need!

Related

Post request doesn't receive data from autocomplete (jQuery)

I apaologize in advance if not enough info will be given, I'm just a novice, but i will try to explain it the best I can.
In short, the data from ajax is not sent back to the "AutoComplete" request in the controller. I have a input form field that is directly connected to the autocomplete function, the "url" is specified and all the components i can think of. I think the problem is in the "data" part of the code, but I'm not quite sure. When i hardcode the incoming string value to a letter that one of the names in my database contains, then it works fine (discluding the possibility of the controller not working properly). Code below.
Home controller
[HttpGet]
public IActionResult TestView()
{
return View();
}
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
var customers = (from customer in _context.Customers where customer.Name.StartsWith(prefix) select new {
label = customer.Name, val = customer.CustomerId})
.ToList();
return Json(customers);
}
[HttpPost]
public IActionResult TestView(string CustomerName, string CustomerId)
{
ViewBag.Message = "CustomerName: " + CustomerName + " CustomerId: " + CustomerId;
return View();
}
TestView.cshtml
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<script>
$(function() {
$("#txtCustomer").autocomplete({
source: function(request, response) {
$.ajax({
url: '/Home/AutoComplete/',
data: "{ 'prefix': '" + request.term + "'}", #* also tryed == > data: { prefix: request.term }*#
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data, function(item) {
return item;
}))
},
error: function(response) {
alert(response.responseText);
},
failure: function(response) {
alert(response.responseText);
}
});
},
select: function(e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
#using (Html.BeginForm("TestView", "Home", FormMethod.Post))
{
<input type="text" id="txtCustomer" name="CustomerName"/>
<input type="hidden" id="hfCustomer" name="CustomerId" />
<br />
<br />
<input type="submit" id="btnSubmit" value="Submit" />
<br />
<br />
#ViewBag.Message
}
</body>
Hope I managed to explain enough and sorry if my terminology is not the best. Thank you!

Changing from a textbox onblur to onKeyDown event

I have the following code on my partial view:
#foreach (var lineItem in Model.LineItems)
{
<tr>
<td>
<img src="#Url.Action("GetImage", "ImageBlocks", new { imageID = lineItem.Product.SelfOrDefault().Image.SelfOrDefault().ImageId, Width = 75 })" alt="Thumbnail" />
</td>
<td>
<span title="#(lineItem.Description ?? "")" id="lineItemDescription">#(lineItem.Product.ReceiptName ?? "")</span><br />
<span id="lineItemSKU">#lineItem.Product.SKU</span>
</td>
<td>
<span>#((lineItem.Product.InventorySummary ?? 0).ToString())</span><br />
</td>
<td><input type="text" id="lineItemQuantity" name="lineItemQuantity" value="#lineItem.Quantity" onblur="changeCartQty(#lineItem.Product.SKU,this.value)" /></td>
#if (lineItem.Discount != null ? lineItem.Discount.DiscountCategory != DiscountCategory.ORDER : true)
{
<td>
<input type="text" id="lineItemAmount" name="lineItemAmount" value="#lineItem.AdjustedUnitPrice.Value.ToString("C")" /><br />(Adj. #(lineItem.DiscountDisplayValue))
</td>
<td>#lineItem.AdjustedTotalLinePrice.Value.ToString("C")</td>
}
else
{
<td>#lineItem.BaseUnitPrice.Value.ToString("C")</td>
<td>#lineItem.TotalLineBaseValue.ToString("C")</td>
}
<td>Remove</td>
</tr>
}
<script>
On the lineItemQuantity text input, I want to change this from onblur to an onKeyDown event to capture the "Enter" key pressed to call the changeCartQty function with the same parameters. Here is the function being called:
function changeCartQty(ProductId, Quantity) {
var userId = $('#ID').val();
$.ajax({
url: "/Orders/AddtoCart",
type: 'POST',
cache: false,
datatype: 'json',
async: false,
data: { "ProductID": ProductId, "Quantity": Quantity, "UserID": userId},
success: function (data) {
console.log("Adjusted Quantity in cart");
success(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error("[Error in Ajax request, adjust price] Code:" + jqXHR.status + "Error: " + errorThrown + " \nText Status: " + jqXHR.resonseText);
}
})
};
This works fine and the amounts update, I just need to change this to an onChange and I am unsure how this would be done.
Thanks.

Shopify Trying to update a customer

I'm trying to create a view where my customer can update his personal info (like First Name, Last Name, email, ect) using Liquid/JS, but I have failed epicly.
The nearest point that I have reached is this post where they use a form and some AJAX to update but I'm getting code 500. This is the code that I'm using (based on that).
<form action="/a/custmeta" method="POST" id="custmeta">
<input type="text" name="customer[id]" value="{{ customer.id }}" />
<input type="text" name="customer[first_name]" value="{{ customer.first_name }}" placeholder="namespace1.key1" />
<input type="text" name="customer[last_name]" value="{{ customer.last_name }}" placeholder="namespace2.key2" />
<input type="submit" />
</form>
<script>
$('form#custmeta').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: $(this).serialize(),
url: '/admin/customers/#{{ customer.id }}.json',
success: function (data) {
var formValid = (data.status === 'OK');
if (formValid) {
var msgs = '';
for (var i=0;i<data.messages.length;i++) {
msgs += '-- ' + data.messages[i] + '\n';
}
if (msgs > '') {
alert('SUCCESS WITH MESSAGES:\n\n' + msgs);
}
else {
alert('SUCCESS!');
}
}
else {
alert('Status: ' + data.status + '\nMessage: ' + data.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('AJAX or Server 500 error occurred');
}
});
return false;
});
</script>
found this other post where you could do it using the API but dont know how to use it.
Any help?

Send checkbox values in Ajax

The following code is my original code. In the code, I tried to post value of an input for each checkbox which is checked.
<tbody class="myFormSaldo">
<tr>
<td> <input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$ref.'" onchange="enableList(this);" class="chb_group" /> </td>
<td> <input name="items['.$i.']" type="text" readonly value="'.$obj->items.'" /> </td>
<td> <input name="size['.$i.']" type="text" readonly value="'.$obj->size.'Kg" /> </td>
<td> <input name="quantity['.$i.']" type="text" readonly value="'.$obj->myquantity.'" /> </td>
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_size=$_POST['size'][$i];
The code above is working fine. It post the value of each inputs for each checkbox which were checked. For example; if there were three checkedbox which were checked and the form was submited, then it would post three arrays (3 loop) of : $product_name,$product_size,etc..
What I want now is to use Ajax. Like this:
var product_name= document.getElementById('product_name').value;
var product_size = document.getElementById('product_size').value;
$.ajax(
{
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: product_name='+product_name+'&product_size ='+product_size ,
cache: false,
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
But it doesn't count or find the checkbox
So my question now is how to do the same as the php do with foreach($_POST['checkbox'] as $i) in ajax?
I am just a beginner in all of these things.
Thank you for any help.
You are using your product_name as a string, not as a variable:
Try this:
data: 'product_name='+product_name+'&product_size='+product_size,
Or, as Ghost sad in comments, use formdata.
var dataString = $('form').serialize();
and later, in the ajax:
data: dataString,
...
Try this...
<script>
$.ajax({
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: "{'product_name':" + product_name + ", 'product_size':" + product_size+ "}",
cache: false,
dataType: "html"
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
</script>
Try this
Ajax is simplified check here
var data = $('form').serialize();
$.post( "../actions/selectReferenceOrder.php", { name: data}).done(function( data ) {
alert( "Data Loaded: " + data );
});
OR
$.post( "../actions/selectReferenceOrder.php", { product_name: product_name, product_size : product_size }).done(function( data ) {
alert( "Data Loaded: " + data );
});

show php json data into jquery ajax

I'm very new in this topic.I have a Json result something like this :
{
"span": " 1",
"numcard": "12",
"chan": " Yes",
"idle": "Yes",
"level": "idle ",
"call": "No ",
"name": ""
}
How can I show all the json data using a ajax .I currently have this code written up and although i am getting the data its not quite working the way i want it to be.
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$.each(data, function(key, val) {
$("#span").val(val.span);
$("#numcard").val(val.numcard);
$("#chan").val(val.chan);
$("#idle").val(val.idle);
$("#level").val(val.level);
$("#call").val(val.call);
$("#name").val(val.name);
});
}
}
});
});
<input id="span" name="span" value="" />
<input id="numcard" name="numcard" value="" />
<input id="chan" name="chan" value="" />
<input id="idle" name="idle" value="" />
<input id="level" name="level" value="" />
<input id="call" name="call" value="" />
<input id="name" name="name" value="" />
when I try to alert ,example alert(val.span) it keep showing undifined .Does anyone with experience in this topic and see if any problem about my code? Any help would be greatly appreciated.Thank you .
You are returning a single set of values so you do not need the each within your success handler. Try this:
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
In theory, you shouldn't need the data != "" check as your server side code should not be allowed to return an empty response for when the result of the request is 200 OK.
Try this:
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
});
});
should be
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}

Categories

Resources