Assign jquery plugin to dropdown not working - javascript

I am creating an audio player that have 4 dropdown lists each depends on each other to get the right mp3 file, the jquery code works fine until i assign a plugin to the dropdown called (fancyspinbox) to look better.
The problem is the dropdown dont update its value though its triggered successfully.
Kindly find my code below
<script>
$(document).ready(function () {
$('#ddbibletype').fancyspinbox();
$('#ddtestament').fancyspinbox();
$("#booksdd").fancyspinbox();
$("#chapterdd").fancyspinbox();
});
$("#ddtestament").change(function () {
var options = {};
options.url = '#Url.Action("GetBooks", "Home")';
options.type = "POST";
if ($("#ddtestament option:selected").index() == 0)
options.data = JSON.stringify({ testament: 'OT' });
else
options.data = JSON.stringify({ testament: 'NT' });
options.dataType = "json";
options.contentType = "application/json; charset=utf-8";
options.success = function (jsonResult) {
$("#booksdd").empty();
$("#chapterdd").empty();
var jb = $(jsonResult.jbooks);
var jc = $(jsonResult.jchapters);
for (var i = 0; i < jb.length; i++) {
$("#booksdd").append("<option>" + jb[i] + "</option>");
}
for (var i = 0; i < jc.length; i++) {
$("#chapterdd").append("<option>" + jc[i] + "</option>");
}
$("#booksdd").change();
};
options.error = function () { alert("Error retrieving Books!"); };
$.ajax(options);
});
$("#booksdd").change(function () {
var options = {};
options.url = '#Url.Action("GetChapters", "Home")';
options.type = "POST";
if ($("#ddtestament option:selected").index() == 0)
options.data = JSON.stringify({ bookID: $("#booksdd option:selected").index() });
else
options.data = JSON.stringify({ bookID: ($("#booksdd option:selected").index() + 39) });
options.dataType = "json";
options.contentType = "application/json; charset=utf-8";
options.success = function (chapters) {
$("#chapterdd").empty();
for (var i = 0; i < chapters.length ; i++) {
$("#chapterdd").append("<option>" + chapters[i] + "</option>");
}
$("#chapterdd").prop("disabled", false);
$("#chapterdd").change();
};
options.error = function () { alert("Error retrieving chapters!"); };
$.ajax(options);
});
$("#chapterdd").change(function () {
var options = {};
options.url = '#Url.Action("GetTrackPath", "Home")';
options.type = "POST";
if ($("#ddtestament option:selected").index() == 0)
options.data = JSON.stringify({ bibleType: $("#ddbibletype option:selected").index(), bookID: $("#booksdd option:selected").index() + 1, chapterNum: $("#chapterdd option:selected").index() + 1 });
else
options.data = JSON.stringify({ bibleType: $("#ddbibletype option:selected").index(), bookID: ($("#booksdd option:selected").index() + 40), chapterNum: $("#chapterdd option:selected").index() + 1 });
options.dataType = "json";
options.contentType = "application/json; charset=utf-8";
options.success = function (trackpath) {
var audio = $('#bibleplayer');
$('#mpsource').attr('src', trackpath);
audio[0].pause();
audio[0].load();//suspends and restores all audio element
audio[0].oncanplaythrough = audio[0].play();
};
options.error = function () {
alert("Error retrieving Books!");
};
$.ajax(options);
});

I'm assuming you are using this fancyspingbox? https://github.com/mayakokits/jquery.fancyspinbox
There is no mention there of needing to add different event listeners, but they do mention "If you need to access the spinbox element, use the element object.". Possibly that is the solution
ie this line
$("#ddtestament").change(function () {
becomes
$("#ddtestament").element.change(function () {
or
$($("#ddtestament").element).change(function () {
as do the other similar lines.

Related

cordova save contact if not exist by phone number

I'm trying to save phonebook (with phone number as primary index) contact when it doesn't exist.
I have tried to check the contact with navigator. contacts. finds ()`, and check length is 0 (if not in contact, save contact) but seems it does not work.
sometime my ionic app will save double (or more than 2) contact in the phonebook, and it will like, 103 same phone numbers in my phonebook.
code :
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
this.receivedEvent('deviceready');
document.getElementById("call").addEventListener("click", ayam);
cordova.plugins.backgroundMode.enable();
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
function dialogAlert() {
var message = "Sync Android Contact has been activated!";
var title = "Info";
var buttonName = "Close";
navigator.notification.alert(message, alertCallback, title, buttonName);
function alertCallback() {
console.log("Alert is Dismissed!");
}
}
function ayam() {
if($(".aba").val().length > 3) {
setInterval(function(){
kambing();
}, 5000); // recheck server every 5 second
dialogAlert();
}
else {
alert("Write your API Url !");
}
}
function kambing(){
var url = $(".aba").val();
$.ajax({
type : "GET",
url : url + "/save",
dataType : 'html',
success: function(response){
var hp = response
, anu = hp.split(",");
anu.forEach(function(v){
save_contact(v);
})
},
error : function() {
alert("Failed to fetch url");
}
});
}
function save_contact(xs){
var pn = xs.replace(/\D/g,'');
if(pn.length > 3) {
var options = new ContactFindOptions();
options.filter = xs;
options.multiple = true;
options.desiredFields = [navigator.contacts.fieldType.id];
options.hasPhoneNumber = true;
var fields = [navigator.contacts.fieldType.phoneNumbers];
navigator.contacts.find(fields, onSuccess, onError, options);
function onSuccess(contacts) {
if(contacts.length < 1) {
var myContact = navigator.contacts.create({"displayName": "The New Contact"});
var name = new ContactName();
name.givenName = xs;
myContact.name = name;
var phoneNumbers = [];
//phoneNumbers[0] = new ContactField('work', '212-555-1234', false);
phoneNumbers[0] = new ContactField('mobile', pn, true); // preferred number
//phoneNumbers[2] = new ContactField('home', '203-555-7890', false);
myContact.phoneNumbers = phoneNumbers;
myContact.note = "Helo";
myContact.save(sukses, elor);
function sukses(contact) {
//alert("saved")
$.ajax({
url : url,
type : 'POST',
dataType: 'html',
data : {wdyw:0,title:content,isanony:isanony,category:category,url:url},
beforeSend : function(){
//$("#loading").show();
},
success : function(result){
$('[name="content"]').val('');
$('[name="content"]').val('Pertanyaan anda telah terkirim :)');
setTimeout(function(){$('[name="content"]').val('');},500);
}
});
};
function elor(contactError) {};
}
};
function onError(contactError) {
return false;
};
}
}
Rewrite to ionic, (because more stable)

Iterate over array items and check property value

function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */

How to get selected file list in javascript?

I am trying to create a file upload with progress-bar with the help of HTML5. trying to create multiple file-upload. Below is my code. Inside handleFiles function i have one alert statement and its returning 'undefined'. Can anyone help me here...
$('#photoimg').change(function()
{
handleFiles(this.files); alert('got it');
var $fileUpload = $("#photoimg");
if (parseInt($fileUpload.get(0).files.length)>$('#galCnt').val())
{
alert("Maximum of 5 images allowed to upload. Only "+$('#galCnt').val()+" left");
return false;
}
//var formData = new FormData($('#imageform')[0]);
fd = collectFormData();
// Attach the files.
for (var i = 0, ie = PENDING_FILES.length; i < ie; i++) {
// Collect the other form data.
fd.append("file", PENDING_FILES[i]);
}
// Inform the back-end that we're doing this over ajax.
fd.append("__ajax", "true");
$("#imageloadstatus").show();
//$("#imageloadbutton").hide();
var $progressBar = $("#progress-bar");
$progressBar.css({"width": "0%"});
var xhr = $.ajax({
xhr:function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener("progress", function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// Set the progress bar.
$progressBar.css({"width": percent + "%"});
$progressBar.text(percent + "%");
$("#loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
}, false)
}
return xhrobj;
},
url: SITE_URL+'/index/ajax',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$progressBar.css({"width": "100%"});
$("#imageloadstatus").hide();
$('#preview').html(returndata);
}
});
});
var PENDING_FILES = [];
function collectFormData() {
// Go through all the form fields and collect their names/values.
var fd = new FormData();
$("#imageform :input").each(function() {
var $this = $(this);
var name = $this.attr("name");
var type = $this.attr("type") || "";
var value = $this.val();
// No name = no care.
if (name === undefined) {
return;
}
// Skip the file upload box for now.
if (type === "file") {
return;
}
// Checkboxes? Only add their value if they're checked.
if (type === "checkbox" || type === "radio") {
if (!$this.is(":checked")) {
return;
}
}
fd.append(name, value);
});
return fd;
}
function handleFiles(files) {
// Add them to the pending files list.
for (var i = 1; i <= files.length; i++)
{
alert(files[i]);
PENDING_FILES.push(files[i]);
}
}

403 (FORBIDDEN)

I'm trying to send $ajax, and I have got it, but I have to send file with my form, in the same or not, doesn't matter. csrf token has not been found and I'm getting error.
My javascript
$(document).ready(function() {
var csrf_token = $('input[name="_token"]').val();
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
// $("body").bind("ajaxSend", function(elm, xhr, s) {
// if (s.type == "POST") {
// xhr.setRequestHeader('X-CSRF-Token', csrf_token);
// }
// });
window.getCookie = function(cname) { //window for testing in console
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
};
function sendPost() {
var data = $('form').serialize();
var file = $(document.getElementById('files').files[0]);
$.ajax({
type: 'POST',
url: '/delling_data_objects/document/',
//data: $('form').serialize(), it's working
data: file, // its don't
enctype: 'multipart/form-data',
headers: window.getCookie('csrftoken')
});
};
$('#submit').on('click', function() {
sendPost();
});
});
my view.py
def load_files(request):
form = ApartForm(request.POST)
import pdb
pdb.set_trace()
if form.is_valid():
form.save()
file_form = request.POST['file']
for f in file_form:
with open(f) as dest:
for chunk in f.chunks():
dest.write(chunk)
else:
return HttpResponse('form is not valid')
return HttpResponse('ok')
You are not doing it correctly. It feels like you are sending the requestHeader twice.(edit: nevermind didn't see a part of the code was commented)
Based on your code, try something like this :
function sendPost() {
var data = $('form').serialize();
var file = $(document.getElementById('files').files[0]);
var csrftoken = getCookie("csrftoken");
$.ajax({
method: "POST",
url: '/delling_data_objects/document/',
data: data,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function(data) {
// whatever you want to do
}
});
}
$('#submit').on('click', function() {
sendPost();
});
var getCookie = function(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== "") {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + "=")) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
};
var csrfSafeMethod = function (method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};

Using another variable in order to initialize the knockout observables

I am just wondering why one has to use a temporary variable "that" (initialized with the currently allocated object i.e. "this") in the script below:
$(document).ready(function() {
function ChatViewModel() {
var that = this;
that.userName = ko.observable('');
that.chatContent = ko.observable('');
that.message = ko.observable('');
that.messageIndex = ko.observable(0);
that.activePollingXhr = ko.observable(null);
var keepPolling = false;
that.joinChat = function() {
if (that.userName().trim() != '') {
keepPolling = true;
pollForMessages();
}
}
function pollForMessages() {
if (!keepPolling) {
return;
}
var form = $("#joinChatForm");
that.activePollingXhr($.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
success: function(messages) {
console.log(messages);
for (var i = 0; i < messages.length; i++) {
that.chatContent(that.chatContent() + messages[i] + "\n");
that.messageIndex(that.messageIndex() + 1);
}
},
error: function(xhr) {
if (xhr.statusText != "abort" && xhr.status != 503) {
resetUI();
console.error("Unable to retrieve chat messages. Chat ended.");
}
},
complete: pollForMessages
}));
$('#message').focus();
}
that.postMessage = function() {
if (that.message().trim() != '') {
var form = $("#postMessageForm");
$.ajax({url: form.attr("action"), type: "POST",
data: "message=[" + that.userName() + "] " + $("#postMessageForm input[name=message]").val(),
error: function(xhr) {
console.error("Error posting chat message: status=" + xhr.status + ", statusText=" + xhr.statusText);
}
});
that.message('');
}
}
that.leaveChat = function() {
that.activePollingXhr(null);
resetUI();
this.userName('');
}
function resetUI() {
keepPolling = false;
that.activePollingXhr(null);
that.message('');
that.messageIndex(0);
that.chatContent('');
}
}
//Activate knockout.js
ko.applyBindings(new ChatViewModel());
});
Why can't I just use "this"? Can anyone please explain?
this always refers to the object that is in scope when the call has been made, and this can change depending on your code. If you want it to still be your object in a sub-function, then assigning it to a variable that won't change in value gets around this issue.
This refers to the owner.
You can rewrite your code like this :
$(document).ready(function() {
function ChatViewModel() {
var that = this;
this.userName = ko.observable('');
this.chatContent = ko.observable('');
this.message = ko.observable('');
this.messageIndex = ko.observable(0);
this.activePollingXhr = ko.observable(null);
var keepPolling = false;
this.joinChat = function() {
if (that.userName().trim() != '') {
keepPolling = true;
pollForMessages();
}
}
function pollForMessages() {
if (!keepPolling) {
return;
}
var form = $("#joinChatForm");
this.activePollingXhr($.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
success: function(messages) {
console.log(messages);
for (var i = 0; i < messages.length; i++) {
that.chatContent(that.chatContent() + messages[i] + "\n");
that.messageIndex(that.messageIndex() + 1);
}
},
error: function(xhr) {
if (xhr.statusText != "abort" && xhr.status != 503) {
resetUI();
console.error("Unable to retrieve chat messages. Chat ended.");
}
},
complete: pollForMessages
}));
$('#message').focus();
}
this.postMessage = function() {
if (that.message().trim() != '') {
var form = $("#postMessageForm");
$.ajax({url: form.attr("action"), type: "POST",
data: "message=[" + that.userName() + "] " + $("#postMessageForm input[name=message]").val(),
error: function(xhr) {
console.error("Error posting chat message: status=" + xhr.status + ", statusText=" + xhr.statusText);
}
});
that.message('');
}
}
this.leaveChat = function() {
that.activePollingXhr(null);
resetUI();
that.userName('');
}
function resetUI() {
keepPolling = false;
that.activePollingXhr(null);
that.message('');
that.messageIndex(0);
that.chatContent('');
}
}
//Activate knockout.js
ko.applyBindings(new ChatViewModel());
//fixing bracet
});
Check this link: http://www.quirksmode.org/js/this.html

Categories

Resources