how to remove duplicate div ondrop - php

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;
}
}

Related

How to add order list into jQuery Nestable JSON serialize

I've using jQuery Nestable menu from http://robertan.com/blog/?p=108
But I want make an enhancement on the JSON serialize from
[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5}]}]
become
[{"id":1,"order":1},{"id":2,"order":2},{"id":3,"order":3,"children":[{"id":4,"order":1},{"id":5,"order":2}]}]
Any suggestion?
I don't know javascript well,but PHP is OK~
This gives your expected result, find the inline comments for more details
<script>
$(document).ready(function(){
//create the json object
var menu = $.parseJSON('[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5}]}]');
//final result variable menu
var final_menu = [];
//initial variable
var i = 1;
//process each element
$.each(menu, function(index, value){
//local variable
var item = {};
//type of validation
if(typeof(value.children) !== 'undefined')
{
var j = 1;
item['id'] = value.id;
item['order'] = i;
item['children'] = [];
//process each children
$.each(value.children, function(index1, value1){
var child = {};
child['id'] = value1.id;
child['order'] = j;
item['children'].push(child);
j++;
});
}
else
{
item['id'] = value.id;
item['order'] = i;
}
//create the final menu
final_menu.push(item);
i++;
});
console.log(final_menu);
});
</script>

loading xml from a database to be used in multiple functions

I have a database where i'm using php to randomize the information by ID and send it out via xml. My issue is that I only want to grab the xml once and store it for use in at least 2 functions... one function that runs onload to grab the first line of xml, another that will run every time a button is pressed to access the next line of xml until the end. My 2 functions are loadfirst() and loadnext(). loadfirst() works perfectly, but I'm not sure how to pass the xml data to loadnext(). Right now I'm just using loadfirst() on pageload and loadfirst() on button press, but i end up creating new xml from the database each time which causes randomization issues and is incredibly inefficient. Any help would be appreciated.
var places;
var i = 0;
function loadXML(){
downloadUrl("places.php", function(data){
places = data.responseXML;
getFeatured(i);
});
}
function getFeatured(index){
var id = places[index].getAttribute("id");
var name = places[index].getAttribute("name");
var location = places[index].getAttribute("location");
var imgpath = places[index].getAttribute("imgpath");
var tags = places[index].getAttribute("tags");
}
function getPrev() {
i--;
getFeatured(i);
}
function getNext() {
i++;
getFeatured(i);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
loadnext() will be very similar to loadfirst(), I'm just running into issues with passing the xml data so that i can use it without having to access the database again. Thanks.
Set your xml and i in public scope. Then all you have to do is increment/decrement i and re-read data from XML. Something like this:
var xml;
var xml_idx = 0; // replaces your i counter
function loadXML() {
downloadUrl ("places.php", function(data) {
xml = data.responseXML;
)};
}
function loadItem(index) {
var id = xml[index].getAttribute("id");
var name = xml[index].getAttribute("name");
var location = xml[index].getAttribute("location");
var imgpath = xml[index].getAttribute("imgpath");
var tags = xml[index].getAttribute("tags");
// do something with this data
}
function loadCurrentItem() {
loadItem(xml_idx);
}
function loadNextItem() {
xml_idx++;
loadItem(xml_idx);
}
function loadPreviousItem() {
xml_idx--;
loadItem(xml_idx);
}
// usage
loadXML(); // do this first to populate xml variable
loadItem(xml_idx); // loads first item (i=0)
loadCurrentItem(); // loads i=0
loadNextItem(); // loads i=1
loadNextItem(); // loads i=2
loadPreviousItem(); // loads i=1
If you really want to get fancy (and keep the global namespace cleaner), you could easily make this into a class.
Use global variables (items - items array, iterator - counter) to store data available for all functions.
Try something like this:
items = false;
iterator = 0;
function loadfirst(){
downloadUrl ("places.php", function(data) {
var i = 0;
var xml = data.responseXML;
var places = xml.documentElement.getElementsByTagName("place");
var id = places[i].getAttribute("id");
var name = places[i].getAttribute("name");
var location = places[i].getAttribute("location");
var imgpath = places[i].getAttribute("imgpath");
var tags = places[i].getAttribute("tags");
items = places;
iterator++;
)};
}
function loadnext(){
var i = iterator;
var id = items[i].getAttribute("id");
var name = items[i].getAttribute("name");
var location = items[i].getAttribute("location");
var imgpath = items[i].getAttribute("imgpath");
var tags = items[i].getAttribute("tags");
iterator++;
}
You should wrap all this into a single object to control scope and data state. (Untested code below, which should just illustrate a possible pattern and interface to use.)
function PlacesScroller(url, callback) {
this.url = url;
this.data = null;
this._index = null;
this.length = 0;
var self = this;
downloadURL(this.url, function(result, status) {
if (Math.floor(status/100)===2) {
self.setData(result);
}
if (callback) {
callback(self, result);
}
});
}
PlacesScroller.prototype.setData(xmldom) {
this._index = 0;
// this may require changing; it depends on your xml structure
this.data = [];
var places = xmldom.getElementsByTagName('place');
for (var i=0; i<places.length; i++) {
this.data.push({
id : places[i].getAttribute('id'),
name : places[i].getAttribute('name')
// etc
});
}
}
PlacesScroller.prototype.getPlaceByIndex = function(index) {
if (this.data) {
return this.data[index];
} else {
return null;
}
}
PlacesScroller.prototype.getCurrentFeature = function() {
return this.getPlaceByIndex(this._index);
}
PlacesScroller.prototype.addToIndex(i) {
// This sets the index forward or back
// being careful not to fall off the end of the data
// You can change this to (e.g.) cycle instead
if (this.data===null) {
return null;
}
var newi = i+this._index;
newi = Math.min(newi, this.data.length);
newi = Math.max(0, newi);
this._index = newi;
return this._index;
}
PlacesScroller.prototype.getNextFeature = function() {
this.addToIndex(1);
return this.getCurrentFeature();
}
PlacesScroller.prototype.getPreviousFeature = function() {
this.addToIndex(-1);
return this.getCurrentFeature();
}
Then initialize it and use it like so:
var scroller = new PlacesScroller('places.php', function(scrollerobject, xmlresult){
// put any initialization code for your HTML here, so it can build after
// the scrollerobject gets its data.
// You can also register event handlers here
myNextButton.onclick = function(e){
var placedata = scrollerobject.getNextFeature();
myPictureDisplayingThing.update(placedata);
}
// etc
});

Javascript events - send values to database

I am having trouble sending data to the database. The values are being sent, but they are all going into the first drop zone field. And I need each dropzone value to go into the correct field in the database.
I've tried putting in different listeners & if statements in the javascript but it won't work for me.
the html:
<ul id="images">
<li><a id="img1" draggable="true"><img src="images/1.jpg"></a></li>
<li><a id="img2" draggable="true"><img src="images/2.jpg"></a></li>
<li><a id="img3" draggable="true"><img src="images/3.jpg"></a></li>
</ul>
//dropzones
<div class="drop_zones">
<div class="drop_zone" id="drop_zone1" droppable="true">
</div>
<div class="drop_zone" id="drop_zone2" droppable="true">
</div>
<div class="drop_zone" id="drop_zone3" droppable="true">
</div>
</div>
<button id = "post" onClick="postdb();">Post info</button>
the javascript:
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () {
return fn.call(el, window.event);
});
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
var dragItems;
updateDataTransfer();
var dropAreas = document.querySelectorAll('[droppable=true]');
function cancel(e) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
function updateDataTransfer() {
dragItems = document.querySelectorAll('[draggable=true]');
for (var i = 0; i < dragItems.length; i++) {
addEvent(dragItems[i], 'dragstart', function (event) {
event.dataTransfer.setData('obj_id', this.id);
return false;
});
}
}
addEvent(dropAreas, 'dragover', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#000";
return false;
});
addEvent(dropAreas, 'dragleave', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#ccc";
return false;
});
addEvent(dropAreas, 'dragenter', cancel);
// drop event handler
addEvent(dropAreas, 'drop', function (event) {
if (event.preventDefault)
event.preventDefault();
// get dropped object
var iObj = event.dataTransfer.getData('obj_id');
var oldObj = document.getElementById(iObj);
// get its image src
var oldSrc = oldObj.childNodes[0].src;
oldObj.className += 'hidden';
var oldThis = this;
setTimeout(function () {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
function postdb(){
if (document.querySelectorAll('[droppable=true]')){
var dropDetails = oldThis.id + '=' + iObj;
$.post("a-2.php", dropDetails);
}
oldThis.style.borderColor = "#ccc";
}, 500);
return false;
});
and my php:
$sql="INSERT INTO table_answers (drop_zone1, drop_zone2, drop_zone3) VALUES ('$_POST[drop_zone1]','$_POST[drop_zone2]','$_POST[drop_zone3]')";
Any idea please?
var u = $('drop_zone1');
if(u){
$.post("post.php", y);
};
(I'm assuming this is jQuery.)
Add the # to the beginning of the selector: $('#drop_zone1');.
The jQuery resultset always evaluates to a truthy value. It's not clear to me what condition you're trying to validate here...
In the PHP code, you're creating the query in $sql2 in the first if, as opposed to $sql in the other two.
Edit - now that we know what you're trying to do in setTimeout, this simplified function should work:
setTimeout(function() {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
/*
this part has been removed, see edit below
var dropDetails = oldThis.id + '=' + iObj;
// now dropDetails should look something like "drop_zone1=img1"
$.post("post.php", dropDetails);
*/
oldThis.style.borderColor = "#ccc";
}, 500);
One more edit, to submit all the dropped elements at once:
function postdb() {
var postDetails = {};
var dropZones = document.querySelectorAll('[droppable=true]');
var allZonesDropped = true;
for(var ix = 0; ix < dropZones.length; ++ix) {
var zone = dropZones[ix];
var dropped = zone.querySelector('[draggable=true]');
if(dropped) {
var dropTag = dropped.id;
postDetails[zone.id] = dropTag;
} else {
allZonesDropped = false;
}
}
if(allZonesDropped) {
$.post("a-2.php", dropDetails);
} else {
alert('Not all targets have elements in them');
}
return false;
});
Just be careful where you place this function - your edited question has it in the middle of the setTimeout call, where it's definitely not going to work.
Regarding your PHP code: You should really learn about PDO or MySQLi and use prepared statements instead of blindly inserting user input into the query. If you care to learn, here is a quite good PDO-related tutorial.

JavaScript DOM Error in Internet Explorer

I'm receiving the following error on this line of code
select.up().appendChild(sw);
With error "SCRIPT438: Object doesn't support property or method 'up' "
This only happens in Internet Explorer... Chrome, Safari, and Firefox all run the code fine. I'm unable to find anything via Google searching for "select.up()". This code isn't my own and I'm not very adept with using DOM in Javascript.
Here is rest of the code:
<?php
$swatches = $this->get_option_swatches();
?>
<script type="text/javascript">
document.observe('dom:loaded', function() {
try {
var swatches = <?php echo Mage::helper('core')->jsonEncode($swatches); ?>;
function find_swatch(key, value) {
for (var i in swatches) {
if (swatches[i].key == key && swatches[i].value == value)
return swatches[i];
}
return null;
}
function has_swatch_key(key) {
for (var i in swatches) {
if (swatches[i].key == key)
return true;
}
return false;
}
function create_swatches(label, select) {
// create swatches div, and append below the <select>
var sw = new Element('div', {'class': 'swatches-container'});
select.up().appendChild(sw);
// store these element to use later for recreate swatches
select.swatchLabel = label;
select.swatchElement = sw;
// hide select
select.setStyle({position: 'absolute', top: '-9999px'})
$A(select.options).each(function(opt, i) {
if (opt.getAttribute('value')) {
var elm;
var key = trim(opt.innerHTML);
// remove price
if (opt.getAttribute('price')) key = trim(key.replace(/\+([^+]+)$/, ''));
var item = find_swatch(label, key);
if (item)
elm = new Element('img', {
src: '<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>swatches/'+item.img,
alt: opt.innerHTML,
title: opt.innerHTML,
'class': 'swatch-img'});
else {
console.debug(label, key, swatches);
elm = new Element('a', {'class': 'swatch-span'});
elm.update(opt.innerHTML);
}
elm.observe('click', function(event) {
select.selectedIndex = i;
fireEvent(select, 'change');
var cur = sw.down('.current');
if (cur) cur.removeClassName('current');
elm.addClassName('current');
});
sw.appendChild(elm);
}
});
}
function recreate_swatches_recursive(select) {
// remove the old swatches
if (select.swatchElement) {
select.up().removeChild(select.swatchElement);
select.swatchElement = null;
}
// create again
if (!select.disabled)
create_swatches(select.swatchLabel, select);
// recursively recreate swatches for the next select
if (select.nextSetting)
recreate_swatches_recursive(select.nextSetting);
}
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
$$('#product-options-wrapper dt').each(function(dt) {
// get custom option's label
var label = '';
$A(dt.down('label').childNodes).each(function(node) {
if (node.nodeType == 3) label += node.nodeValue;
});
label = trim(label);
var dd = dt.next();
var select = dd.down('select');
if (select && has_swatch_key(label)) {
create_swatches(label, select);
// if configurable products, recreate swatches of the next select when the current select change
if (select.hasClassName('super-attribute-select')) {
select.observe('change', function() {
recreate_swatches_recursive(select.nextSetting);
});
}
}
});
}
catch(e) {
alert("Color Swatches javascript error. Please report this error to support#ikova.com. Error:" + e.message);
}
});
</script>
Appreciate any insight anyone could give me!
I'm pretty sure up() is a PrototypeJS method, so i'm pretty sure you would need it to work.
http://prototypejs.org/api/element/up
I m also facing this problem. so, i comment
var sw = new Element('div', {'class': 'swatches-container'});
$(select).up().appendChild(sw);
select.setStyle({position: 'absolute', top: '-9999px'})
lines from function create_swatches
and paste it in function trim(str).
After this i did not error again.

How to operate with onfocus?

I have a textbox.
Now when the page is opened i want the textbox to have a default value.Once he click on the textbox the value should disappear and again when he removes his cursor from the text box ,the old value should come back.
So how do i do this ?
Thanks
Add a specific class to all textboxes on the page that you want to have this functionality.
Then, use this code to apply the functionality to the elements that have the class:
window.onload = function() {
var elements = document.querySelectorAll('.yourClassName');
for(var i = 0, j = elements.length; i < j; i++) {
var element = elements[i];
element.onfocus = function() {
this.value = '';
this.style.color = 'black';
};
element.onblur = function() {
if(this.value == '') {
this.value = this.getAttribute('defaultValue');
this.style.color = 'grey';
}
};
element.onblur();
}
};
​
Working example: http://jsfiddle.net/6TmGA/1/
Can you use jQuery?
If you can there are a lot of plugins that will help with this.
such as;
http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/
<script language="JavaScript">
function setFocus() {
document.getElementById('username').focus();
}
</script>

Categories