I'm returning an array. I don't want to ahve same elements. So how I make a if control?
$.each(data, function(v, k) {
if ( ) {
// İşlem
}
});
headers.forEach(function (header, i) {
if ( ) { // controle ???
}
});
I don't want another same element in array? .
try the following:
var result = []; // result array without duplicate
$.each(data, function(v, k) {
if ($.inArray(k, result) == -1) result.push(k);
});
Try the following function to get distinct elements in an array:
function getDistinctArray(arr) {
var compareArray = new Array();
if (arr.length > 1) {
for (i = 0;i < arr.length;i++) {
if (compareArray.indexOf(arr[i]) == -1) {
compareArray.push(arr[i]);
}
}
}
return compareArray;
}
You can pass the final array to this function before returning the array.
Related
I am using Laravel 4.1 and created a global filter which redirects to a particular page if any of the following value is null.
Name
email
DOB
Religion
Caste
In the above values Caste is populated dynamically. When the religion value is changed. Everything was working fine With the below code in filter.php:
if (is_null(value->name)) {
return Redirect::to('confirm');
}
if (is_null(value->email)) {
return Redirect::to('confirm');
}
if (is_null($value->dob) {
return Redirect::to('confirm');
}
But when I added Religion or caste or both. The jQuery in the page crashes that is the dropdown isn't populating properly and the entire browser hangs.
if (is_null(value->name)) {
return Redirect::to('confirm');
}
if (is_null(value->email)) {
return Redirect::to('confirm');
}
if (is_null($value->dob) {
return Redirect::to('confirm');
}
if (is_null($value->religion) {
return Redirect::to('confirm');
}
if (is_null($value->caste) {
return Redirect::to('confirm');
}
I don't why it is happening; the first three work completely fine.
jQuery:
var Religion = '#Religion' ;
var Caste = '#Caste' ;
var caste = new Array();
var usr ;
$(function () {
$.ajaxSetup({
async: false
});
usr = getUser();
if(!$.isEmptyObject(usr))
{
var data = getCasteForReligion(usr.religionid) ;
if (data != null) {
// alert(data);
caste = new Array();
for (var i = 0; i < data.length; i++) {
caste.push(data[i]);
}
loadCastes(caste);
}
if(user.casteid != null)
{
$(Caste).val(usr.casteid).trigger('list:updated');
}
}
$(Religion).change(function () {
if ($(Religion).val() != "") {
var data = getCasteForReligion($(Religion).val());
if (data != null) {
// alert(data);
caste = new Array();
for (var i = 0; i < data.length; i++) {
caste.push(data[i]);
}
loadCastes(caste);
}
}
else {
}
});
});
function getCasteForReligion(religionid) {
var result;
$.get('/getCastes',
{ religionId : religionid },
function(data) {
result = data;
});
return result;
}
function getUser() {
var result;
$.get( '/User',
{ },
function(data) {
result = data;
});
return result;
}
//Generate Products variant for Indent
function loadCastes(castlst) {
$(Caste).find('option').remove();
$(Caste).val('').trigger('list:updated');
$(Caste).append(new Option("--Select--", "")).trigger('list:updated');
for (var i = 0; i < castlst.length; i++) {
$(Caste).append(new Option(castlst[i].name, castlst[i].id)).trigger('list:updated');
}
}
I got a script that:
reads urls from a txt file
does some calculations
inserts results into a table
I want to replace txt file with php array. Heres my current code:
<script type="text/javascript">
$.get("imones.txt", function (data) {
var array = data.split(/\r\n|\r|\n/);
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
var beforeTimes = [];
$('#frame_id').on('load', function () {
beforeTimes.push(beforeLoad); /
loadTimes.push((new Date()).getTime());
$('#frame_id').attr('src', array.shift());
try {
$.each(loadTimes, function (index, value) {
var result = (value - beforeTimes[index]) / 1000;
if (result < 0) {
result = result * (-1);
}
$("#loadingtime" + [index]).html(result);
beforeLoad = value;
});
} catch(ex) {}
}).attr('src', array.shift());
</script>
It reads from imones.txt, then inserts each url into a frame, does some calculations, and then inserts results into #loadingtime div. I want to replace imones.txt with a php array. Also i would like the output to be stored in another php array instead of storing it in a div. Can someone help me with this?
Try something like this:
<?php
$str = implode(',',$yourPhpArr);
?>
<script type="text/javascript">
var urls = "<?=$str?>";
var array = urls.split(/,/);
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
var beforeTimes = [];
$('#frame_id').on('load', function () {
beforeTimes.push(beforeLoad); /
loadTimes.push((new Date()).getTime());
$('#frame_id').attr('src', array.shift());
try {
$.each(loadTimes, function (index, value) {
var result = (value - beforeTimes[index]) / 1000;
if (result < 0) {
result = result * (-1);
}
$("#loadingtime" + [index]).html(result);
beforeLoad = value;
});
} catch(ex) {}
}).attr('src', array.shift());
</script>
Let a php file echo your array:
echo Array(1,2,3,4,5);
your html/javascript:
$.get("yourphp.php", function (data) {
var array = data.split(/\r\n|\r|\n/);
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
var beforeTimes = [];
$('#frame_id').on('load', function () {
beforeTimes.push(beforeLoad); /
loadTimes.push((new Date()).getTime());
$('#frame_id').attr('src', array.shift());
try {
$.each(loadTimes, function (index, value) {
var result = (value - beforeTimes[index]) / 1000;
if (result < 0) {
result = result * (-1);
}
$("#loadingtime" + [index]).html(result);
beforeLoad = value;
});
} catch(ex) {}
}).attr('src', array.shift());
</script>
I'm a newbie in javascript, so i need all your help.
So basically i'm trying to do ondrop function(validate), so when I drop something for the first time, the validate function will run and drop the div value from the php. But for the second time and so on, if I dropped the same div value I want it to alert duplicate and remove that div element(the duplicate), but I'm unsuccessfull in detecting the duplicate div.
Can anyone tell me whats wrong with my code?
I have a javascript, php, and html like this:
<script type="text/javascript">
function dragIt(target, e) {
e.dataTransfer.setData('div', target.id);
return false;
}
function validate(target, e){
var id = e.dataTransfer.getData('div');
var clone = document.getElementById(id).cloneNode(true);
var allValues = [];
for (i=0; i<clone.length; i++)
{
if (clone[i].value != "")
{
allValues[i] = clone[i].value.toLowerCase();
}
}
allValues.sort();
var uniqueValues = [];
var idx = 0;
var prevValue = allValues[0];
var currValue = allValues[0];
for (i=0; i<allValues.length; i++)
{
currValue = allValues[i];
if (currValue != prevValue){idx++;}
uniqueValues[idx] = currValue;
prevValue = currValue;
}
if (uniqueValues.length != allValues.length)
{
e.preventDefault();
clone.parentNode.removeChild(clone);
alert('Cannot submit duplicate entries');
return false;
}
else {
alert(clone.id);
e.preventDefault();
target.appendChild(clone);
return true;
}
}
I have a problem regarding on how to get the value of the array variable passed by .post in jquery into my php page
this is my jquery code:
minDate = [];
hoursWork = [];
empId = [];
$('.minDate').each(function() {
minDate.push($(this).val());
});
$('.hoursWork').each(function() {
hoursWork.push($(this).val());
});
$('.empId').each(function() {
empId.push($(this).val());
});
$.post('rtInsert.php', { minDate: minDate, hoursWork: hoursWork, empId: empId }, function(data) {
alert(data);
});
How can I get the passed data in my rtInsert.php
i tried
$minDate = $_POST['minDate'];
$empId = $_POST['empId'];
$workHours = $_POST['hoursWork'];
now how will i get the individual value of the array because all the 3 variables is an array
All I know is a single array using foreach() but
what if there are 3 arrays passed
Is there any idea how I can get it or how can I passed into single array.
Thanks in Advance.
You can use the JSON.stringify(data); to turn them into JSON and prase it on the server side as this; $data = json_decode($json);.
Your code will then become this:
var minDate = [];
var hoursWork = [];
var empId = [];
$('.minDate').each(function() {
minDate.push($(this).val());
});
$('.hoursWork').each(function() {
hoursWork.push($(this).val());
});
$('.empId').each(function() {
empId.push($(this).val());
});
$.post('rtInsert.php', { minDate: JSON.stringify(minDate), hoursWork: JSON.stringify(hoursWork), empId: JSON.stringify(empId) }, function(data) {
alert(data);
});
And your server side ccode:
<?php
$mindate = json_decode($_POST['minDate']);
$hourswork = json_decode($_POST['hoursWork']);
$empid = json_decode($_POST['empId']);
foreach($mindate as $k=>$val)
{
$date = $val;
$work =$hourswork[$k];
$id =$empid[$k];
//...
}
?>
Is there a foreach code in JQuery as in PHP?
I have a code in php,like
<?php foreach ($viewfields as $viewfield): ?>
if ("<?php echo $viewfield['Attribute']['required'];?>" == 'true') {
$("<span class='req'><em> * </em></span>").appendTo("#fb_contentarea_col1down21 #label<?php echo $viewfield['Attribute']['sequence_no']?>");
}
if (<?=$viewfield['Attribute']['type'];?> == 'text' || <?=$viewfield['Attribute']['type'];?> == 'date' || <?=$viewfield['Attribute']['type'];?> == 'number') {
$("<input id=input<?=$viewfield['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
else if (<?=$viewfield['Attribute']['type'];?> == 'textarea') {
$("<textarea style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> id=input<?=$viewfield['Attribute']['sequence_no'];?>></textarea><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
<?php endforeach; ?>
Is there any equivalent of foreach in Jquery? How can I accomplish this same functioality in jQuery?
EDIT 1:
I thought it worked but I get an error. The code and the error message is given below.
for (<?=$viewfield;?> in <?=$viewfields;?>) {
if ("<?=$viewfield['Attribute']['required'];?>" == 'true') {
$("<span class='req'><em> * </em></span>").appendTo("#fb_contentarea_col1down21 #label<?php echo $viewfield['Attribute']['sequence_no']?>");
}
if (<?=$viewfield['Attribute']['type'];?> == 'text' || <?=$viewfield['Attribute']['type'];?> == 'date' || <?=$viewfield['Attribute']['type'];?> == 'number') {
$("<input id=input<?=$viewfield['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
else if (<?=$viewfield['Attribute']['type'];?> == 'textarea') {
$("<textarea style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> id=input<?=$viewfield['Attribute']['sequence_no'];?>></textarea><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
}
Error message:
syntax error
for( in Array)
Can someone help me..
The $.each function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = [ "one", "two", "three", "four", "five" ];
$.each(arr, function(index, value) {
// work with value
});
Maybe is useful to know, if you want to break the loop, you can do it with return false; or if you want to skip only one iteration (continue), you return true;
If you want to iterate an object, I would recommend the JavaScript variant:
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
You can also iterate objects in jQuery like this:
Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.
$.each(obj, function (key, value) {
alert(key + ': ' + value);
});
To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):
for (var i = 0, l = arr.length; i < l; i++) {
alert(i + ': ' + arr[i]);
}
To do it in jQuery, you can do it like this:
$.each(arr, function (index, value) {
alert(index + ': ' + value);
});
There is jQuery.each.
Javascript supports the for(data in data_array) syntax. jQuery also has a $.each function (as already mentioned)
Jquery operating on selectors:
$('a').each(function() {
$(this).click(function(e) {
e.preventDefault()
var href = this.href;
open(href);
});
// operate on the anchor node.
});
jQuery direct $.each:
var a = ['one', 'two'];
$.each(a, function() {
alert(this)
});
JS: Vanilla for loop
for ( var i = 0, len = 10; i<l; ++i ) {
alert(i)
}
JS #2: vanilla for
var humanLimbs = ['arms', 'legs'];
for ( var limb in humanLimbs ) {
if ( humanLimbs.hasOwnProperty(limb) ) {
alert( limb )
}
}
Js #3: infinite loop
for (;;) { alert(1) } // dont try this :p