How do I store multiple check boxes with local storage - javascript

So, to be honest I am going to have a hard time explaining this so I apologize in advanced.
Basically I am populating a list of checkboxes with the names of cities. using ajax. What I want to do is allow multiple checkboxes to be checked and store each checkbox value in one single key in local storage. I guess it would look something like this as an example in local storage: city: new york,Los Angeles,Miami. I have tried everything I know and I don't even know how to phrase it in google so if anyone could me that would be great. Ill post my code below.
--This is how I am currently populating the checkbox list:
$(document).delegate("#main", "pagecreate", function () {
var citySelect = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'base_city.php',
data: '',
isajax: 1,
dataType: 'json',
success: function (data) {
var $city_box = $('#city-selector');
$city_box.empty();
for (var i = 0, len = data.length; i < len; i++) {
$city_box.append("<label for='city_select'><input type='checkbox' name='city_select[]' class='citySelect' value='" + data[i].city + "'>" + data[i].city + "</label>");
}
}
});
});
--This is how I am currently storing the values:
<script type="text/javascript">
function filterForm() {
var cityNames = $('.city_select').attr('value');
localStorage.setItem("city2", JSON.stringify(cityNames));
window.location = "#main";
location.reload();
}
</script>

try to replace
$('.city_select').attr('value');
by
var arr = [];
$("input[type=checkbox].city_select:checked").each(function(){arr.push(this.value);});

Related

Data fields are undefined in ASP.Net Core MVC using JSON

So, I have an issue with my Javascript code. I am using cascading dropdowns, one is for the car brand and another one for the car model. According to logic, when I choose one of the brands from the dropdown (e.g. Toyota or Audi, etc.) the second dropdown should show the models of the selected brand. Generally, I use GetModelsJson method in the controller to join Brand and Model tables and return models as json.
public JsonResult GetModelsJson(int p)
{
var models = (from x in GetModels()
join y in GetBrands() on x.BrandId equals y.Id
where x.BrandId == p
select new
{
Text = x.Name,
Value = x.Id.ToString()
}).ToList();
return new JsonResult(new { data = models });
}
In the view, I want to display the dropdowns using following code:
#Html.Label("Brands")
#Html.DropDownList("drpBrand",Model.BrandList,"--Select Brand--", new {#class = "form-control"})
#Html.Label("Models")
#Html.DropDownList("drpModel",Model.ModelList,"--Select Model--", new {#class = "form-control"})
The problem starts in the javascript code. Everything works fine until a for loop. For some reason, length of the data variable and other fields like text and value are undefined.
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function(){
$('#drpBrand').change(function(){
var id = $('#drpBrand').val();
$.ajax({
url: '/Admin/Vehicle/GetModelsJson',
data: {p : id},
type: "POST",
dataType: "Json",
success: function(data){
console.log(data);
$('#drpModel').empty();
for (let i = 0; i < 3; i++){
$('#drpModel').append("<option value ='" + data[i].value + "'>" + data[i].text + "</option>");
}
}
});
});
});
</script>
As a result, the second dropdown for models becomes empty.
Picture of the web site
As you can see from this picture, the second dropdown is empty, although according to console data has its fields like "A5", "A4", "A6".
As the picture you uploaded the object from the server has a "data" field which contains the array so edit your code like this:
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function(){
$('#drpBrand').change(function(){
var id = $('#drpBrand').val();
$.ajax({
url: '/Admin/Vehicle/GetModelsJson',
data: {p : id},
type: "POST",
dataType: "Json",
success: function(data){
console.log(data);
$('#drpModel').empty();
for (let i = 0; i < data.data.length; i++){
$('#drpModel').append("<option value ='" + data.data[i].value + "'>" + data.data[i].text + "</option>");
}
}
});
});
});
</script>

Passing a parameter with an onclick event

I'm working on a project with API calls. Basically, I need to be able to pass a parameter to a function with jQuery when a certain button is clicked.
I am working on a project that calls an API to display class buttons to a user.
Each button will be generated based on the presence of a classId, which is called in a jQuery file:
jQuery:
function getCourses() {
$.ajax({
url: apisource + "/courses",
dataType: "json"
}).done(function(data) {
let dataLength = Object.keys(data).length;
for (let i = 0; i < dataLength; i++) {
courseId = data["courses"][i].id; //this is the important part
nameOfClass = data["courses"][i].name;
let classButton = ('<button type=\'button\' class=\'classButton\' onclick=\'javascript:getStudentsInCourses(' + courseId + ');\'>' + nameOfClass + '</button>');
$('#classButtonContainer').append(classButton);
}
})
}
getCourses();
function getStudentsInCourses(currentCourseId) {
console.log("current course id: " + currentCourseId);
$.ajax({
url: apisource + "/course=" + currentCourseId + "/students",
dataType: "json"
}).done(function(data) {
console.log("here are the students");
console.log(data);
}}
What I want to do here is that when a user clicks on a class button, the courseId for that button becomes the "currentCourseId", and is able to be passed to getStudentsInCourses so that it can call the students for that course. I've been scouring the web for the proper way to pass that variable but no method has worked so far. Does anyone have any pointers for how to pass this variable?
So it should be something like this:
when a user clicks one of the classButtons, that button's courseId will pass to the "getStudentsInCourses" function as the "currentCourseId"
In Jquery you can use the click event to execute a logic.
Do not forget to call the function before the click event below.
//your functions
$('.classButtons').on('click', function(){
const id = $(this).attr('id');
//now call your function with the id
getStudentsInCourses(id);
});
If you have questions or misunderstood your request let me know =)
It seems to be working for me. Perhaps, it's your courseId variable that's causing an issue ? Are you sure it's not the same id ?
courseId = data["courses"][i].id;
function getCourses() {
for (let i = 0; i < 5; i++) {
let classButton = ('<button type=\'button\' class=\'classButton\' onclick=\'javascript:getStudentsInCourses(' + i + ');\'>Test ' + i + '</button>');
$('#classButtonContainer').append(classButton);
}
}
getCourses();
function getStudentsInCourses(currentCourseId) {
console.log("current course id: " + currentCourseId);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="classButtonContainer"></div>

If new data else stop insert over and over

To keep it simple, I'm just wanting to know how I'd go about and if else statement against my ajax to print new data out once if it finds it and not the same data over and over again. Amd how can I possibly store the last id as a variable to reuse it when searching for more new records?
Someone mentioned to me also I could save the new notification idea as a return so when the ajax restarts it uses this to find the next new set of results.
Has anybody got any ideas how to achieve these?
<script type="text/javascript">
setInterval(function(){
var time = new Date().getTime();
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
}
});
},20000);
</script>
Regarding to store the last id, you could use:
window.localStorage.setItem('key', 'value');
Then when you want to get it again you'll should use:
var lastId = window.localStorage.getItem ('key');
And regarding the duplicates issue, well, you should have a internal storage in order to handle the recieved data. May be an array can help as storage, also you can also store this array in local storage.
Once you handle this data storage, you could apply something like this to verify that your data has no duplicates:
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
UPDATE
var notification_id = window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler(response);
if(response.num){
window.localStorage.setItem('lastId', response.num);
}
});
},20000);

Set form data without creating DOM inputs

I have an empty form tag, and a function which generates 4000 hidden inputs which contains the data to be send by the form.
Generating the 4000 hidden inputs is pretty fast (takes about 4ms). However, the browser freezes for about 1 second when i am appending the hidden inputs in the form tag.
I have also wrapped the hidden inputs in a <div/> tag, but doesn't helps too much.
Is there any way to set the form data programmatically, without using the input DOM elements?
Something like:
$form[0].setData([{ id: 1, value: "A" }, { id: 2, value: "B" }]);
$form.submit();
Here is the function which generates the hidden inputs
function saveUIPositions() {
var $form = $("#saveUIPositionsForm");
$form.empty();
console.time("ui");
var array = [];
array.push("<div>");
var items = dataTable.dataView.getItems();
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
var index = dataTable.dataView.getRowById(item.Id) + 1;
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Item_Id' value='");
array.push(item.Id);
array.push("' />");
array.push("<input type='hidden' name='[");
array.push(i);
array.push("].Index' value='");
array.push(index);
array.push("' />");
}
array.push("</div>");
console.timeEnd("ui");
// here it gets very costly (and not because of array.join())
$form.append(array.join(""));
$form.submit();
};
Maybe you can send this data using ajax ? If so you will not have to generate and append your 4K hidden inputs to the DOM.
If ajax is not an option, can you give us the code generating and appending your inputs ? Maybe it can be optmized.
I wrote a small jsFiddle (open your debug console to see time informations)
to illustrate the difference between a generate then append all solution:
for(var i=0; i<4000; i++)
inputs += '<input type="hidden" value="' + i + '"/>'
$('form').append(inputs);
and generate and append each:
for(var i=0; i<4000; i++)
$form.append('<input type="hidden" value="' + i + '"/>');
You don't even really need a form element when working in just Javascript, data can be sent to your server with an ajax request.
$.ajax({
url: "myScript.php", //The script on your server that deals with the data
data: {
dataA: "a",
dataB: "b",
dataC: "c" //Your form input name and value key pairs
},
success: function(data){
alert("Form Submitted, Server Responded:"+data); //The server response
},
error: function(data){
alert("Error contacting server:"+data); //Error handler
}
});
You don't even need to reload the page when the form is submitted. Unless you want to, then just add:
location.href="http://link.com";
to the success callback.
You don't need to add the inputs to the DOM, you could create an array of the data an post the form via ajax e.g.
inputNames = 'YourInputNameHere'; // Could be an array of names
generatedData = arrrayOfData //presumably generated elsewhere
for (i=0;i<400;i++) {
formData[inputName][i] = generatedData[i]
// if you are using an array of names you want to change the above line to
// formData[inputName[i]] = generatedData[i]
}
$('body').on('submit', '#myForm', function(e) {
e.preventDefault();
postUrl = 'url/to/send/data';
// get any other use inputs that might have been taken from user ignore
// this line if there are no inputs
formData[] = $(this).serialize();
$.ajax(
{
url: postUrl,
type: 'POST',
data: formData,
dataType: 'html',
success: function( data )
{
// redirect, post message whatever
}
}
)
});
Hope this helps and makes sense.

Implementing jQuery Autocomplete

So I came up with this script that ajax calls google's suggestions and JSONP returns the search results. I managed to make the results sorted but I'd like to implement jquery autocomplete instead. I've tried any possible way I could think of but haven't got any results.
Here is the a working fiddle: http://jsfiddle.net/YBf5J/
and here is the script:
$(document).ready(function() {
$('#q').keyup(retrieve);
$('#q').focus();
$('#results').show('slow');
$("#q").autocomplete(parse, {
Height:100,
width:620,
noCache: false,
selectFirst: false
});
});
function retrieve() {
$.ajax({
type: "GET",
url: 'http://suggestqueries.google.com/complete/search?qu=' + encodeURIComponent($('#q').val()),
dataType: "jsonp",
jsonpCallback: 'parse'
});
}
var parse = function(data) {
var results = "";
for (var i = 0; i < data[1].length; i++) {
results += '<li>' + '' + data[1][i][0] + '' + '</li>';
}
$('#results').html('' + results + '');
$('#results > li a').click(function(event) {
event.preventDefault();
$('#q').val($(this).html()).closest('form').submit();
});
}
And here's the simple body:
<body><input type="text" id="q"><div id="results"></div></body>
Any help is really appreciated.
Thanks alot, rallyboy.
Here is an example of using the Jquery-UI Auto complete. Taken from your code, all i did was update the auto complete source every time the data changes using this code.
var parse = function(data) {
var results = [];
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i][0]);
}
$('#q').autocomplete({
source: results
});
See fiddle
http://jsfiddle.net/WUcpC/1/
It uses just the base CSS but that can be changed by pointing it at which ever theme you want.

Categories