Raja Abbas Raja Abbas - 3 years ago 151
HTML Question

Laravel - Javascript work in JSFiddle but not in blade

I am trying to build a form and output its values in JSON format which I intend to shoot off to my controller.

I am using this script in JSFiddle and it works fine but not inside my blade template. I am not sure what is wrong. When I hit the submit button, it automatically adds values to the url rather then showing them in the box below the form.

Here is the code:

https://jsfiddle.net/sba0va3g/

HTML

<section class="content">
<h1 class="content__heading">Send Me a Message</h1>
<p class="content__lede">Use this handy contact form to get in touch with me.</p>
<form class="content__form contact-form">
<div class="contact-form__input-group">
<input class="contact-form__input contact-form__input--radio" id="salutation-mr" name="salutation" type="radio" value="Mr."/>
<label class="contact-form__label contact-form__label--radio" for="salutation-mr">Mr.</label>
<input class="contact-form__input contact-form__input--radio" id="salutation-mrs" name="salutation" type="radio" value="Mrs."/>
<label class="contact-form__label contact-form__label--radio" for="salutation-mrs">Mrs.</label>
<input class="contact-form__input contact-form__input--radio" id="salutation-ms" name="salutation" type="radio" value="Ms."/>
<label class="contact-form__label contact-form__label--radio" for="salutation-ms">Ms.</label>
</div>
<div class="contact-form__input-group">
<label class="contact-form__label" for="name">Full Name</label>
<input class="contact-form__input contact-form__input--text" id="name" name="name" type="text"/>
</div>
<div class="contact-form__input-group">
<label class="contact-form__label" for="email">Email Address</label>
<input class="contact-form__input contact-form__input--email" id="email" name="email" type="email"/>
</div>
<div class="contact-form__input-group">
<label class="contact-form__label" for="subject">How can I help you?</label>
<select class="contact-form__input contact-form__input--select" id="subject" name="subject">
<option>I have a problem.</option>
<option>I have a general question.</option>
</select>
</div>
<div class="contact-form__input-group">
<label class="contact-form__label" for="message">Enter a Message</label>
<textarea class="contact-form__input contact-form__input--textarea" id="message" name="message" rows="6" cols="65"></textarea>
</div>
<div class="contact-form__input-group">
<p class="contact-form__label--checkbox-group">Please send me:</p>
<input class="contact-form__input contact-form__input--checkbox" id="snacks-pizza" name="snacks" type="checkbox" value="pizza"/>
<label class="contact-form__label contact-form__label--checkbox" for="snacks-pizza">Pizza</label>
<input class="contact-form__input contact-form__input--checkbox" id="snacks-cake" name="snacks" type="checkbox" value="cake"/>
<label class="contact-form__label contact-form__label--checkbox" for="snacks-cake">Cake</label>
</div>
<input name="secret" type="hidden" value="1b3a9374-1a8e-434e-90ab-21aa7b9b80e7"/>
<!--<button class="contact-form__button" type="submit">Send It!</button>-->
<input type="submit" name="submit">
</form>
</section>
<div class="results">
<h2 class="results__heading">Form Data</h2>
<pre class="results__display-wrapper"><code class="results__display"></code></pre>
</div>


Javascript

<script type="text/javascript">
'use strict';

/**
* Checks that an element has a non-empty `name` and `value` property.
* @param {Element} element the element to check
* @return {Bool} true if the element is an input, false if not
*/
var isValidElement = function isValidElement(element) {
return element.name && element.value;
};

/**
* Checks if an element’s value can be saved (e.g. not an unselected checkbox).
* @param {Element} element the element to check
* @return {Boolean} true if the value should be added, false if not
*/
var isValidValue = function isValidValue(element) {
return !['checkbox', 'radio'].includes(element.type) || element.checked;
};

/**
* Checks if an input is a checkbox, because checkboxes allow multiple values.
* @param {Element} element the element to check
* @return {Boolean} true if the element is a checkbox, false if not
*/
var isCheckbox = function isCheckbox(element) {
return element.type === 'checkbox';
};

/**
* Checks if an input is a `select` with the `multiple` attribute.
* @param {Element} element the element to check
* @return {Boolean} true if the element is a multiselect, false if not
*/
var isMultiSelect = function isMultiSelect(element) {
return element.options && element.multiple;
};

/**
* Retrieves the selected options from a multi-select as an array.
* @param {HTMLOptionsCollection} options the options for the select
* @return {Array} an array of selected option values
*/
var getSelectValues = function getSelectValues(options) {
return [].reduce.call(options, function (values, option) {
return option.selected ? values.concat(option.value) : values;
}, []);
};

/**
* A more verbose implementation of `formToJSON()` to explain how it works.
*
* NOTE: This function is unused, and is only here for the purpose of explaining how
* reducing form elements works.
*
* @param {HTMLFormControlsCollection} elements the form elements
* @return {Object} form data as an object literal
*/
var formToJSON_deconstructed = function formToJSON_deconstructed(elements) {

// This is the function that is called on each element of the array.
var reducerFunction = function reducerFunction(data, element) {

// Add the current field to the object.
data[element.name] = element.value;

// For the demo only: show each step in the reducer’s progress.
console.log(JSON.stringify(data));

return data;
};

// This is used as the initial value of `data` in `reducerFunction()`.
var reducerInitialValue = {};

// To help visualize what happens, log the inital value, which we know is `{}`.
console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));

// Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
var formData = [].reduce.call(elements, reducerFunction, reducerInitialValue);

// The result is then returned for use elsewhere.
return formData;
};

/**
* Retrieves input data from a form and returns it as a JSON object.
* @param {HTMLFormControlsCollection} elements the form elements
* @return {Object} form data as an object literal
*/
var formToJSON = function formToJSON(elements) {
return [].reduce.call(elements, function (data, element) {

// Make sure the element has the required properties and should be added.
if (isValidElement(element) && isValidValue(element)) {

/*
* Some fields allow for more than one value, so we need to check if this
* is one of those fields and, if so, store the values as an array.
*/
if (isCheckbox(element)) {
data[element.name] = (data[element.name] || []).concat(element.value);
} else if (isMultiSelect(element)) {
data[element.name] = getSelectValues(element);
} else {
data[element.name] = element.value;
}
}

return data;
}, {});
};

/**
* A handler function to prevent default submission and run our custom script.
* @param {Event} event the submit event triggered by the user
* @return {void}
*/
var handleFormSubmit = function handleFormSubmit(event) {

// Stop the form from submitting since we’re handling that with AJAX.
event.preventDefault();

// Call our function to get the form data.
var data = formToJSON(form.elements);

// Demo only: print the form data onscreen as a formatted JSON object.
var dataContainer = document.getElementsByClassName('results__display')[0];

// Use `JSON.stringify()` to make the output valid, human-readable JSON.
dataContainer.textContent = JSON.stringify(data, null, " ");

// ...this is where we’d actually do something with the form data...
};

/*
* This is where things actually get started. We find the form element using
* its class name, then attach the `handleFormSubmit()` function to the
* `submit` event.
*/
var form = document.getElementsByClassName('contact-form')[0];
form.addEventListener('submit', handleFormSubmit);
</script>


Layout Template

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

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">

<title>{{ config('app.name', 'Laravel') }}</title>

<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<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('/') }}">
{{ config('app.name', 'Laravel') }}
</a>
</div>

<div class="collapse navbar-collapse" id="app-navbar-collapse">
<!-- Left Side Of Navbar -->
<ul class="nav navbar-nav">
@auth
<li><a href="{{ route('leads') }}">Leads</a></li>
@endauth
</ul>

<!-- Right Side Of Navbar -->
<ul class="nav navbar-nav navbar-right">
<!-- Authentication Links -->
@guest
<li><a href="{{ route('login') }}">Login</a></li>
<li><a href="{{ route('register') }}">Register</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="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>

<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
@endguest
</ul>
</div>
</div>
</nav>

@yield('content')
</div>

<!-- Scripts -->
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Answer Source

Can you change app.blade.php to this code

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

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div id="app">
        <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('/') }}">
                        {{ config('app.name', 'Laravel') }}
                    </a>
                </div>

                <div class="collapse navbar-collapse" id="app-navbar-collapse">
                    <!-- Left Side Of Navbar -->
                    <ul class="nav navbar-nav">
                        @auth
                        <li><a href="{{ route('leads') }}">Leads</a></li>
                        @endauth
                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="nav navbar-nav navbar-right">
                        <!-- Authentication Links -->
                        @guest
                            <li><a href="{{ route('login') }}">Login</a></li>
                            <li><a href="{{ route('register') }}">Register</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="{{ route('logout') }}"
                                            onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                            Logout
                                        </a>

                                        <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                            {{ csrf_field() }}
                                        </form>
                                    </li>
                                </ul>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        @yield('content')
    </div>

    <!-- Scripts -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script src="{{ asset('js/app.js') }}"></script>
@stack('scripts')
</body>
</html>

And in your blade section you can add jquerey

   @push('scripts')
<script type="text/javascript">
'use strict';

/**
 * Checks that an element has a non-empty `name` and `value` property.
 * @param  {Element} element  the element to check
 * @return {Bool}             true if the element is an input, false if not
 */
var isValidElement = function isValidElement(element) {
  return element.name && element.value;
};

/**
 * Checks if an element’s value can be saved (e.g. not an unselected checkbox).
 * @param  {Element} element  the element to check
 * @return {Boolean}          true if the value should be added, false if not
 */
var isValidValue = function isValidValue(element) {
  return !['checkbox', 'radio'].includes(element.type) || element.checked;
};

/**
 * Checks if an input is a checkbox, because checkboxes allow multiple values.
 * @param  {Element} element  the element to check
 * @return {Boolean}          true if the element is a checkbox, false if not
 */
var isCheckbox = function isCheckbox(element) {
  return element.type === 'checkbox';
};

/**
 * Checks if an input is a `select` with the `multiple` attribute.
 * @param  {Element} element  the element to check
 * @return {Boolean}          true if the element is a multiselect, false if not
 */
var isMultiSelect = function isMultiSelect(element) {
  return element.options && element.multiple;
};

/**
 * Retrieves the selected options from a multi-select as an array.
 * @param  {HTMLOptionsCollection} options  the options for the select
 * @return {Array}                          an array of selected option values
 */
var getSelectValues = function getSelectValues(options) {
  return [].reduce.call(options, function (values, option) {
    return option.selected ? values.concat(option.value) : values;
  }, []);
};

/**
 * A more verbose implementation of `formToJSON()` to explain how it works.
 *
 * NOTE: This function is unused, and is only here for the purpose of explaining how
 * reducing form elements works.
 *
 * @param  {HTMLFormControlsCollection} elements  the form elements
 * @return {Object}                               form data as an object literal
 */
var formToJSON_deconstructed = function formToJSON_deconstructed(elements) {

  // This is the function that is called on each element of the array.
  var reducerFunction = function reducerFunction(data, element) {

    // Add the current field to the object.
    data[element.name] = element.value;

    // For the demo only: show each step in the reducer’s progress.
    console.log(JSON.stringify(data));

    return data;
  };

  // This is used as the initial value of `data` in `reducerFunction()`.
  var reducerInitialValue = {};

  // To help visualize what happens, log the inital value, which we know is `{}`.
  console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));

  // Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
  var formData = [].reduce.call(elements, reducerFunction, reducerInitialValue);

  // The result is then returned for use elsewhere.
  return formData;
};

/**
 * Retrieves input data from a form and returns it as a JSON object.
 * @param  {HTMLFormControlsCollection} elements  the form elements
 * @return {Object}                               form data as an object literal
 */
var formToJSON = function formToJSON(elements) {
  return [].reduce.call(elements, function (data, element) {

    // Make sure the element has the required properties and should be added.
    if (isValidElement(element) && isValidValue(element)) {

      /*
       * Some fields allow for more than one value, so we need to check if this
       * is one of those fields and, if so, store the values as an array.
       */
      if (isCheckbox(element)) {
        data[element.name] = (data[element.name] || []).concat(element.value);
      } else if (isMultiSelect(element)) {
        data[element.name] = getSelectValues(element);
      } else {
        data[element.name] = element.value;
      }
    }

    return data;
  }, {});
};

/**
 * A handler function to prevent default submission and run our custom script.
 * @param  {Event} event  the submit event triggered by the user
 * @return {void}
 */
var handleFormSubmit = function handleFormSubmit(event) {

  // Stop the form from submitting since we’re handling that with AJAX.
  event.preventDefault();

  // Call our function to get the form data.
  var data = formToJSON(form.elements);

  // Demo only: print the form data onscreen as a formatted JSON object.
  var dataContainer = document.getElementsByClassName('results__display')[0];

  // Use `JSON.stringify()` to make the output valid, human-readable JSON.
  dataContainer.textContent = JSON.stringify(data, null, "  ");

  // ...this is where we’d actually do something with the form data...
};

/*
 * This is where things actually get started. We find the form element using
 * its class name, then attach the `handleFormSubmit()` function to the 
 * `submit` event.
 */
var form = document.getElementsByClassName('contact-form')[0];
form.addEventListener('submit', handleFormSubmit);
</script>

@endpush
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download