laravel Javascript and Render sections - javascript

Hi I did a webapp with laravel, with various forms that add datas to database and then refresh only some sections (for example insert an order, then insert some products...etc), but when section render javascript doesn't work anymore.
I have some Jquery that catch some events...for example some click buttons.
EXAMPLE
PART of script in the HEAD
<script src="{{ asset('public/js/jquery-3.5.1.min.js') }}"></script>
<script src="{{ asset('public/js/vendor/popper.min.js') }}"></script>
<script src="{{ asset('public/js/bootstrap.min.js') }}"></script>
<script src="{{ asset('public/js/vendor/holder.min.js') }}"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function(){
$(document).ajaxSend(function() {
$("#overlay").fadeIn(300); 
});
$('#searchPolizza').keydown(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
$value=$(this).val();
$.ajax({
type : 'get',
url : "{{ url("/trova") }}",
data:{'numero':$value},
success:function(data){
$('#RefreshContent').replaceWith(data);
//initRefundsFunctions();
//initDossierListClick();
}
});
}
});
$( "#addDossier" ).click(function( event ) {
event.preventDefault();
//$("#addDossierForm")[0].reset();
var r = confirm("Vuoi veramente creare un nuovo dossier?");
if (r == true) {
....continue.......</script>
After i found a "polizza" calling ajax '#searchPolizza' Then i refresh content section
Part of RefreshContent section where i have a form with button #addDossier that i can press after refresh section related to first search
<div class="" style="zoom:90%">
<form class="form-inline" id="addDossierForm">
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="dossier" id="dossier">
<input type="date" class="form-control mb-2 mr-sm-2" placeholder="data sinitro" id="date_cla">
<button type="submit" class="btn btn-primary mb-2" data-customer_id="#isset($customer_id){{$customer_id}}#endisset" id="addDossier"><i class="fa fa-plus" aria-hidden="true"></i></button>
</form>
</div>
But jquery cannot catch anymore the click event
I tried to put all script in the head or also to create function to recall but it doesn't work well.
Is there another solution?
Thx

Here, $(dom).click() binds events statically, You should try registering you click event function like this:
$( '#addDossier' ).on( 'click', function (event) { your code});
which binds event handler dynamically, check that out here and you could use shorthand (function(){..})(); instead of $(document).ready(function(){...}); and you should consider using something modern like Vue/React. Jquery is primitive and getting older.

Related

Jquery: html, text and append functions are not working

I have a simple code to make requisition by ajax.
<script type="text/javascript" src="{{ url_for('static', filename='jquery-2.2.4.min.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function (e) {
var url = "{{ url_for('ajaxPage') }}";
$.ajax({
type: "POST",
url: url,
data: $('form').serialize(),
dataType:'json',
success: function (data) {
var text= "Anything here!";
$('div.panel-body').html(text); //Not Working
$('div.panel-body').text(text); //Not Working
$('div.panel-body').append(text); //Not Working
alert(text); //Working
console.log(text); //Working
}
});
e.preventDefault();
});
});
</script>
Here body layout:
<body>
<div class="panel-body"> // Waiting content </div>
</body>
Ajax is working perfectly, I can view my array using console.log, alert, but I can not use HTML(), TEXT() and APPEND(). Where is my mistake? I already change JS file and I have other page with the same code and it works fine!
Update
My Network page
Updating body page
<div class="input-group">
<form method="POST" name='form'>
<input type="text" name="inputxt" class="form-control" size="20">
<button type="submit">Search</button>
</form>
</div>
<div class="panel-body">
</div>
I recreated this page and the problem was a css inside DIV.

preventDefault form submit not working in bootstrap popover

I have a bootstrap popover element with a form inside.
I do a preventDefault() when the form is submitted but it doesn't actually prevent the submit.
When I don't use the popover and a modal instead it works perfectly.
Here is my HTML:
<div class="hide" id="popover-content">
<form action="api/check.php" class="checkform" id="requestacallform" method="get" name="requestacallform">
<div class="form-group">
<div class="input-group">
<input class="form-control" id="domein" name="name" placeholder="domein" type="text">
</div>
</div><input class="btn btn-blue submit" type="submit" value="Aanmelden">
<p class="response"></p>
</form>
</div>
Here is my JavaScript file where I create the popup (main.js)
$('#popover').popover({
html: true,
content: function() {
return $("#popover-content").html();
}
});
And this is where I do my preventDefault() in an other JavaScript file
$(".checkform").submit(function(e) {
e.preventDefault();
var request = $("#domein").val();
$.ajax({
// AJAX content here
});
});
Why the preventDefault() isn't working?
You're trying to append event handler for .checkform before adding it to DOM. You need to load second javascript file after loading contents html or append event globaly:
$("body").on("submit",".checkform", function(e){
e.preventDefault();
var request = $("#domein").val();
$.ajax({
...
});
You can read more about events binding on dynamic htmls here
Try it like this please:
$(document).on('submit', '.checkform', function(e){
e.preventDefault();
var request = $("#domein").val();
$.ajax({
...
});
It is possible that the popover isn't loaded on page load and is getting generated just when it is needed so you need the document selector.
Because whenever the popover is opened a new dom fragment is created on the fly you may take advantage on this to attach events or manipulate the html itself like you need.
From bootstrap popover docs you need to listen for this event:
inserted.bs.popover: This event is fired after the show.bs.popover event when the popover template has been added to the DOM.
So, my proposal is to avoid the event delegation and attach the event directly to the correct element:
$(function () {
// open the popover on click
$('#popover').popover({
html: true,
content: function () {
return $("#popover-content").html();
}
});
// when the popover template has been added to the DOM
// find the correct element and attach the event handler
// because the popover template is removed on close
// it's useless to remove the event with .off('submit')
$('#popover').on('inserted.bs.popover', function(e){
$(this).next('.popover').find('.checkform').on('submit', function(e){
e.preventDefault();
var request = $("#domein").val();
// do your stuff
$('#popover').trigger('click');
});
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<body>
<button type="button" class="btn btn-default popover-content" role="button" id="popover">
Click to open Popover
</button>
<div id="popover-content" class="hidden">
<form action="z.html" id="requestacallform" method="GET" name="requestacallform" class="checkform">
<div class="form-group">
<div class="input-group">
<input id="domein" type="text" class="form-control" placeholder="domein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue submit"/>
<p class="response"></p>
</form>
</div>
Thanks for the responses, I was using Meteor and had the same problem. I used #Marcel Wasilewski's response like so...
Template.voteContest.onRendered(function() {
$(document).on('submit', '.keep-vote', function(event){
// Prevent default browser form submit
event.preventDefault();
// Clear all popovers
$("[data-toggle='tooltip']").popover('hide');
});
});

Unwanted Multiple KeyDown Events triggered on single keydown

So basically what I need to do is detect a keydown event of spacebar and hence perform some logic based on it in my javascript file.
So as you can see in my html, that there is a button "compose" on clicking which the message-container is displayed.
Now I need to implement Gmail like feature of converting the mail ids in recipients as tags but in my case a valid mail-id will be converted to a tag as soon as a space-bar is pressed, i.e, the string before the space bar will be checked for valid email-id.
So i've written the on-click function of the recipient container and the keydown function for spacebar.
Now here comes the problem. When the page is loaded for the first time, it works perfectly fine. I click inside the recipient box and as soon as i hit space bar, "spacebar pressed" gets printed on the browser console one time for one key down.
Now if I hide this message-container div by clicking the "close" button, and then again show the message-container div by clicking the "compose" button, and then when i click in the recipients box, it fires two keydown events for spacebar i.e., "spacebar pressed" will be printed twice.
And consequently, if i again close and reopen the box and click again, it will print "spacebar pressed" three times for every keydown of spacebar.
So is it something related to binding and unbinding of events or something else? Coz i have gone through similar links in which the key down event was getting binding again and again, but could really figure out how I would like kill the event on clicking of "close" button.
Here is html:
<!DOCTYPE html>
<html>
<head>
<title>ZMail</title>
<link rel="stylesheet" type="text/css" href="css/fonts.css" />
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div class="header">
<h2>ZMail</h2>
</div>
<div class="body-container">
<button type="button" class="compose-button" id="compose-button">Compose</button>
<div class="message-container" id="message-container">
<div class="compose-form-header">
<p> New Message </p>
<button type="button" class="close-button" id="close-button">x</button>
</div>
<form id="compose-form" method="POST" action="">
<div class="recipient-container" id="recipient-container">
<div class="to-box" id="to-box">
<p>To</p>
</div>
<div class="input-elements-container" id="input-elements-container">
<input type="text" id="recipient-box" name="recipients" placeholder="Recipients">
</div>
</div>
<input type="text" id="subject-box" name="subject" placeholder="Subject">
<textarea form="compose-form" id="message-text-box" name="message-text" ></textarea>
<div class="send-button-container">
<button type="submit" class="send-mail-button" id="send-mail-button">Send</button>
</div>
</form>
</div>
</div>
</body>
And here is the JS
var contacts = ['ankush.rgv#gmail.com']
$(document).on('ready', function(){
$("#message-container").hide();
$("#to-box").hide();
$("#compose-button").click(function (event) {
if($("#message-container").is(':hidden')){
$(function() {
$("#recipient-box" ).autocomplete({
source: contacts
});
});
$("#message-container").show();
}
});
$("#close-button").click(function (event) {
$("#message-container").hide();
$("#to-box").hide();
$("#recipient-box").val('');
$("#subject-box").val('');
$("#recipient-box").attr('placeholder', 'Recipients');
$("#subject-box").attr('placeholder', 'Subject');
});
$("#recipient-container").click(function (event) {
console.log("recipients clicked");
$("#to-box").show();
$("#recipient-box").attr('placeholder', '');
$(document).keydown(function(e) {
if (e.keyCode == 32) {
console.log("spacebar pressed!!");
}
});
});
$("#subject-box").click(function (event) {
$(this).attr('placeholder', '');
});
});
Any help will be appreciated.
Everytime you click on #recipient-container, .keydown() will add an extra event handler to the document, without removing the existing ones.
The easiest solution here would be to remove the handler when you click on #close-button. Unbinding events can be done with .off().
$(document).off('keydown');

bootstrap to display click result without page refresh

I have a page that I have it split in half. The left side will have the text hyperlinks or buttons, and on the right side I need to display the results without page refresh. I'm hoping that bootstrap has something like this but have not been able to find it. Any help will greatly be appreciated.
Bootstrap doesn't provide AJAX calls, it's more for styling your site web. For this, you need to check the jQuery AJAX documentation.
Edit
Here's a simple example to make AJAX calls.
index.php (Basic HTML code)
<div class="container">
<div class="row">
<div class="col-md-6">
<button id="cats" data-animal="cats" class="btn btn-default">Text on cats</button>
<button id="dogs" data-animal="dogs" class="btn btn-default">Text on dogs</button>
</div>
<div class="col-md-6">
<div id="results"></div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
script.js (Script where the AJAX call will be made)
$(document).ready(function() {
$("button").on('click', function(e) {
e.preventDefault();
var $this = $(this),
animal = $this.data('animal');
$.ajax({
type: "post",
url: "getAnimal.php",
dataType: "html",
data: { pet : animal },
success: function(data) {
$("#results").html('').html(data);
}
});
});
});
getAnimal.php (PHP script called by AJAX)
<?php
$animal = $_POST['pet'];
if($animal == "cats") {
echo "You clicked on cats!";
}
else if($animal == "dogs") {
echo "You clicked on dogs!";
}
Are these links all in the same domain? If so, it's not too hard to fetch the content at each URL using jQuery's ajax API.

Using JavaScript in Polymer element

I have an object of polymer:
<newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;">
<span class="title">Utwórz nowy folder</span>
<input type="text" class="ginput" style="width: 350px; padding: 5px;" placeholder="Nowy katalog" />
<br />
<button class="action blue"><span class="label">Utwórz</span></button>
<button class="action red" id="cancelBtn"><span class="label">Anuluj</span></button>
<script type="text/javascript">
...
</script>
</newfolder-element>
I want to access dom elements in javascript, I tried this:
<script type="text/javascript">
Polymer('newfolderelement', {
domReady : function(){
$(this.shadowRoot.querySelector("#cancelBtn")).on('click', '#cancelBtn', function(){
console.log("clicked");
});
}
});
</script>
And this:
<script type="text/javascript>
$(this.shadowRoot.querySelector("#cancelBtn")).on('click', '#cancelBtn', function(){
console.log("clicked");
});
</script>
And this:
<script type="text/javascript>
$("#cancelBtn").click(function(){
console.log("clicked");
});
</script>
But all of above doesn't work. How to access dom elements inside polymer object ?
Why do you want to use jQuery, the Polymer already provides that functionality to you:
to access DOM elements use the $ map of the element, ie to get reference to the #cancelBtn use
this.$.cancelBtn
to add an eventhandler use declarative event mapping, ie to add an click handler to the button
<button class="action red" id="cancelBtn" on-click="{{cancelClicked}}"></button>
and just add method cancelClicked to your component's script section.
<script>
Polymer('newfolder-element', {
cancelClicked: function() {
// do something
}
});
</script>
This is much simpler and your component won't require additional library.

Categories

Resources