event.preventDefault() with .on('click') doesn't prevent default behavior - javascript

I have the following HTML and javascript. When I click .todo and .completedmsg which have links, I am expecting event.preventDefault(). But it jumps to the link.
$("#form").on('click',".todo", function(event){...}
$("#form").on('click','.completedmsg', function(event){...}
What am I doing wrong here?
HTML all
<div id="homeright" class="adminhome">
<form method="post" id="form" action="admin/insertShoutBox">
<input type="hidden" name="user_id" id="user_id" value="1">
<input type="hidden" name="user" id="nick" value="admin">
<p class="messagelabel"><label class="messagelabel">Message</label>
<textarea id="message" name="message" rows="2" cols="80"></textarea>
</p>
<div class="buttons">
<button type="submit" class="positive" name="submit" value="submit">
<img src="http://localhost/website2014/assets/icons/disk.png" alt="disk"> Save </button>
</div>
</form>
<div id="loading" style="display: none;"><img src="../../assets/images/general/ajax-loader2.gif" alt="Loading now. Smile"></div>
<div class="clearboth"></div>
<div id="container">
<span class="clear"></span>
<div class="content">
<h1>Latest Messages or Task To Do</h1>
<ul id="message_ul" style="display: block;">
<li class="1">
<div class="listbox"><span class="user"><strong>admin</strong></span>
<span class="date">2014-03-28 17:25:50</span>
to do<span class="msg">test</span></div></li></ul>
</div>
</div>
<div id="completed">
<h1>Completed Lists</h1>
<ul id="completed_ul" style="display: block;">
<li class="2">
<span class="user"><strong>admin</strong></span>
<span class="date">2014-03-28 18:11:29</span>
completed
x<span class="msg">another test
</span>
</li></ul>
</div>
</div>
jQuery all
$(document).ready(function(){
//global vars
var inputUser = $("#nick");
var inputMessage = $("#message");
var loading = $("#loading");
var messageList = $("#message_ul");
var completedmsg = $("#completed");
var completedList = $("#completed_ul");
//Load for the first time the shoutbox data
updateShoutbox();
updateCompletedbox();
function updateShoutbox()
{
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/AjaxgetShoutBox'); ?>",
complete: function(data)
{
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(500);
//completedList.fadeIn(500);
}
});
}
function updateCompletedbox()
{
//just for the fade effect
completedList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/AjaxgetCompletedBox'); ?>",
complete: function(data)
{
loading.fadeOut();
completedList.html(data.responseText);
// messageList.fadeIn(500);
completedList.fadeIn(500);
}
});
}
//check if all fields are filled
function checkForm()
{
if(inputUser.val() && inputMessage.val())
{
return true;
}
else
{
return false;
}
}
//on submit event
$("#form").submit(function(event){
event.preventDefault();
if(checkForm())
{
var nick = inputUser.attr("value");
var message = inputMessage.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/insertShoutBox'); ?>",
data: $('#form').serialize(),
complete: function(data)
{
messageList.html(data.responseText);
updateShoutbox();
$('#message').val('');
//reactivate the send button
$("#send").attr({ disabled:false, value:"SUBMIT !" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
//on todo event. this changes the status to compeleted
$("#form").on('click',".todo", function(event){
event.preventDefault();
loading.fadeIn();
var href = $(this).attr("href");
var msgContainer = $(this).closest('li');
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function()
{
msgContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
// on complete event. this changes the status to todo
$("#form").on('click','.completedmsg', function(event){
event.preventDefault();
loading.fadeIn();
var href = $(this).attr("href");
var CompMsgContainer = $(this).closest('li');
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function(){
CompMsgContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
$("#form").on('click','.delete',function(event){
event.preventDefault();
// alert ('clicked');
loading.fadeIn();
var href = $(this).attr("href");
var commentContainer = $(this).parent();
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function()
{
commentContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
});

There are no links inside #form with a class of todo - so the events are not attached to your links:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
The links are outside of the form, so those particular events can't be firing. If the event isn't firing then it makes sense that the links are being 'jumped to' as there's nothing to trap it. If you place a link with the class of .todo inside the form, you will get the desired effect.
As a first test, you could just bind to $(document) instead of #form and check the preventDefault before re-working the HTML so that you can bind to a lower-level element in the DOM (if required...)
Cut-down example of issue: http://jsfiddle.net/YWV9A/1/
Solution: http://jsfiddle.net/YWV9A/3/

Related

Why ajax reloads the page

I have an ajax + jquery script and when I execute it (click the button) it reloads the page.
script
jQuery(document).ready(function($) {
$(document).on('click', '.image-remove-btn', function (e){
var img = $(this).closest('.thumbs');
var id = img.attr('data-id');
$.ajax({
url: admin_url('admin-ajax.php'),
type: 'POST',
data: {deletedId : id},
success: function( data ) {
img.remove();
}
});
});
});
HTML of element that should be removed:
<div class="thumbs ui-droppable">
<div class="inner ui-draggable ui-draggable-handle" data-thumb="0">
<img data-id="32949" src="https://badzingerauto.com/wp-content/uploads/2021/05/NISSAN__QASHQAI__1-5_dCi_106_Acenta__inc-__inc-__2009__BC501CF-e01-350x205.jpg">
<div class="inner-hover">
<button class="image-remove-btn butterbean-remove-image"> <!-- <i class="fa fa-arrows"></i> Font Awesome fontawesome.com -->
</div>
</div>
</div>
I think #Charlieft is correct you can change your code as follows to prevent the reload
jQuery(document).ready(function($) {
$(document).on('click', '.image-remove-btn', function (e){
e.preventDefault();
var img = $(this).closest('.thumbs');
var id = img.attr('data-id');
$.ajax({
url: admin_url('admin-ajax.php'),
type: 'POST',
data: {deletedId : id},
success: function( data ) {
img.remove();
}
});
});
});

How to pass onclick function values to ajax post method without refresh page?

This is my onclick function. When I click it the php values should save in database.
<div class="startup-like">
<label class="toggler toggler-danger">
<input type="checkbox" onclick="return favadd(<?php echo $favblogid;?>,<?php echo $b;?>,<?php echo $type_id;?>,<?php echo $lang_id;?>);">
<i class="fa fa-bookmark" title="Save" id="toptip"></i>
</label>
</div>
and this is my script for the onclick function.
<script>
function favadd(val,val2,val3,val4)
{
var blog_id=val;
var userid=val2;
var catid=val3;
var lang=val4;
$.ajax({
type: "POST",
url: "startuparticle_save.php",
data: {
fav_blogid: blog_id,
fav_user_id: userid,
cat_id:catid,
langid:lang
},
success: function (value) {
}
});
}
</script>
I want to pass the values without refresh the page.
<script>
function favadd(val,val2,val3,val4)
{
var blog_id=val;
var userid=val2;
var catid=val3;
var lang=val4;
$.ajax({
type: "POST",
url: "startuparticle_save.php",
data: {
fav_blogid: blog_id,
fav_user_id: userid,
cat_id:catid,
langid:lang
},
success: function (value) {
"$("#your div id").load(" #your div id> ");"
}
});
}
</script>
<script type="text/javascript">
$("#MyButton").click(function() {
alert('clicked')
$("#refresh_div").load(" #refresh_div> *`enter code here`");
});
</script>

Textarea is not displaying the result

I have a textarea which will be in hidden state when the request comes to the page and once i select the value in the page i call a controller method which does manipilation and returns the response to the same page and in the ajax success method i try to print the response in the textarea
This is my gsp page
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<title>Json Compare</title>
<g:javascript plugin="jquery" library="jquery"
src="jquery/jquery-1.11.1.js" />
<script>
$(document).ready(function(){
$('.testMe').click(function(){
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
var retrievedValue = JSON.parse(data);
alert("Parsed Values are: "+retrievedValue)
alert("Values are: "+retrievedValue.status)
//alert("success: "+retrievedValue.result)
if (retrievedValue.status===true) {
alert("inside the success: "+retrievedValue.result)
alert("the parsed values 1st data"+data.firstText)
$("#result").css("display","block")
$("#result").val(data.firstText)
//notice .html since it is content of textArea
//$('.textarea').html(retrievedValue.result)
//document.getElementById("textarea").style.display = "block"
//document.getElementById("textarea").innerHTML = data.result
//$('#textarea').val(retrievedValue.result).show()
// $('.textarea').css("display","");
//$('#result').attr('style', 'display:block'); 
//$('#testdiv').show()
//$('.textarea').toggle();
// $('#testdiv').attr('style', 'display:block'); 
//$('#testdiv').removeAttr("style");
//document.getElementById("result").style.display = "none";
} else { /// if (data===false ) {
alert("Failure: "+retrievedValue.value1+" "+retrievedValue.value2)
//$('#result1').html(entry.value1).show()
// $('#result2').html(entry.value2).show()
}
}
});
});
});
//event.preventDefault();
</script>
</head>
<body>
<g:form>
<div>
<label>From Time</label>
<g:select name="firstText" from="${eventsList}" noSelection="['':'-Choose the From Date-']" />
<label>To Time</label>
<g:select name="secondText" from="${eventsList}" noSelection="['':'-Choose the To Date-']" />
<button class="testMe">Compare</button>
</div>
<br>
<textarea id="result" style="display: none"></textarea>
<%--<div id="textarea">
<label>Output</label><br>
<textArea id="result" name="myField" />
<textarea></textarea>
</div>
--%></g:form>
</body>
</html>
once the result is displayed immediately it disappears how to stop it. And also how to display the result different textarea based on the response from the controller. Initially the textarea should not be visible
Treat a textArea like a div
$('#textArea').html('content');
Unless you declare:
<g:textArea value="something" />
Which then behaves differently to a standard textArea if I recall correctly
Update:
$(document).ready(function(e){
$('.testMe').click(function(e){
e.preventDefault();
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
//alert("success"+data.value)
console.log(data);
$("#result").val(data).show()
}
});
});
});
try this.. hopefully it'll work.
$(document).ready(function() {
$('.testMe').click(function() {
var URL = "${createLink(controller:'jsonComparison',action:'compare')}";
var firstText = $('#firstText');
var secondText = $('#secondText');
alert(URL);
alert(firstText.val());
alert(secondText.val());
$.ajax({
url: URL,
data: {
firstText: firstText.val(),
secondText: secondText.val()
},
success: function(data) {
//alert("success"+data.value)
console.log(data);
$("#result").val(data);
$("#result").show();
}
});
});
});
And if you try to append the textarea element dynamically? For example:
$(document).ready(function(){
$('.testMe').click(function(){
// ... your code ...
// ajax part
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
var textarea_el = $('<textarea />', {
id: 'result',
text: data.value // or just data?
});
// change form_selector with the real selector!
$(<form_selector>).append(textarea_el);
}
});
});
});
<script>
$(document).ready(function(){
$('.testMe').click(function(){
var URL="${createLink(controller:'jsonComparison',action:'compare')}";
alert(URL)
alert(firstText.value)
alert(secondText.value)
$.ajax({
url:URL,
data: {firstText:firstText.value,secondText:secondText.value},
success: function(data){
//alert("success"+data.value)
console.log(data);
$("#result").css("display","block")
$("#result").val(data.firstText)
}
});
});
});
</script>
try above code
if it not ,try to alert(data.firstText) check the return value in alert .whether it is object or value

How to bind jquery ajax returned html using on.() [duplicate]

This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 8 years ago.
I know this question has been asked but I can't wrap my head around how to implement it correctly in my use case.
End game is when an item is added to the cart by clicking the items add button, it triggers and ajax call passing the items id to a php function that adds it to the cart session (this works great).
On the ajax calls success it calls the function update_cart(), which builds new cart html and returns it. The div holding the cart html has its contents replaced by the new cart html contents (item qty price line items). This part works well also.
The new cart contents line items include name, the qty is displayed in an input, and the price.
The newly created line items qty input is not reacting the the onblur action (i think) due to the fact that it hasnt been bound to anything since it didnt exist on page load.
Can some amazing gentleman (or woman) and scholar help me understand how to bind the new inputs so I can call an ajax function to update the item qty when the field blurs?
My JS
$(document).ready(function () {
function update_cart() {
var dataString = "";
//alert (dataString);return false;
$.ajax({
type: "POST",
dataType: "html",
data: dataString,
url: "/actions/updatecart.action.php",
beforeSend: function() {
$('#loader').show();
},
complete: function() {
$('#loader').hide();
},
success: function(data) {
$('#cart-items').hide().html(data).fadeIn( "slow");
},
error: function(data){
$('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Error Updating Cart</div>").slideDown( "fast");
}
});
};
$(function() {
$("button[id^=add]").on("click", function(){
var id = $( this ).data('id');
var dataString = 'id='+ id;
/* alert (dataString);return false; */
$.ajax({
type: "POST",
dataType: "html",
data: dataString,
url: "/actions/add.action.php",
beforeSend: function() {
$('#loader').show();
},
complete: function() {
$('#loader').hide();
},
success: update_cart ,
error: function(data){
// $('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Error Adding Item</div>").slideDown( "fast");
}
});
return false;
});
});
$(function() {
$("input[id^=lineitem]").on("blur", function(){
var id = $( this ).data('id');
var qty = $( this ).val();
var dataString = 'id='+ id + '&qty=' + qty;
alert (dataString);return false;
$.ajax({
type: "POST",
dataType: "html",
data: dataString,
url: "/actions/add.action.php",
beforeSend: function() {
$('#loader').show();
},
complete: function() {
$('#loader').hide();
},
success: update_cart ,
error: function(data){
// $('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Error Updating Quanity</div>").slideDown( "fast");
}
});
return false;
});
});
});
My Returned html and php foreach that creates it
foreach($_SESSION['basket']['items'] as $item){ ?>
<div class="cart-item">
<div class="col-lg-8 col-md-8 np item"><?php echo $item['name']; ?></div>
<div class="col-lg-2 col-md-2 np"><div class="input-group"><input data-id="<?php echo $item['id']; ?>" id="lineitem-<?php echo $item['id']; ?>" value="<?php echo $item['count']; ?>" type="text" class="form-control"></div></div>
<div class="col-lg-2 col-md-2 np price"><?php echo $item['price']; ?></div>
</div>
<?php } ?>
Thanks to anyone who can help me get my mind around how to do this. Everything was so smooth up until now.
I think this is what you want:
...success: function(data) {
$('#cart-items').hide().html(data).fadeIn( "slow");
$(".cart-item .input-group input").bind("change",...function);
OR
$(".cart-item .input-group input").on("change",...function);
OR
$(".cart-item .input-group input").change(...function);
}...

How to close the box if click anywhere?

I have an code that the function is autosuggestion. This code works good. And I just want to ask You about how to close the box after I input text in the textbox. In my code when I try to click anywhere, it didn't close the box. So what I want to do is when I click anywhere so the box must be close.
Here is my jQuery:
$(document).ready(function() {
$(".text_search").keyup(function() {
var searchbox = $(this).val();
var dataString = 'searchword=' + searchbox;
if (searchbox == '') {} else {
$.ajax({
type: "POST",
url: "search1.php",
data: dataString,
cache: false,
success: function(html) {
$("#display").html(html).show();
}
});
}
return false;
});
});​
HTML:
<div class="search">
<form method="get" action="search.php" autocomplete="off">
<input class="text_search" type="text" name="q" id="q" value="Search people" onfocus="if (this.value == 'Search people') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search people';}">
</form>
</div>
<div id="display">
</div>
Just add a event handler on the document body and close the box if it's open. Put that at the end of your body :
<script>
$(window).ready(function(){
$('body').click(function(){
$("#display").hide();
});
});
</script>
EDIT :
If you want also to have the search launched again when you click the search box, change your script to this :
$(document).ready(function() {
var launchSearch = function() {
var searchbox = $(this).val();
var dataString = 'searchword=' + searchbox;
if (searchbox == '') {} else {
$.ajax({
type: "POST",
url: "search1.php",
data: dataString,
cache: false,
success: function(html) {
$("#display").html(html).show();
}
});
}
return false;
};
$(".text_search").keyup(launchSearch).click(launchSearch);
$('body').click(function(){
$("#display").hide();
});
});​
Try this:
$('body').click(function(){
$("#display").hide();
});
$(document).click(function(e) {
if($(e.target).parents("#display").length == 0 &&
$(e.target).attr("id") != "display") {
$("#display").hide();
}
});
You must check if click is not in display div
Try this
$(document).ready(function(){
$('body').click(function(){
$("#display").hide();
});
$(".text_search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{}
else
{
$.ajax({
type: "POST",
url: "search1.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}return false;
});
});

Categories

Resources