3

I have a jQuery function that is not working under Laravel and i think it just needs to be rewritten and declared differently.

This is the error that i get in browser: error

Under normal environment with jQuery 2.2.3 it works just fine like in Fiddle

and this is the source code:

// replace , with . and block writing letters
$.fn.ForceNumericOnly = function() {
        return this.each(function() {
      if($(this).data('forceNumericOnly')){ return; }
      $(this).data('forceNumericOnly', true);
            $(this).keydown(function(e) {
                if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
                    e.preventDefault(); 
                    $(this).val($(this).val() + '.');
                }
                    var key = e.charCode || e.keyCode || 0;
                    return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));                
            });
        });
};

// execute function on element focus
$(document).on('focus', '.amount', function(){
    $(this).ForceNumericOnly();
});

More info:

folder tree

routes.php file

routes.php

This is app.blade.php layout

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>

    <!-- Fonts -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css" integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700">

    <!-- Styles -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{-- <link href="{{ elixir('css/app.css') }}" rel="stylesheet"> --}}

    <style>
        body {
            font-family: 'Lato';
        }

        .fa-btn {
            margin-right: 6px;
        }
    </style>
</head>
<body id="app-layout">
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="navbar-header">

                <!-- Collapsed Hamburger -->
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                    <span class="sr-only">Toggle Navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <!-- Branding Image -->
                <a class="navbar-brand" href="{{ url('/') }}">
                    Secure
                </a>
            </div>

            <div class="collapse navbar-collapse" id="app-navbar-collapse">
                <!-- Left Side Of Navbar -->
                <ul class="nav navbar-nav">
                    @if (Auth::guest())
                        <li><a href="{{ url('/home') }}">Home</a></li>
                    @elseif (!Auth::guest() && Auth::user()->isAdmin())
                        <li><a href="{{ url('/home') }}">Home</a></li>
                        <li><a href="{{ url('admin') }}">Admin</a></li>
                        <li><a href="{{ url('anfrage') }}">Anfrage</a></li>
                        <li><a href="{{ url('angebote') }}">Angebote</a></li>
                    @elseif (!Auth::guest() && Auth::user()->isAgentur())
                        <li><a href="{{ url('/home') }}">Home</a></li>
                        <li><a href="{{ url('angebotmachen') }}">Angebot machen</a></li>
                        <li><a href="{{ url('anfrage') }}">Anfrage</a></li>
                    @elseif (!Auth::guest() && Auth::user()->isEndkunde())
                        <li><a href="{{ url('/home') }}">Home</a></li>
                        <li><a href="{{ url('anfragestellen') }}">Anfrage stellen</a></li>
                        <li><a href="{{ url('angebote') }}">Angebote</a></li>
                    @endif
                </ul>

                <!-- Right Side Of Navbar -->
                <ul class="nav navbar-nav navbar-right">
                    <!-- Authentication Links -->
                    @if (Auth::guest())
                        <li><a href="{{ url('/login') }}">Login</a></li>
                        <li><a href="{{ url('rgagenturen') }}">Register Agenturen</a></li>
                        <li><a href="{{ url('rgendkunden') }}">Register Endkunden</a></li>
                    @else
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                {{ Auth::user()->name }} <span class="caret"></span>
                            </a>

                            <ul class="dropdown-menu" role="menu">
                                <li><a href="{{ url('/logout') }}"><i class="fa fa-btn fa-sign-out"></i>Logout</a></li>
                            </ul>
                        </li>
                    @endif
                </ul>
            </div>
        </div>
    </nav>

    @yield('content')

    <!-- JavaScripts -->
    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
    {{-- <script src="{{ elixir('js/app.js') }}"></script> --}}
</body>
</html>

This is angebotmachen.blade.php

@extends('layouts.app')
@section('content')
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Angebot machen</div>

                <div class="panel-body">
{{ Form::open(array('url' => 'agentur/angebotmachen', 'method' => 'POST' )) }}
<table id="t1">
    <tr>
        <th><button type="button" class="addRow">Personal hinzuf&uuml;gen</button></th>
        <th>Anzahl</th>
        <th>Preis pro Stunde</th>
        <th>Stunden</th>
        <th>Total</th>
    </tr>
    <tr id="row0" class="item">
        <td>{{ Form::select('personal[]', array(
               'koeche' => 'K&ouml;che',
               'barkeeper' => 'Barkeeper',
               'garderobiere' => 'Garderobiere',
               'chauffeure' => 'Chauffeure',
               'oberkellner' => 'Oberkellner',
               'serviceleitung' => 'Serviceleitung',
               'hilfskoch' => 'Hilfskoch',
               'servicekraefte' => 'Servicekr&auml;fte',
               ), null, ['placeholder' => '--ausw&auml;hlen']) }}
       </td>
        <td><input name="anzahl[]" class="qnty amount" value="" type="number" min="0" step="1"></td>
        <td><input name="preisps[]" class="price amount" value=""></td>
        <td><input name="stunden[]" class="hours amount" value=""></td>
        <td><input name="total[]" class="total" value="" readonly="readonly" /></td>
    </tr>
</table>

<br />

<table id="t2">
  <tr>
    <th>Netto =<br></th>
    <th>{{ Form::text('netto', '', ['id' => 'netto', 'readonly' => 'readonly']) }}</th>
  </tr>
  <tr>
    <td>Steuer 19% =<br></td>
    <td>{{ Form::text('steuer', '', ['id' => 'steuer', 'readonly' => 'readonly']) }}</td>
  </tr>
  <tr>
    <td>Brutto =<br></td>
    <td>{{ Form::text('brutto', '', ['id' => 'brutto', 'readonly' => 'readonly']) }}</td>
  </tr>
</table>
    <br>
  {{ Form::submit('Submit') }}
  {{ Form::reset('Reset') }}
  {{ Form::close() }}

                </div>
            </div>
        </div>
    </div>
</div>

<script>  
// main function when page is opened
    $(document).ready(function () {
        // function for adding a new row
        var r = 0;
        $('.addRow').click(function () {
            r++;
            $('#t1').append('<tr id="row' + r + '" class="item"><td><select name="personal[]" class="select"><optgroup label="Personal"><option selected="true" disabled="true" style="display:none">--ausw&auml;hlen</option><option value="koeche">K&ouml;che</option><option value="barkeeper">Barkeeper</option><option value="garderobiere">Garderobiere</option><option value="chauffeure">Chauffeure</option><option value="oberkellner">Oberkellner</option><option value="serviceleitung">Serviceleitung</option><option value="hilfskoch">Hilfskoch</option><option value="servicekraefte">Servicekr&auml;fte</option></optgroup></select></td><td><input name="anzahl[]" class="qnty amount" value="" type="number" min="0" step="1"></td><td><input name="preisps[]" class="price amount" value=""></td><td><input name="stunden[]" class="hours amount" value=""></td><td><input name="total[]" class="total" value="" readonly="readonly"></td><td><button type="button" name="remove" id="' + r + '" class="btn_remove">X</button></td></tr>');
        });
        // remove row when X is clicked
        $(document).on("click", ".btn_remove", function () {
            var button_id = $(this).attr("id");
            $("#row" + button_id + '').remove();
        });

        // calculate everything
        $(document).on("keyup", ".amount", calcAll);

    });

    // function for calculating everything
    function calcAll(event) {
        // calculate total for one row
          $(".item").each(function () {
            var qnty = 1;
            var price = 1;
            var hours = 1;
            var total = 1;
            if (!isNaN(parseFloat($(this).find(".qnty").val()))) {
                qnty = parseFloat($(this).find(".qnty").val());
            }
            if (!isNaN(parseFloat($(this).find(".price").val()))) {
                price = parseFloat($(this).find(".price").val());
            }
            if (!isNaN(parseFloat($(this).find(".hours").val()))) {
                hours = parseFloat($(this).find(".hours").val());
            }
            total = qnty * price * hours;
            $(this).find(".total").val(total.toFixed(2));
        });


        // sum all totals
        var sum = 0;
        $(".total").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                sum += parseFloat(this.value);
            }
        });

        // show values in netto, steuer, brutto fields
        $("#netto").val(sum.toFixed(2));
        $("#steuer").val(parseFloat(sum * 0.19).toFixed(2));
        $("#brutto").val(parseFloat(sum + parseFloat(($("#steuer").val()))).toFixed(2));

    }

    // replace , with . and block writing letters
    $.fn.ForceNumericOnly = function() {
            return this.each(function() {
          if($(this).data('forceNumericOnly')){ return; }
          $(this).data('forceNumericOnly', true);
                $(this).keydown(function(e) {
                    if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
                        e.preventDefault(); 
                        $(this).val($(this).val() + '.');
                    }
                        var key = e.charCode || e.keyCode || 0;
                        return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));                
                });
            });
    };
    // execute function on element focus
    $(document).on('focus', '.amount', function(){
        $(this).ForceNumericOnly();
    });

</script>
@endsection
2
  • 1
    Could you provide some more info such as how this is actually loaded into the view? Commented May 17, 2016 at 21:22
  • I have added more info to my question Commented May 17, 2016 at 21:48

1 Answer 1

1

You're loading jQuery twice, which is causing conflicts/errors.

You're loading it first in app.blade.php just before your </body> tag, and again in angebotmachen.blade.php.

The two jQuery libraries are conflicting, which is causing your issue.

You also need to load the jQuery library before you use:

$(document).ready(function () { 
    // etc
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.