I am trying to set up an array of keys that are strings instead of numbers. But, when I try to do so, the array ends up null.
Here is the function that works (where the keys are just a simple number "i":
function loadImages(arr, data, callBack){
var count = 0;
var img = new Array();
for(var i in arr ){
var src = "\""+arr[i]+"\"";
img[i] = new Image();
img[i].src = arr[i];
img[i].onload = function(){
count++;
if(count == arr.length){
callBack(data, img);
}
}
}
}
Here is the function I am attempting to use but the resulting array is null:
function loadImages(arr, data, callBack){
var count = 0;
var img = new Array();
for(var i in arr ){
var src = "\""+arr[i]+"\"";
img[src] = new Image();
img[src].src = arr[i];
img[src].onload = function(){
count++;
if(count == arr.length){
callBack(data, img);
}
}
}
}
I have tried defining "src" in the following ways too:
var src = arr[i];
var src = "'"+arr[i]+"'";
Does anyone know why it is resulting in null?
Javascript arrays are not good to be used for an enumerated array. That is what you are trying to do here. Use Object instead.
Then you can use a string as a key.
function loadImages( arr, data, callBack )
{
var nCount = 0 ;
var oImg = new Object() ;
for ( i = 0; i < arr.lenght; i++ )
{
var sSrc = "\"" +arr[ i ]+ "\"" ;
oImg[ sSrc ] = new Image() ;
oImg[ sSrc ].src = arr[ i ] ;
oImg[ sSrc ].onload = function()
{
count++;
if ( count == arr.length )
{
callBack( data, oImg ) ;
alert( oImg ) ;
}
}
}
}
JAVASCRIPT
function loadImages(arr, data, callBack){
var count = 0;
var img = new Array();
for(i=0; i<arr.lenght; i++ ){
var src = "\"" +arr[i]+ "\"";
img[src] = new Image();
img[src].src = arr[i];
img[src].onload = function(){
count++;
if(count == arr.length){
callBack(data, img);
alert(img);
}
}
}
}
Try this..
Related
I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);
I'm trying to script a converter (image) that pickup the checksum inside a image (form my Server) and add it to the selected image file.
But there I got 2 problems:
First problem:
It just accept jpg files, I tried everythink, but it dont work (png, gif etc.)
The second problem is, that the valid image, need to be from my server (convert.jpg)
But if I do that, I get this error:
TypeError: Argument 1 of FileReader.readAsDataURL is not an
object.
The line:
readerValid.readAsDataURL(valid);
What did I do wrong? (And sry for my bad english)
My Code:
function hexToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
function bytesToHex(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes.charCodeAt(i) >>> 4).toString(16));
hex.push((bytes.charCodeAt(i) & 0xF).toString(16));
}
return hex.join("");
}
function UpdateChecksum(pic, data) {
var string = ""
for (var i = 0; i < data.length; ++i) {
string += String.fromCharCode(data[i])
}
pic = atob(pic.replace(/^data:image\/jpeg;base64,/, ""))
for (var i = 0; i + 1 < pic.length; ++i) {
if (pic.charCodeAt(i) == 0xFF && pic.charCodeAt(i + 1) == 0xDB) {
pic = pic.slice(i, pic.length)
break
}
}
var regexp = new RegExp("(<checksum2>[0-9a-f]{32}</checksum2>)")
var match = regexp.exec(string)
string = string.replace(match[1], "<checksum2>" + bytesToHex(rc4("bns_gamepic", hexToBytes(md5(pic)))) + "</checksum2>")
for (var i = 0; i < data.length; ++i) {
data[i] = string.charCodeAt(i)
}
return data
}
function process() {
if(document.getElementById("custom").value == ""){
document.getElementById('error').innerHTML="Chose Image!";
}
else{
var valid = "convert.jpg";
var custom = document.getElementById('custom').files[0]
var readerValid = new FileReader()
readerValid.onloadend = function(e) {
var exif = piexif.load(e.target.result)
var readerCustom = new FileReader()
readerCustom.onloadend = function(e) {
var image = new Image()
image.onload = function() {
var result
try {
result = piexif.remove(e.target.result)
} catch (err) {
result = e.target.result
}
exif["Exif"][700] = UpdateChecksum(result, exif["Exif"][700])
result = piexif.insert(piexif.dump(exif), result)
download(result, "Converted_Image.jpg", "image/jpeg");
}
image.src = e.target.result
}
readerCustom.readAsDataURL(custom);
};
readerValid.readAsDataURL(valid);
}
}
I hope you can help me
Someone said:
The code var valid = "convert.jpg"; defines valid as a string, but the function readAsDataURL expect an object of type blob as a parameter, not a string.
But:
var valid = new Blob(["convert.jpg"], { type: 'image/jpeg'});
dont work :/
I have a html tag like this.
<a class="employee_details" target="_blank" href="index1.php?name=user1&id=123">User</a>
I need to get the two parameter values in jquery
<script type="text/javascript">
$(function () {
$('.employee_details').click(function () {
var status_id = $(this).attr('href').split('name');
alert(status_id[0]);
});
});
</script>
Any help in getting both the parameter values in two variables in javascript.
I want to get user1 and 123 in two variables using jQuery
Thanks
Kimz
You can use URLSearchParams as a most up-to-date and modern solution:
let href = $(this).attr('href');
let pars = new URLSearchParams(href.split("?")[1]);
console.log(pars.get('name'));
Supported in all modern browsers and no jQuery needed!
Original answer:
Try this logic:
var href = $(this).attr('href');
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
console.log(result);
So you'll get the parameters as properties on result object, like:
var name = result.name;
var id = result.id;
Fiddle.
An implemented version:
var getParams = function(href)
{
var result = {};
var pars = href.split("?")[1].split("&");
for (var i = 0; i < pars.length; i++)
{
var tmp = pars[i].split("=");
result[tmp[0]] = tmp[1];
}
return result;
};
$('.employee_details').on('click', function (e) {
var params = getParams($(this).attr("href"));
console.log(params);
e.preventDefault();
return false;
});
Fiddle.
$(function() {
$('.employee_details').on("click",function(e) {
e.preventDefault(); // prevents default action
var status_id = $(this).attr('href');
var reg = /name=(\w+).id=(\w+)/g;
console.log(reg.exec(status_id)); // returns ["name=user1&id=123", "user1", "123"]
});
});
// [0] returns `name=user1&id=123`
// [1] returns `user1`
// [2] returns `123`
JSFiddle
NOTE: Better to use ON method instead of click
Not the most cross browser solution, but probably one of the shortest:
$('.employee_details').click(function() {
var params = this.href.split('?').pop().split(/\?|&/).reduce(function(prev, curr) {
var p = curr.split('=');
prev[p[0]] = p[1];
return prev;
}, {});
console.log(params);
});
Output:
Object {name: "user1", id: "123"}
If you need IE7-8 support this solution will not work, as there is not Array.reduce.
$(function () {
$('.employee_details').click(function () {
var query = $(this).attr('href').split('?')[1];
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
var varName = decodeURIComponent(pair[0]);
var varValue = decodeURIComponent(pair[1]);
if (varName == "name") {
alert("name = " + varValue);
} else if (varName == "id") {
alert("id = " + varValue);
}
}
});
});
It's not very elegant, but here it is!
var results = new Array();
var ref_array = $(".employee_details").attr("href").split('?');
if(ref_array && ref_array.length > 1) {
var query_array = ref_array[1].split('&');
if(query_array && query_array.length > 0) {
for(var i = 0;i < query_array.length; i++) {
results.push(query_array[i].split('=')[1]);
}
}
}
In results has the values. This should work for other kinds of url querys.
It's so simple
// function to parse url string
function getParam(url) {
var vars = [],hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
// your code
$(function () {
$('.employee_details').click(function (e) {
e.preventDefault();
var qs = getParam($(this).attr('href'));
alert(qs["name"]);// user1
var status_id = $(this).attr('href').split('name');
});
});
Hi I am using an ajax call to a function called build_Array. This function should break up myString which is "Call 1-877-968-7762 to initiate your leave.,1,0,through;You are eligible to receive 50% pay.,1,365,through;Your leave will be unpaid.,1,0,After;"
into sections divided by the commas into a 2d array. But it is not working. It says all of the values for the array are undefined. Here is where I call the function inside the ajax... (It works in the jsfiddle http://jsfiddle.net/ChaZz/3/)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var myString = request.responseText;
myString = build_Array(myString);
document.getElementById('ajax').innerHTML = myString;
}
}
And here is the function build_Array...
function build_Array (myString) {
var mySplitResult = myString.split(';');
var myArray = new Array(mySplitResult.length);
//may need to get rid of -1
for(var i = 0; i < mySplitResult.length -1; i++){
myArray[i] = new Array(4);
var mySplitResult2 = mySplitResult[i].split(',');
for(var z = 0; z < mySplitResult2.length; z++) {
myArray[i][z] = mySplitResult2[z];
}
}
var final_message = myArray[1][1];
return final_message;
}
http://jsfiddle.net/ChaZz/5/
var myString = "Call 1-877-968-7762 to initiate your leave.,-30,0,through;You are eligible to receive 50% pay.,0,365,through;Your leave will be unpaid.,365,0,After;";
function build_Array (myString) {
var mySplitResult = myString.split(';');
var myArray = [];
for(var i = 0; i < mySplitResult.length; i++){
myArray[i] = [];
var mySplitResult2 = mySplitResult[i].split(',');
for(var z = 0; z < mySplitResult2.length; z++) {
myArray[i][z] = mySplitResult2[z];
}
}
var final_message = myArray[1][1];
return final_message;
}
console.log(build_Array(myString)); // 0
There's no need for the loop to copy from mySplitArray2 to myArray, just assign the array returned by split directly to that element of the new array. And array.push can be used to build up an array incrementally.
function build_Array (myString) {
var myArray = [];
for (substring in myString.split(';')){
myArray.push(substring.split(','));
}
var final_message = myArray[1][1];
return final_message;
}
I was trying to make a JSON Object from a String URL without success
i have this:
var URL = "http://localhost/index.php?module=search¶m1=4";
i need this:
var dir = index.php;
var result = {
module:'search',
param1:4
};
Can anyone help me with the code?
It's not entirely correct to post a link here, but in this case what OP needed is just some library to parse urls.
And here it is: http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
This function can parse variables AND arrays from a string URL:
function url2json(url) {
var obj={};
function arr_vals(arr){
if (arr.indexOf(',') > 1){
var vals = arr.slice(1, -1).split(',');
var arr = [];
for (var i = 0; i < vals.length; i++)
arr[i]=vals[i];
return arr;
}
else
return arr.slice(1, -1);
}
function eval_var(avar){
if (avar[1].indexOf('[') == 0)
obj[avar[0]] = arr_vals(avar[1]);
else
obj[avar[0]] = avar[1];
}
if (url.indexOf('?') > -1){
var params = url.split('?')[1];
if(params.indexOf('&') > 2){
var vars = params.split('&');
for (var i in vars)
eval_var(vars[i].split('='));
}
else
eval_var(params.split('='));
}
return obj;
}
In your case:
obj = url2json("http://localhost/index.php?module=search¶m1=4");
console.log(obj.module);
console.log(obj.param1);
Gives:
"search"
"4"
If you want to convert "4" to an integer you have to do it manually.
This simple javascript does it
url = "http://localhost/index.php?module=search¶m1=4";
var parameters = url.split("?");
var string_to_be_parsed = parameters[1];
var param_pair_string = string_to_be_parsed.split("&");
alert(param_pair_string.length);
var i = 0;
var json_string = "{"
for(;i<param_pair_string.length;i++){
var pair = param_pair_string[i].split("=");
if(i < param_pair_string.length - 1 )
json_string += pair[0] + ":'" + pair[1] + "',";
else
json_string += pair[0] + ":'" + pair[1] + "'";
}
json_string += "}";
alert(json_string);