How to operate with onfocus? - php

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>

Related

Get index value from dropdown form

I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>

How to Scroll to position of page using get method?

How to Scroll to position of page using get method ?
EG: mysite.com/index.php?positon=1
after load page it's will be Scroll to position id=1 of page
how can i do that ?
You could use this javascript function :
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value) {
vars[key] = value;
});
return vars;
}
For example when your url is : mysite.com/index.php?positon=1
You can get the value by doing : var position = getUrlVars()["position"];
Then to scroll you do :
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
window.scroll(0,findPos(document.getElementById(position)));
You have to use that after the DOM has loaded so write that just after </body> like this :
<script type="text/javascript">
(function() {
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value) {
vars[key] = value;
});
return vars;
}
var position = getUrlVars()["position"];
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
window.scroll(0,findPos(document.getElementById(position)));
})();
</script>
You can then reuse these functions for any variables you want
I can't show you on JSFiddle because the ?position=1 won't work on it
However here is a paste of a fully working html page which I used for testing : http://pastebin.com/tjj4fDK9
Paste it in a html file on your computer, open it with Chrome and add ?position=1 in the URL

how to remove duplicate div ondrop

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

How do I pass a PHP array to a jQuery function?

I have a jQuery function that opens a modal popup and I have in the same file a variable in PHP like $url="iteminfo.php?ID=".$i['itmid'];($i['itmid'] is the id of some products from MySQL). The jQuery function looks like this:
<script type="text/javascript">
$(document).ready(function(Surl) {
var source="iteminfo.php?ID=<?echo $i['itmid']?>";
var width = 920;
var align = "center";
var top = 100;
var padding = 10;
var backgroundColor = "#FFFFFF";
var borderColor = "#000000";
var borderWeight = 4;
var borderRadius = 5;
var fadeOutTime = 300;
var disableColor = "#666666";
var disableOpacity = 40;
var loadingImage = "js/popup/loading.gif";
$(".modal").click(function() {
modalPopup( align,
top,
width,
padding,
disableColor,
disableOpacity,
backgroundColor,
borderColor,
borderWeight,
borderRadius,
fadeOutTime,
source,
loadingImage );
});
$(document).keyup(function(e) {
if (e.keyCode == 27) {
closePopup(fadeOutTime);
}
});
});
</script>
It opens the respective links but the function open all of them like in a loop. How can I pass the $url into the jQuery function to open the respective link for the respective product?
For starters it would look more like this, but without seeing your HTML code its hard to say how you would be pulling out the ID of each different object with an ID.
<script type="text/javascript">
$(document).ready(function(Surl) {
var source="iteminfo.php?ID=";
var width = 920;
var align = "center";
var top = 100;
var padding = 10;
var backgroundColor = "#FFFFFF";
var borderColor = "#000000";
var borderWeight = 4;
var borderRadius = 5;
var fadeOutTime = 300;
var disableColor = "#666666";
var disableOpacity = 40;
var loadingImage = "js/popup/loading.gif";
$(".modal").click(function() {
//get the id of what you're opening on each click event.
var myid = ...
modalPopup( align,
top,
width,
padding,
disableColor,
disableOpacity,
backgroundColor,
borderColor,
borderWeight,
borderRadius,
fadeOutTime,
source + myid,
loadingImage );
});
$(document).keyup(function(e) {
if (e.keyCode == 27) {
closePopup(fadeOutTime);
}
});
});
</script>
Did you said that when you click in the element .modal, the right modal appear with the good content ?
And what do you mean by 'them' in 'the function open all of them' ?
Maybe you should take a look in your 'modalPopup' function.
You can store the corresponding url for every .modal element as an attribute with a php loop which browse your array.

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.

Categories