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>
Related
My checkboxes are empty when page refreshes after submit. I would like to keep them checked. How can I do that in jquery?
Here is my jquery code.
$(document).ready(function () {
$(':checkbox.selectall').on('click', function () {
$(':checkbox[id="' + $(this).data('checkbox-name') + '"]').prop("checked", $(this).prop("checked"));
$( "#frm1" ).submit();
});
$(':checkbox.checkme').on('click', function () {
var _selectall = $(this).prop("checked");
if (_selectall) {
$(':checkbox[name="' + $(this).attr('name') + '"]').each(function (i) {
_selectall = $(this).prop("checked");
return _selectall;
});
}
$(':checkbox[name="' + $(this).data('select-all') + '"]').prop("checked", _selectall);
$( "#frm1" ).submit();
});
});
My html is as follows...
<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'/></label></a></li>
<input type='checkbox' name='subcatinput[]' value='$test[id]' id='$test[category]'
class='checkme' data-select-all='sa_subcatinput[]'/>
You cannot do this unless you send a value back to your page which indicates the checkbox to be checked.Since you said the page refreshes, a server communication is happened. So you may use ajax to keep the check box checked
Pass a querystring parameter of the id or number or value or whatever of the checked checkbox.
request the parameter using server side code or a client-side javascript using a get parameter function (there on many on this site).
rechecked the box using your custom function and the value returned.
$('#ckeckbox1').val(unescape(getParam(document.URL,'checkbox1')));
function getParam(url,name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if( results == null )
return "";
else
return results[1];
}
function removeParameter(url, parameter) {
var urlparts= url.split('?');
if (urlparts.length>=2) {
var urlBase=urlparts.shift(); //get first part, and remove from array
var queryString=urlparts.join("?"); //join it back up
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;) //reverse iteration as may be destructive
if (pars[i].lastIndexOf(prefix, 0)!==-1) //idiom for string.startsWith
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
}
return url;
}
I was able to get the code working with php. Here is the code I inserted in the input to make it work.
echo"<input type='checkbox' id='selectall' name='sa_subcatinput[]' value='$row[id]'
data-checkbox-name='$row[id]' class='selectall'";
if (isset($_POST['sa_subcatinput'])) {
if (in_array($row['id'], $_POST['sa_subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>
echo"<input type='checkbox' name='subcatinput[]' value='$test[id]'
id='$test[category]' class='checkme' data-select-all='sa_subcatinput[]'";
if (isset($_POST['subcatinput'])) {
if (in_array($test['id'], $_POST['subcatinput'])) {
echo"checked='checked'";
}
}
echo"/>
I'm using the following to auto refresh the contents of a div.
$(document).ready(function() {
$("#log").load("test.php?q=" + $('#sq').val());
var refreshId = setInterval(function() {
$("#log").load("test.php?q=" + $('#sq').val());
}, 1000);
$.ajaxSetup({ cache: false });
});
This seems to work fine. I have a text field with the name 'sq' and anything entered in there is searched for by test.php.
My page also has 2 other form fields.
A checkbox and another text field. The checkbox has the id 'chk' and the text field 'txt'.
What I would like to do is change the URL being used by load() if the checkbox is ticked and a value is entered in the text field. Obviously this will also need to include 'sq'.
Can some one point me in the right direction.
The URL with out the check box being ticked is : ( is it is now )
test.php?q=VALUE_FROM_sq
With the checkbox ticked it needs to be :
test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq
Then test.php can use $_REQUEST to get the values passed.
My network box only supports php4 so that does limit me some..
Can some one point me in the right direction. Thanks
Just add some logic in the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
var refreshId = setInterval(LoadLog, 1000);
LoadLog();
});
function LoadLog() {
var sq = $('#sq').val();
var text = $("#txt").val();
var url = "test.php?q=" + encodeURIComponent(sq);
if ($("#chk").is(":checked") && text.length > 0)
url += "&s=1&txt=" + encodeURIComponent(text);
$("#log").load(url);
}
You could save the URL in a separate variable and update it on the changed event of the checkbox.
var url = "test.php?q=VALUE_FROM_sq"
$(document.body).on('change', '#chk', function (event) {
if ($(this).is(':checked')) {
url = "test.php?s=1&txt=VALUE_FROM_txt&q=VALUE_FROM_sq"
} else {
url = "test.php?q=VALUE_FROM_sq"
}
}
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/
I have created some dynamic text boxes and values according to the no. of cart items selected by a user. The no. of cart items are stored in a cookie and I am trying to do the following:
1) Get the no. of cart items from the cookie named cartcounter
2) Create 'cartcounter' no of text boxes with name itemkey_skey where itemkey is the hash key of each items in user cart.
3) Submit the form
4) Get the keys of the selected items in php
Now I can create cartcounter, the number of text boxes with different values.
But the problem is that I can get only the first text box value in $_POST in PHP. I would like to get all the values of the dynamically created form elements.
Code:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
$("#frm").submit();
}
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
}
});
I have solved it. The problem was that I was calling the submit function inside the loop. I have solved it by doing:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
}
$("#frm").submit();
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.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];
}
});