Im new to jquery and even newer to ajax so please bear with me here.
I have the following script which fetches data (branch names) asynchronously via database:
$(document).ready(function () {
$("#pickup").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'modal/fetch_branch.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
}
});
});
});
<input type="text" class="form-control empty" name="keyword" id="pickup" placeholder=""/>
When the user types, S as an example all branches containg S will be returned as can be seen in the image below:
WHAT I WOULD LIKE TO DO
I need to find a way to modify my script, to
allow user to click the link, for desired result (branch)
When link (branch) is clicked it needs to get appended to the form input field as the value of pickup
Any help or advise on how the above can be achieved, much appreciated.
P.S returned data (names) are <a> elements , thus they are links.
As far as I understand data in success:function (data) contains some <a> elements, so you need to add a handler to process click on these elements:
// use `on` as elements are added dynamically
$( "#results" ).on("click", "a", function() {
// take `text` of a clicked element and set it as `#pickup` value
$( "#pickup" ).val( $( this ).text() );
// return false to prevent default action
return false;
});
Add onclick on the link. Try this
<a onclick="func(this);" data-value="Strand">Strand</a>
function func(idn){
var value = $(idn).attr("data-value");
$("#pickup).val(value); //assuming that the pickup field has a "pickup" id
}
Related
I have a form with a conditional field that is only shown if the user selects a radio button for "other." If I remove the conditional on this field, my original javascript function works; however, with the conditional I can not get it to fire correctly.
The form has an event "cf.add" that fires when a conditional field is made visible, and using this jquery I get a correct response in the console:
jQuery( document ).on( 'cf.add', function(){
console.log('cf.add triggered' );
});
And if I remove the conditional so that this field is rendered when the page is rendered, I get the correct response in this field, which is to add a '$':
$("#fld_3169487_4").on("blur", handleChange);
function handleChange() {
var myValue = document.getElementById("fld_3169487_4").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("fld_3169487_4").value = myValue;
}
I've tried putting this second function within the first, but no luck. I feel like I'm adding them in the incorrect order when I try to combine the two, I'm not sure what I'm doing wrong though.
I've also tried to call the function handleChange() on the 'cf.add' trigger, but that did not work for me either.
After some playing around, I figured it out:
jQuery( document ).on( 'cf.add', function(){
var otherField = $("#fld_3169487_3");
otherField.focus();
var dollarValue;
$(otherField).on("blur", function() {
dollarValue = otherField.val();
if (dollarValue.indexOf("$") != 0) {
dollarValue = "$ " + dollarValue;
}
$(otherField).val(dollarValue);
});
});
Since cf.add is an custom even that is published by your form, you can have other elements subscribe to the event:
$("#fld_3169487_4").on('cf.add', function(event){
if ($(this).val().indexOf("$") != 0)
{
$(this).val("$" + $(this).val());
}
});
Using $(this), we can target just the field the event is attached to. Additionally, data from the event publisher can be passed to the subscribers via the event argument.
A Radio Button runs a onchange jQuery function when we click on it. But if we directly check this same radio button by a link parameter, the function is not called. Please, how to solve this? I've tried changing onchange to onclick without success.
Page I'm working on: Once any Store is manually selected, the onchange function will hide the Store DIV and show the Category DIV, simulating a step filter. http://www.hotsales.com.br/procurar/
This is the direct link parameter to automatically select some Store. But this way, the onchange function doesn't run, so the Store DIV is still visible and the Category DIV still hidden. http://www.hotsales.com.br/procurar/?offer_store=852
This is the first function that should run when Store is selected (both manually or by direct link).
/* AJAX SEARCH*/
$(document).on( 'change', '.advanced-search input', function(){
start_ajax_search3();
$.ajax({
url: $('.advanced-search').attr('action'),
data: $('.advanced-search').serialize(),
success: function( response ){
handle_ajax_search_response( response ); /*this function hide/show desired DIV*/
},
complete: function(){
end_ajax_search();
}
});
});
This is how the DIVs are hidden/showed:
function handle_ajax_search_response( response ){
var $response = $('<div>'+response+'</div>');
$('.ajax-results').html( $response.find('.ajax-results').html() );
$('.ajax-sidebar').html( $response.find('.ajax-sidebar').html() );
$('.category-filter').show();
$('.store-filter').hide();
$('.offer-type-filter').show();}
You could call your function on change and on document ready, ex:
function test(chk){
console.log("called by" + $(chk).attr("id"));
}
$(document).ready(function(){
if($("#chkTest2").is(":checked")){
test($("#chkTest2"));
}
});
$(".chkboxes").on( 'change', function(){
test(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="chkboxes" type="checkbox" id="chkTest1">Test 1
<input class="chkboxes" type="checkbox" id="chkTest2" checked="checked"> Test 2
I hope it helps you, bye.
I'm trying to figure out how to change behaviour of a button using AJAX.
When the button is clicked, it means that user confirmed order recently created. AJAX calls /confirm-order/<id> and if the order has been confirmed, I want to change the button to redirect to /my-orders/ after next click on it. The problem is that it calls again the same JQuery function. I've tried already to remove class="confirm-button" attribute to avoid JQuery again but it does not work. What should I do?
It would be enough, if the button has been removed and replaced by text "Confirmed", but this.html() changes only inner html which is a text of the button.
$(document).ready(function () {
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
var id = this.value;
var url = '/confirm-order/'+id;
$.ajax({
type: 'get',
url: url,
success: function (data) {
$this.empty();
$this.attr('href','/my-orders/');
$this.parent().attr("action", "/my-orders/");
$this.html('Confirmed');
}
})
});
});
The event handler will be still attached to the button, so this will run again:
b.preventDefault();
which will prevent the default, which is opening the href. You need to remove the event handler on success. You use the jQuery #off() method:
$(".confirm-button").off('click');
or more shortly:
$this.off('click');
You can add to your success function something like: $this.data('isConfirmed', true);
And then in your click handler start by checking for it. If it's true, redirect the user to the next page.
$(".confirm-button").click(function (b) {
b.preventDefault();
var $this = $(this);
if ($this.data('isConfirmed')) {
... redirect code ...
}
else {
... your regular code ...
}
}
You need to use .on() rather than .click() to catch events after the document is ready, because the "new" button appears later.
See http://api.jquery.com/on/
$(document).ready(function() {
$('.js-confirm').click(function(){
alert('Confirmed!');
$(this).off('click').removeClass('js-confirm').addClass('js-redirect').html('Redirect');
});
$(document).on('click', '.js-redirect', function(){
alert('Redirecting');
});
});
<button class="js-confirm">Confirm</button>
Well my main problem is the button. I can't seem to find the reason why the button doesn't show up when I already clicked a certain tr
Here is the code that displays the returned employee data from the database
$.each(data, function(index, val) {
$("#employee_list").append('<tr class="emp_delete" id="'+val.emp_id+'"><td>'+val.emp_id+'</td><td>'+val.last_name+'</td><td>'+val.first_name+
'</td><td>'+val.middle_in+'</td>'+
'<td><input type="button" value="Resigned Employee" class="deleteBtn" id="delete_"'+val.emp_id+'"></td></tr>');
});
and here is the code that shows the button if .emp_delete is clicked. then the .deleteBtn code to delete the certain data
$(".emp_delete").click(function(){
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
$(".deleteBtn").click(function(){
var ID=$(".emp_delete").attr('id');
if (confirm("Are you sure you want to delete?")) {
var dataString = 'emp_id='+ID;
$.ajax({
type: "POST",
url: "<?php echo site_url('c_employee/delete_employee'); ?>",
data: dataString,
cache: false,
success: function(html){
location.reload();
}
});
}
UPDATE
The code that #Satpal gave worked but the .deleteBtn still doesn't show up after going through the each loop.
Here is the updated code:
$('#employee_list').delegate( ".emp_delete", 'click', function() {
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
$(".deleteBtn").click(function(){
var ID=$(".emp_delete").attr('id');
if (confirm("Are you sure you want to delete?")) {
var dataString = 'emp_id='+ID;
$.ajax({
type: "POST",
url: "<?php echo site_url('c_employee/delete_employee'); ?>",
data: dataString,
cache: false,
success: function(html){
location.reload();
}
});
}
else
return false;
});
As you are adding HTML dynamically.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
Use
$(document).on(event, selector, eventHandler);
In above example, document should be replaced with closest static container.
In Your case
$('#employee_list').on('click', ".emp_delete", function() {
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
Similarly you have to delegate event for ".deleteBtn"
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
EDIT
As per comment.
Since you are using jQuery 1.5, use .delegate()
$(elements).delegate( selector, events, data, handler );
In Your case
$('#employee_list').delegate( ".emp_delete", 'click', function() {
var ID=$(this).attr('id');
$("#delete_"+ID).show();
});
EDIT 2
Use similar syntax for delete button also
$('#employee_list').delegate( ".deleteBtn", 'click', function() {
});
You mean the button does not fire?
If so, that is because you define the function before you insert the element in the DOM, you need to bind it.
So instead of:
$(".deleteBtn").click(function(){
Put:
$("#employee_list").on("click",".deleteBtn",function(){
Once the document has been fully loaded, each time you add a new object to the DOM dynamically (like adding a new table row with buttons) you'll need to bind the generated element to an event or action, you cannot say "do something when someone clicks any button" you'd say "do something when someone clicks THIS button" meaning that you have to have the object created first in order to "attach" some action to it.
So let's say that you have these:
<button class="action-button" id="1">Button 1</button>
<button class="action-button" id="2">Button 2</button>
And then this javascript:
$(document).ready(function(){
$(".action-button").click(function(){
alert('My id is ' + $(this).attr('id'));
});
});
And then you later decide to add a button with some action on your js/html:
<button class="action-button" id="3">Button 3</button>
Surprise! If you click button 3 you'll get no alert...? Why, because the function that you set up for click event on document.ready parsed only the initial two buttons that existed at that moment, but since you added a third one dynamically later, the document.ready code wasn't aware of it.
So as Emil pointed out, each time you create a new element you'll want to bind it, in our example, for our button 3:
$('#3').bind('click', function(){
alert('My id is ' + $(this).attr('id'));
});
Or by the class, which is not adequate cause it would rebind existing elements and you lose performance:
$('.action-button').bind('click', function(){
alert('My id is ' + $(this).attr('id'));
});
So make sure that if you add elements that do actions or call functions you bind them when you add them, ideally, have a separate function which does whatever the button needs to do and then when you bind the new element, bind it to that function instead of putting a direct callback.
Try jquery version less than 1.9:
$('selector').live('click', function(){
});
you have a problem with the id delete
<div id="di"></div>
Algo
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$('#algo').click(function(){
var a = 1;
//THIS IS IMPORTANT , SEE ID = "delete_" <- has a problem
$('#di').html('<td><input type="button" value="Resigned Employee" class="deleteBtn" id="delete_'+a+'"></td></tr>');
});
</script>
Is id="delete_'+val.emp_id+'" and not id="delete_"'+val.emp_id+'" (" <- error)
I am trying to create a form in which there is a field where the user enters the productName. As the user enters the product name a list of products is shown to him via ajax with an ADD button. When the user clicks the add button, the productName is written into a <div> with a delete button with the help of jquery. Till here everything is working fine. Now I want that if the user clicks on the delete button then that product name is removed from that particular <div> tag. It works for the first time. But when i click the Delete button for next item. It is not working. Here is my jquery code
CODE:
$(function(){
$('.addProducts').keyup(function(event)
{
var searchVal=$(this).val().trim();
if(searchVal.length > 0)
{
$.ajax({
url: 'http://localhost/myurl',
data: {
products: $(this).val(),
},
type: 'POST',
dataType: 'html',
success: function(msg)
{
$('#printTheProducts').html(msg);
var productVal=$(this).attr('name');
var addedProductsValue=$('#myAddedProducts').html();
var textValueOfProducts=$('#myAddedProducts').text();
var deleteButton='<input type="button" class="deleteButton" value="Delete" name="'+productVal+'">';
if(textValueOfProducts.length===0)
{
$('#myAddedProducts').html(productVal+deleteButton);
}
else
{
var checkAddedProducts=textValueOfProducts.split(",");
if(checkAddedProducts.indexOf(productVal) < 0)
{
$('#myAddedProducts').html(addedProductsValue+','+productVal+deleteButton);
}
else
{
alert(productVal+' is already added');
}
}
--------------------------------------------------------------------------------------------
Code where I am Getting problem
$('.deleteButton').click(function()
{
var productsTextArray=new Array();
var productsHtml;
var productsHtmlArray=new Array();
var deleteVal=$(this).attr('name');
var myAddedProductsTextValue=$('#myAddedProducts').text().trim();
if(myAddedProductsTextValue.length > 0)
{
productsTextArray=myAddedProductsTextValue.split(",");
productsHtml=$('#myAddedProducts').html();
productsHtmlArray=productsHtml.split(",");
}
var deleteId=$.inArray(deleteVal,productsTextArray);
productsHtmlArray.splice(deleteId,1);
// if I add
$('#myAddedProducts').html(productsHtmlArray.join());
then it prevents this function from working next time.I do not understand why
});
--------------------------------------------------------------------------------------------
});
}
});
}
});
});
Question
How can I make this delete button to work for all the product name so that it can remove the name of that product from the <div>
Its hard to understand what your code is doing without a fiddle example to play with.
Is the click event being fired on the delete button the second time?
If not, then the problem is the event handler.
You can try this: $('body').on('click', '.deleteButton', function(){
//put the code here. replace 'body' with a closer parent of the delete button for efficiency.
});
http://api.jquery.com/on/
If the click event is being fired, then perhaps the problem is here:
var deleteVal=$(this).attr('name');
As i see you create one delete button for all your products,and assign it's name attribute to last added product.Because of that when you click your delete button it removes only last product.