I'm new to javascript, jquery, and ajax and need help making my code more efficient. I have the following javascript/jquery function that works fine:
<script type="text/javascript">
$(document).ready(function()
{
$("#promo1").change(function() //select menu id that triggers script on change
{
//data here
$.ajax
({
//ajax stuff here
{
//individual values from json array
//set each value textbook value
$("#discprice1").val(disc);
$("#itemprice1").val(total);
$("#tax").val(tax);
$("#grandtotal").val(grand);
}
});
});
});
</script>
I change my original function to this after a suggestion:
<script type="text/javascript">
$(document).ready(function()
{
var setupCalculation = function(index) {
$("#promo" + index).on("change", function() //select menu id that triggers script on change
{
//rest of the function is here....
and change my select to this:
<select name="promo<?php echo $i; ?>" id="promo<?php echo $i; ?>"
onchange="setupCalculation('<?php echo $i; ?>');">
However, it is not working. What am I missing?
However, I need to do the same thing 10 times for 10 different rows of calculations. How can I make it so I can use this function generically and just pass the "id" of the select box to the function and not repeat this code 10 times for each of the selectors, e.g. #promo1, #promo2, #promo3, etc....
I'm assuming I need to add onchange="javascript function here();" to the html code, but I can't get it to work.
Thanks!
This is a case when you should write a little plugin. Take a look how it can look like (I did'nt get what exectly you need but you will grasp the idea):
$.fn.myFirstPlugin = functin() {
return this.each(function() {
// This is currect select box
var $select = $(this);
// Change event
$select.change(function() {
// Do something for this select box; $(this) will point to current select element
$.ajax({ ... })
});
})
};
Then you would use it like:
$('#promo1, #promo2, #promo3').myFirstPlugin();
Instead of using an "onchange" attribute inline, I would use your current approach to wireup the event handler. That way you can define a function setupCalculation that wires up the logic for a given select list.
$(document).ready(function() {
var setupCalculation = function(id) {
$("#" + id).on("change", function() {
// ajax/calculation logic
});
}
setupCalculation("promo1");
setupCalculation("promo2");
// ...etc
});
If the result elements are different (eg discprice2, discprice3, etc), then it may be better to pass an index to the function instead, and hard-code the name part of the ids:
var setupCalculation = function(index) {
$("#promo" + index).on("change", function() {
// ajax stuff
$("#discprice" + index).val(disc);
// etc
});
}
Edit Using the form onchange=setupCalculation(), the function should look like this (no need to wire up the change event):
$(document).ready(function()
{
window.setupCalculation = function(index) {
//rest of the function is here....
sounds like your select boxes look like
<select id="promo1">...</select>
<select id="promo2">...</select>
add a class to each one
<select id="promo1" class="promo">...</select>
<select id="promo2" class="promo">...</select>
so that you can select all the boxes with one simple selector for the change event function:
$(".promo").change(function() {
...
});
You could set up a jQuery function and call it from the selected object:
$.fn.changePromo = function() {
/* return this jQuery object to allow chaining and execute in an 'each()' to allow multiple elements */
return this.each( function() {
$( this ).change( function() {
/* your ajax call here */
} );
} );
}
/* call examples */
$( '#promo1' ).changePromo();
$( '#promo1,#promo2' ).changePromo();
Related
I have the following function, I want to get called everytime, user types something in the typeahead input field.
function getAllActiveUsers() {
var userList = $('#usersTable').jqGrid('getGridParam').userData;
var userNames = {};
if(userList) {
// Return the list of all active users
$(userList).each(function() {
if(this.userStatus != 1) {
// If the user is verified
// Could be active/inactive
userNames.user = this.username;
}
});
}
return JSON.stringify(userNames);
}
HTML:
<div id="the-basics">
<input class="typeahead" type="text" data-provide="typeahead" placeholder="User List">
</div>
I have been browsing through, the examples, but do not understand how to implement this functionality.
Edit:
Why it doesn't work when I initialize as :
$('.typeahead').typeahead({
source : getAllActiveUsers
});
Try this
$(document).ready(function(){
$('.typeahead').keyup(function(){
getAllActiveUsers();
});
});
You can use .keyup jquery function
$( ".typeahead" ).keyup(function() {
getAllActiveUsers();
});
Taken from the reference you gave you can specify the class .typeahead inside the id #the-basics:
$(document).ready(function(){
$('#the-basics .typeahead').typeahead({
//code here;
}
}
Since the page can't be manipulated safely until the document is ready you should be using $(document).ready.
Also, try to use your browser console and check if you can reach $('#the-basics .typeahead')
You can use Jquery Keyup which gets triggered when a key is released.
$( ".typeahead" ).on('keyup',function() {
getAllActiveUsers();
});
if your text box coming dynamically then you should try
$(document).on("keyup", ".typeahead" , function() {
getAllActiveUsers();
});
try this and let us know if its works or not.
It should be possible
var getAllActiveUsers = function(q, cb, cb2) {
// cb for sync, cb2 for async
var userList = $('#usersTable').jqGrid('getGridParam').userData;
var filterted = /* whatever you want to do with q */;
cb(filtered);
};
$('.typeahead').typeahead({
/* Options */
},
{
source : getAllActiveUsers
});
I am trying to display the database table using php. When the page is loaded I need to show all table data and when I select the dropdown select, I neeed to display only data related to it ie.using where condition. I don't need any sql query or php code for it, I just need jquery.
$(document).ready(function()
{
$('#myHref').change(function()
{
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
});
$('#myHref').on('change',function()
{
$('#projectDetail').fadeIn();
});
});
Here when I select drop down menu id="myHref" execute get_projectName.php, but I need to execute get_projectName.php when page is load before select dropdown so I can display all data
Plz Help!!
bt I need to execute get_projectName.php when page is load before select dropdown so i can display all data
So I see you want to initially load execute get_projectName.php once when page loads and also execute it if there are any changes in the dropdown. So you can do like below
$(document).ready(function() {
//make a call initially on page load
var firstOptionValue = $("#myHref option:eq(1)").val() // take first option value as default
$.get('get_projectName.php',{id:firstOptionValue},function(data)
{
$('#projectDetail').html(data);
});
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
});
Refactoring the code, you can just pull out the common logic into a function and call that function by passing the required value, See below
$(document).ready(function() {
//make a call initially on page load
var firstOptionValue = $("#myHref option:eq(1)").val(); // take first option value as default
GetProjectDetails(firstOptionValue);
$('#myHref').change(function(){
var value = $('#myHref').val();
GetProjectDetails(value);
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
function GetProjectDetails(value){
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
}
});
In the above code you are trying to pass the selected id to php file through $.get() when the dropdown is changed. it is fine, if you want to display all the data when page is loaded then you should have another php which returns all the data in db and doesn't take any value. And write the code as below
$(document).ready(function() {
$.get('get_allDataFromDb.php',function(data)
{ $('#projectDetail').html(data);
});
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{ $('#projectDetail').html(data);
});
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
});
function getData(value) {
params = {};
if value
params.id = value;
$.get('get_projectName.php', params, function (data) {
$('#projectDetail').html(data);
});
}
// Get Data onLoad
getData($('#myHref').val());
$('#myHref').on('change',function(){
getData($('#myHref').val());
$('#projectDetail').fadeIn();
});
Looks like your element (e.g. #myHref) don't exist at time when your script . And when you want to show all data on load just call function eg.
function getData(){//ajax here}
getData();
running. Are there any errors? or something that can help?
Try like this
$(document).on("change", "#myHref" , function() {
// Your Code Here
});
let me know in case it still dont work.
Ok , here is my another answer that how you can trigger some event after our document get ready .
hope this will be helpful to you .
<script>
$(document).ready(function(){
//Function for AJAX Call
function GetData(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
//
$('#projectDetail').fadeIn();
// Any other code here you want to write.
});
}
$('#myHref').change();
//OR you can use
$("#myHref").trigger("change");
});
$(document).on("change", "#myHref" , function() {
// Call the function as change evvent is triggered
GetData();
});
</script>
I'm implementing something similar to this in one of my Wordpress metabox. User should be able to add and remove jquery-ui sortable elements and remember the position(order) of the elements exists.
I already know how to remember the position(order) when the elements are resorted by dragging and dropping.
jQuery(document).ready(function () {
jQuery('ul').sortable({
stop: function (event, ui) {
var data = jQuery(this).sortable('toArray');
jQuery('#elements-order').val(data);
}
});
});
This will output an array which contains the order like 1,2,3,5,4 But, when new elements are added or elements are deleted, how to make this code run to remember the order of the new elements.
This is the code I use to Add elements
jQuery(document).ready(function () {;
var wrapperSize = jQuery("#element-area-top").width();
(function () {
jQuery(".add-element").on("click", ".add-item", function () {
var start = jQuery("#sortable"),
selectBoxVal = jQuery("#element-list").val();
var element = null;
element = ('<li></li>');
var newRow = jQuery(element);
jQuery(start).append(newRow);
jQuery("#elements-order").val(jQuery('#elements-order').val() + i+',');
});
})();
This is the code I use to delete elements
jQuery("#sortable").on("click", ".delete", function () {
jQuery(this).parents(/*someelement*/).remove();
});
So, could anyone know how to do this ?
You can get sort order with same logic in add/delete functions as well (just replace this with '#ul').
var data = jQuery('#ul').sortable('toArray');
jQuery("#elements-order").val(data);
Or even better, put above code in a common function and just call common function. Here is updated fiddle demonstrating same.
I have an ajax function that loads the content of 4 checkboxes as follows:
$.ajax({
url : some url..,
dataType : 'json',
success : function(data) {
buildCheckboxes(data);
},
error : function(data) {
do something...
}
});
build checkboxes methods does something like this:
function updateNotificationMethods(items) {
var html = [];
$.each(items, function(i, item) {
htmlBuilder = [];
htmlBuilder.push("<input type='checkbox' class='checkbox-class' name='somename' value='");
htmlBuilder.push(item.id);
htmlBuilder.push("'");
htmlBuilder.push("/> ");
htmlBuilder.push(item.name);
htmlBuilder.push("<br/><br/>")
html.push(htmlBuilder.join(''));
});
$("#div").html(html.join(''));
}
i have also an event binder that should be triggered when checkbox value changes:
$(".checkbox-class").change(function() {
alert("change");
});
it works if i have the checkboxes html in the source (i.e. static) as opposed to the set up i have here, where i dynamically load the data from server.
is there something i can do so that binding take place timely?
peace!
This is because the element is not present when you bind your handler.
Try this:
$( document ).on( 'change', '.checkbox-class', function() {
alert("change");
});
Or if you are using an older version of jQuery (less than 1.7) ...
$( '.checkbox-class' ).live( function() {
alert("change");
});
Checkboxes are not available while you are binding the events. jsfiddle
Assuming that element with id div is present while binding the event.
$("#div").on("change",".checkbox-class",function() {
alert("change");
});
This code:
$(".checkbox-class").change(function() {
alert("change");
});
do not establishes a continuous and on-going rule, instead, this code attaches an event manager (in this case to the change event) to each matching DOM object that exists at the moment it is executed.
If you want you can re-execute this code (or one similar and narrow) each time you add checkboxes to the DOM.
How can I apply the .delegate method to this line of jquery?
$(function() {
$("input[type='checkbox']").on('change', function() {
if (this.checked) {
$(".loadingItems").fadeIn(300);
var color = encodeURI(this.value);
$(".indexMain").load('indexMain.php?color=' + color, function() {
$(".indexMain").fadeIn(slow);
});
$(".loadingItems").fadeOut(300);
} else {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php', function() {
$(".loadingItems").fadeOut(300);
});
}
});
});
Form:
echo "<input type='checkbox' class='regularCheckbox' name='color[]' value='".$colorBoxes[color_base1]."' /><font class='similarItemsText'> ".$colorBoxes[color_base1]."</font><br />";
PHP receiving colors:
$color = $_GET['color'];
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 = :colorbase1");
$items -> bindValue(":colorbase1", $color);
while($info = $items->fetch(PDO::FETCH_ASSOC))
{ ....
I need to allow multiple selections in a checkbox set.
Now that you've shown us a little more about what you're really trying to do, you will have to change how your code works and .delegate() is not useful for solving that issue.
Right now, you are examining the value of only one checkbox when constructing the URL that you will use with indexMain.php. Instead, you need to examine the values of all the checked checkboxes when constructing that URL.
You don't say how you want to construct the URL when multiple checkboxes are checked, but structurally the code would go something like this:
$(function() {
$("input[type='checkbox']").on('change', function() {
var colors = [];
$("input[type='checkbox']:checked").each(function() {
colors.push(this.value);
});
if (colors.length) {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php?color=' + colors.join("+"), function() {
$(".indexMain").fadeIn(slow);
});
$(".loadingItems").fadeOut(300);
} else {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php', function() {
$(".loadingItems").fadeOut(300);
});
}
});
});
This code will produce a URL for the .load() command like this when one or more colors are selected:
indexMain.php?color=blue+yellow+green+orange
If no colors are selected, it will call indexMain.php with no other arguments.
It will be up to your server code to parse the colors from the URL and create the desired response.
$(document).on('change', 'input[type=checkbox]', function() {
// code
});
Using jQuery .on() you can do that.
Syntax of .on():
$(static_parent).on( eventName, target, handlerFunction);
Where static_parent means a non-dynamic container of target and target is the element to bind event(s).
Delegate can be written as below
$("table").delegate("td", "click", function(){$(this).toggleClass("chosen");});
and the same thing can be achieved using latest(available from jquery 1.7) on() like below
$("table").on("click", "td", function(){$(this).toggleClass("chosen");});