auto check checkboxes for matching result in ajax call - javascript

I'm trying to make it so that when my ajax call is returned with an object/array, I can match up the results to checkboxes so that if there is a match I auto check the boxes
Here are my checkboxes
<input type="checkbox" name='Magazine' data-md-icheck />
<input type="checkbox" name='Website' data-md-icheck />
<input type="checkbox" name='Advertisement' data-md-icheck />
Now my ajax call is successful
I get back:
0: {}
type: "Magazine"
1: {}
type: "Website"
so in my ajax success, what I would like to do is take any result in that object, whether just one or all 3, and if the type matches the 'name' of the checkbox I want to check that box.
Here is my function that makes the successful ajax call. I just can't figure out a way to loop the return that I get so that I can match up any result that comes through
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
},
});
};
So in this case, how would I modify my ajax success to check the magazine and website boxes?

Here is a pure JS and simple solution to this:-
// Assuming you get the response as an array of objects, which has a key as type
success: function (data) {
data.forEach(obj => {
let ele = document.getElementsByName(obj.type)[0];
if(ele) {
ele.checked = true;
}
});
}

This is how I would tackle it:
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
for(var i=0;i<data.length;i++){
var item = data[i].type;
var checkbox = $('input[name="'+item+'"]);
if (checkbox.length){
checkbox.prop('checked', true);
}
}
},
});
};

Assume the result is pure text exactly the same as you provided (ES6+)
let a = 'result...'
['Magazine', 'Website', 'Advertisement'].filter(item => a.indexOf(item) != -1).forEach(item => {
let inputs = document.getElementsByName(item)
if (inputs.length > 0)
inputs[0].checked = true
})

Related

Js function passes null to the controller, in the old version

I need to wrote a code on an older version of the .net Framework, namely 4.5.2.
I ran into a problem, the ajax code sends an empty request to the controller.
Here is the form and I need to check user Full Name on unique:
<div class="register-card">
<h1>Register the new user</h1>
#using (Html.BeginForm("CreateUserAsync", "Home", FormMethod.Post))
{
<div>
#Html.Label("FullName", "Enter your full name")
<input type="text" id="FullName" name="FullName" pattern="^(\w\w+)\s(\w+)\s(\w+)$" onblur="CheckAvailability()" required />
<span id="message" onclick="ClearMessage()"></span>
</div>
<p><input type="submit" value="Send" id="submit" /></p>
}
</div>
Here is my js function to checking Full Name:
function CheckAvailability() {
var data = $("#FullName").val();
var param = data;
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "String",
data: JSON.stringify(param),
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
};
function ClearMessage() {
$("#message").html("");
};
Js function pass the FullName to next controller:
[HttpPost]
public async Task<JsonResult> CheckFullNameAsync([FromBody]string fullName)
{
var isValid = await _service.IsUserExistAsync(fullName);
return Json(isValid);
}
But the controller receives null.
I think the problem is in the Js function, but I can figure out what I'm doing wrong.
Dont need to create two variable
var data = $("#FullName").val();
var param = data;
Just create
var param = $("#FullName").val();
try this
Check this link. it explains your problem well
$.ajax({
type: "POST",
url: "/Home/CheckFullNameAsync",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: 'json',
data:{"":param},
//data: { fullName: param },
success: function (response) {
var message = $("#message");
if (response) {
message.css("color", "red");
message.html("Full name is already exist");
$('#submit').attr('disabled', 'disabled');
}
else {
console.log(JSON.stringify(param));
message.css("color", "green");
message.html("Full name is available");
$('#submit').removeAttr('disabled');
}
}
});
or this one also
$.post('/Home/CheckFullNameAsync', { fullname: param},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
What is dataType: "String"? That's not a listed option. And more specifically, all you're sending is a value but with no key. So the server isn't able to deserialize the data and determine where the fullName value comes from.
Change the type to 'json' and send the object with the named key for the value:
dataType: "json",
data: { fullName: param },

Getting an error when i loop through to get input name value

Can't figure out why this loop won't give me the info i'm wanting
I have a page with a few hundred inputs on it , i want to get the the input "name" value for each input that is checked
<input type="checkbox" name="TAXI_SQUAD0001" checked="checked">
<input type="checkbox" name="TAXI_SQUAD0021" checked="checked">
<input type="checkbox" name="TAXI_SQUAD0011">
$.ajax({
url: urlHPM,
xhrFields: {
withCredentials: true
},
cache: false,
type: "GET",
success: function (data) {
checkedInputs = $(data).find('input[checked="checked"]');
for (var i = 0; i < checkedInputs.length; i++) {
console.log(checkedInputs.attr('name')[i]); // loops character of first name of first input over and over
console.log(checkedInputs[i].attr('name')); // error attr not a function
// i want to log input names TAXI_SQUAD0001 and TAXISQUAD0021
}
},
error: function (xhr) {
}
});
You can loop all checked checkboxes in the ajax success response using the .each() jQuery function.
$.ajax({
url: urlHPM,
xhrFields: {
withCredentials: true
},
cache: false,
type: "GET",
success: function (data) {
checkedInputs = $(data).find('input[checked="checked"]');
$(checkedInputs).each(function(){
//Log the input name attribute
console.log($(this).attr('name'));
});
},
error: function (xhr) {
}
});
You are accessing the DOM when you do checkedInputs[i]. It is not the jQuery wrapped code. You can do checkedInputs.eq(i).attr('name') or just checkedInputs[i].name
Your code also does not need the for loop. You can just use each.
checkedInputs.each(function () {
var cb = $(this);
console.log(cb.attr('name'));
});

How to post jquery ajax data object with multiple values

I have a form with two inputs (later more inputs). One input is a text input and the second one is a checkbox. I would like to send these two inputs with $.ajax.
I created an Object formData with one input. The second one I would like to append to the Object if the checkbox is active or not.
Unfortunately, I can't pass the Object because of a wrong format.
My Code:
<form id="myForm">
<input type="text" name="search_text" id="search_text" placeholder="Search by a name">
<input type="checkbox" name="exact" value="Exact">Exact
</form>
<br>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').on('change', ':checkbox', function(){
if($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
}
else {
console.log($(this).val() + ' is now unchecked');
}
});
var formData = {'qry':search};
$('#search_text').on('keyup', function(e){
e.preventDefault();
var search = $(this).val();
$('#result').html('');
$.ajax({
url:"fetch.php",
method: "POST",
data: formData,
dataType: "text",
success:function(data) {
$('#result').html(data);
}
});
});
});
</script>
You need to serialise the form data and then add more data if required:
var data = $('#myForm').serializeArray();
data.push({name: 'sample', value: "something_more"});
Your ajax should then be something like:
var data = $('#myForm').serializeArray();
data.push({name: 'sample', value: "something_more"});
$.ajax({
url:"fetch.php",
method: "POST",
data: data,
dataType: "text",
processData: false,
success:function(data) {
$('#result').html(data);
}
});

jQuery autocomplete UI - doesn't work

I am trying to make an autocomplete widget that will display item's codes returned from a database.
I have successfully made it so my database will return the appropriate JSON response.
The problem now is I don't know why the drop-down list doesn't show up.
Here's the code down below:
<input type="text" id="search" class="form-control" placeholder="">
<form action="post" action="" id="spareParts" class="spareparts">
</form>
$('#search').keyup(function(event) {
var search = $(this).val();
if($.trim(search).length){
var arr = [];
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: search},
success: function (data) {
arr = $.parseJSON( data );
console.log(arr);// CONSOLE.LOG WORKS WELL
//[Object { id="1", value="25.00", desc="Fuel pump", more...}]
// AUTOCOMPLETE DOESN'T WORK
$('#spareParts').autocomplete({
minLength:0,
source: arr
});
}
});
}
});
The autocomplete with AJAX loaded data should be configured differently. source property can be a function which accepts a callback parameter. You should feed this callback with data loaded from server.
Also you don't need to bind keyup event manually. Your code will become:
$('#search').autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: request.term}
}).done(function(data) {
response(data.map(function(el) {
return {
value: el.value,
label: el.desc
};
}))
});
}
});

How to pass checkbox values into an array using jQuery?

I am have the below checkboxes and I want to pass the checked values to an array so that I can do an ajax post. However, I am hitting an error and I am not sure where I went wrong...
How do I pass the values into the array and how do I retrieve them?
HTML
<input type="checkbox" name="newCheckboxes" value="1" />
<input type="checkbox" name="newCheckboxes" value="2" />
<input type="checkbox" name="newCheckboxes" value="3" />
Script (not working)
var allFields = $( [] );
$("#newCheckboxes:checked").each(function() {
allFields.add( $(this).val() );
});
$.ajax(
{
type:"POST",
url: "PostedHere",
data:{
checkedValues: allFields
}
});
You only need:
$.ajax({
type:"POST",
url: "PostedHere",
data: { checkedValues: $("#newCheckboxes:checked").serialize() }
});
// checkedValues: "newCheckboxes=1&newCheckboxes=2" etc..
Using karim79 code idea:
$.post('URL', $('[name="newCheckboxes"]:checked').serializeArray(), function(data){
//data
});
What I prefer to do is: Create a new Object and add all checkboxes 'Value' and 'Ischecked' to an array (access), then pass it to page by Json:
$(document).ready(function () {
$("#btnSave").click(function () {
event.preventDefault();
$("#newCheckboxes").each(function () {
var data= new Object()
var access = new Array();
access.ChValue = $(this).attr("value");
if ($(this).attr("checked") == "checked") access.ChChecked = true;
data.push(access);
});
$.ajax({
type: 'POST',
url: '#Url.Content("~/URLofPage")',
data: $.json.encode(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
});
please do not forgot to add Json reference to your page:
<script src="../../../Scripts/jquery.json.js" type="text/javascript"></script>

Categories