Drop down menu on change do jquery function and sql query - php

I am trying to get a sql query to run on drop down menu selection. Here is what I have so far:
<script>
$('#templateid').change(function(DoUpdateOnSelect) {
$.post('page.edit.php?page_id=(-->Need help in getting this id from the page url<--)&template='+this.options[this.selectedIndex].value);
});
</script>
And the drop down:
<select name="templateid" id="templateid" onchange="DoUpdateOnSelect">
<option >Contact</option>
<option >News</option>
<option >Home</option>
</select>
page.edit.php has conditions on it which will run the sql query if it detects the page id and the template in the URL. The template parameter value is grabbed with the jquery (please let me know if that part is set up wrong in the jquery) from the select drop down menu. What I can't figure out is how to grab the page_id parameter from the current url of the page, and insert that into the function so that the page.edit.php?page_id=1&template=Home will be the correctly outputted URL.
Please let me know if you need further information. Thanks in advance.
EDIT: BASED ON ANSWER BELOW:
function querystring(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
$('#templateid').change(function() {
var page_id = querystring('page_id');
var url = '?VIEW=EDITPAGE&linklabel='+page_id+'&template='+(this.options[this.selectedIndex].value);
$.post(url);
});
NO CHANGE IS HAPPENING WHEN I MAKE A SELECTION IN THE DROP DOWN MENU

for getting the page_id from the url you should use a function like
function querystring( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
then you could retrieve it with
var page_id = querystring('page_id');
so, your onchange handler would look something like:
$('#templateid').change(function() {
page_id = querystring('page_id');
var url = 'page.edit.php?page_id='+page_id+'&template='+this.options[this.selectedIndex].value);
$.post(url, function(response){
//your logic here
});
});
oh, and please remove the onchange attribute from the select markup:
<select name="templateid" id="templateid">
<option >Contact</option>
<option >News</option>
<option >Home</option>
</select>

Try using this plugin
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.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;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});

Related

Html select data to PHP

How to get the html Select value in php?
i have made this Select in html
<select id="year" onchange="filterYear();">
</select>
Function to fill in the Select:
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for (var i=5; i<n; i++) {
select.options[select.options.length] = new Option(i+1, i);
}
}
but i need to read the current selected item from the select.
i tried this (javascript):
function filterYear() {
var e = document.getElementById('year');
var value = e.value;
var text = e.options[e.selectedIndex].text;
alert(text);
}
php:
$text = $_GET['text'];
echo $text;
but this did not work
any ideas on how to fix this
i hope someone can push me in the right direction
Without submitting a form and thus reloading the page you can easily send an ajax request that can be processed by the PHP server script. The response from the server is then used in the callback to, usually, perform further DOM manipulation or whatever.
var n = 22;
function selectOne() {
var select = document.getElementById('year');
for( var i = 5; i < n; i++ ) {
select.appendChild( new Option( i + 1, i ) );
}
}
// build the menu
selectOne();
// bind event listener externally
document.getElementById('year').addEventListener('change',e=>{
// a callback to process response from PHP script
let callback=(r)=>{
alert(r)
};
// send a GET ajax request and process response
fetch( 'path/to/php/script.php?text='+e.target.value )
.then(r=>r.text())
.then(callback)
.catch(alert)
})
<select id="year" name='year'>
</select>

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>

Adding 3rd Dynamic drop down menu

I already have this code working for 2 selection menus, now I am trying to add a third but the third is just showing all of the sub-sub categories, rather than being based on the previous selections..
Here is the menu code, I'll just show 1 selection example so it's easier to read.
<select name="category" id="category">
<option value="Sport">Sport</option>
</select>
<select name="sub_category" id="sub_category">
<option value="Golf" class="Sport">Golf</option>
</select>
<select name="subsub_category" id="subsub_category">
<option value="Mens" class="Golf">Mens</option>
<option value="Ladies" class="Golf">Ladies</option>
</select>
JS CODE
<script src="js/menu.js"></script>
<script type="text/javascript">
window.onload = function() {
dynamicSelect("category", "sub_category", "subsub_category");
}
</script>
MENU.JS
function dynamicSelect(id1, id2, id3) {
// Browser and feature tests to see if there is enough W3C DOM support
var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_mac = (agt.indexOf("mac") != -1);
if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) {
// Obtain references to both select boxes
var sel1 = document.getElementById(id1);
var sel2 = document.getElementById(id2);
var sel3 = document.getElementById(id3);
// Clone the dynamic select box
var clone = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions = clone.getElementsByTagName("option");
// Onload init: call a generic function to display the related options in the dynamic select box
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
// Onchange of the main select box: call a generic function to display the related options in the dynamic select box
sel1.onchange = function() {
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
};
}
}
function refreshDynamicSelectOptions(sel1, sel2, sel3 clonedOptions) {
// Delete all options of the dynamic select box
while (sel2.options.length) {
sel2.remove(0);
}
// Create regular expression objects for "select" and the value of the selected option of the main select box as class names
var pattern1 = /( |^)(select)( |$)/;
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
var pattern3 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
// Iterate through all cloned options
for (var i = 0; i < clonedOptions.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2) || clonedOptions[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions[i].cloneNode(true));
sel3.appendChild(clonedOptions[i].cloneNode(true));
}
}
}
Edit: Had to change a lot to get it working, but it is working now, here: http://jsfiddle.net/kvAWf/11/
Here's the resulting Javascript:
var sel1 = document.getElementById('category');
var sel2 = document.getElementById('sub_category');
var sel3 = document.getElementById('subsub_category');
// Clone the dynamic select box
var clone2 = sel2.cloneNode(true);
var clone3 = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions2 = clone2.getElementsByTagName("option");
var clonedOptions3 = clone3.getElementsByTagName("option");
sel1.onchange = function(){
refreshSelect2();
}
sel2.onchange = function(){
refreshSelect3();
}
function refreshSelect2() {
while (sel2.options.length) {
sel2.remove(0);
}
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions2.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions2[i].className.match(pattern2)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions2[i].cloneNode(true));
}
}
refreshSelect3();
}
function refreshSelect3() {
while (sel3.options.length) {
sel3.remove(0);
}
var pattern3 = new RegExp("( |^)(" + sel2.options[sel2.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions3.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions3[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel3.appendChild(clonedOptions3[i].cloneNode(true));
}
}
}

localize dynamic drop down from database using jquery

This is the language select box.
<select name="lang" id="lang" browser="Indicated by the browser">
<option value="en">English</option>
<option value="fr">French</option>
<option value="ch">Chinese</option>
<option value="sp">Spain</option>`enter code here`
</select>
This is script i have written.
<script type="text/javascript">
jQuery(document).ready(function() {
loadBundles('en');
jQuery('#lang').change(function() {
var selection = jQuery('#lang option:selected').val();
loadBundles(selection != 'browser' ? selection : null);
jQuery('#langBrowser').empty();
if(selection == 'browser') { jQuery('#langBrowser').text('('+jQuery.i18n.browserLang()+')');
}
});
});
function loadBundles(lang) {
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language:lang,
callback: function() {
updateExamples();
}
});
}
function updateExamples() {
var ex1 = 'Firstname';
var ex2 = 'Lastname';
var ex3 = 'Youremail';
var ex4 = 'Reenteremail';
var ex5 = 'Newpassword';
var ex6 = 'Dateofbirth';
var ex7 = 'Signup';
var ex8 = 'Itsfreeandalwayswillbe';
var ex9 = 'Birthlabel';
var ex10 = 'Termslabel';
var ex11 = 'Summarylabel';
var ex12 = 'PersonalLabel';
var ex13 = 'Interestlabel';
var ex14 = 'Addlabel';
var ex15 = 'Editlabel';
var ex16 = 'Deletelabel';
var spreadsheet_label = 'Spreadsheetlabel';
var invite_google_label = 'Invitegooglelabel';
var invite_facebook_label = 'Invitefacebooklabel';
var upload_label = 'Uploadlabel';
var subBut='Submit';
var dialogTitle = 'DTitle';
jQuery("#first_name_label").text(eval(ex1));
jQuery("#first_name_label1").text(eval(ex1));
jQuery("#last_name_label").text(eval(ex2));
jQuery("#last_name_label1").text(eval(ex2));
jQuery("#email_label").text(eval(ex3));
jQuery("#email_label1").text(eval(ex3));
jQuery("#reenter_email_label").text(eval(ex4));
jQuery("#new_password_label").text(eval(ex5));
jQuery("#date_of_birth_label").text(eval(ex6));
jQuery("#date_of_birth_label1").text(eval(ex6));
jQuery("#sign_up").text(eval(ex7));
jQuery("#label1").text(eval(ex8));
jQuery("#button").val(eval(ex7));
jQuery("#birth_label").text(eval(ex9));
jQuery("#terms_label").text(eval(ex10));
jQuery("#summary_label").text(eval(ex11));
jQuery("#personal_label").text(eval(ex12));
jQuery("#interest_label").text(eval(ex13));
jQuery("#add_label").text(eval(ex14));
jQuery("#edit_label").text(eval(ex15));
jQuery("#delete_label").text(eval(ex16));
jQuery("#spreadsheet_label").text(eval(spreadsheet_label));
jQuery("#invite_google_label").text(eval(invite_google_label));
jQuery("#invite_facebook_label").text(eval(invite_facebook_label));
jQuery("#upload_label").val(eval(upload_label));
jQuery("#submit_button").val(eval(subBut));
jQuery("#ui-dialog-title-dialog").text(eval(dialogTitle));
}
</script>
Everything is working fine for the labels. But in the case of dynamic drop down i got problem. How to localize the dynamic drop down data when the user selected the language.
The data in the drop down is coming from the database.
I have a language select drop down box, after selecting one language from dropdown list am able to change the text filed names and all other text in the language that is selected.
At the same time i have another dropdown, in that data is generated dynamically form the database. After the user selecting the language from dropdown list i have to change the data in this drop down list also. please suggest me if u have any idea.
Thank you.
I suggest you to use ajax for this issue.
You can bind ajax to first drop down and then fill secound dropdown by data which you get from back-end.
You can do something like this :
<select name='lang'>
<option value='eng'>Eng</option>
<option value='french'>French</option>
</select>
<!-- below div is another div whose data changes as per the language selected -->
<div id="another_div"></div>​
JS:
$("select[name='lang']").live({
change: function(e){
var selected_lang = $("select[name='lang'] option:selected").html();
data = {}
data['selected_lang'] = selected_lang;
$.ajax({
url: "required url",
data: data,
success: function(res){
$("#another_div").text(res); // if result is a direct text sent from server
// or
$("#another_div").text(res.content); //if result is an object with the required content present in the key 'content'
},
error: function(err){
alert("error occured");
}
});
}
});​
I would use one of the many Cascading jQuery Dropdowns:
http://www.ryanmwright.com/2010/10/13/cascading-drop-down-in-jquery/

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