Enhance Your Forms with Bootstrap 4 Input Extension

I've been struggling to create a form with Bootstrap 4, specifically setting the value in an input text client-side for a modal form. No matter what I try, it just doesn't seem to work...

Here is the form:

$('#contact-modal').on('show.bs.modal', function() {
    alert("prima");
    $("#name").attr({
      "value": 'ëtestí'
    });
  })
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#contact-modal">
  modal
</button>

<div id="contact-modal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <a class="close" data-dismiss="modal">◊</a>
        <h3>Contact Form</h3>
      </div>
      <form id="contactForm" name="contact" role="form">
        <div class="modal-body">
          <div class="form-group">
            <label for="name">Name</label>
            <input type="text" name="name" class="form-control">
          </div>
          <div class="form-group">
            <label for="email">Email</label>
            <input type="email" name="email" class="form-control">
          </div>
          <div class="form-group">
            <label for="message">Message</label>
            <textarea name="message" class="form-control"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <input type="submit" class="btn btn-success" id="submit">
        </div>
      </form>
    </div>
  </div>
</div>

The code snippet that's causing trouble:

  $('#contact-modal').on('hide.bs.modal', function () {
    alert("First message!");
    $("#name").attr({
      "value": 'Test Value'
    });
}) 

If anyone has any suggestions or solutions, please let me know. Thanks!

Answer №1

Make sure to focus on selecting the input element by its name:

<script>
    $('#contact-modal').on('show.bs.modal', function() {
        alert("First step");
        $("input[name='name']").val("Testing");
    })
</script>

Answer №2

Give it a shot this way

<script>
$('#contact-modal').on('show.bs.modal', function() {
    alert("first");
    $("#name").val("sample text")
})
</script>

Answer №3

The main idea is that using .attr(...) retrieves the object's value only at the beginning (when the HTML is generated). On the other hand, val() obtains the property value of the object, which can be modified multiple times.

Consider the following code snippet:

<script>
$('#contact-modal').on('show.bs.modal', function() {
    alert("before");
    $("#name").val("example")
})
</script>

Answer №4

Here are the issues found:

  • The attr method should use two parameters ("key", value) instead of an object ({key: value})
  • To change the values of form elements, it is recommended to use jQuery's val() method
  • The jQuery selector used ("#name") does not exist. There is an input with a name attribute but not with an id="name". To fix this, either add an id="name" to the input element or change the jQuery selector to ("[name=name]")
  • The value ëtestí is not a string and there is no variable with that name. This might be due to copy-paste errors.
  • Your HTML markup has a slight issue: The for attribute of the label element should target the id attribute, not the name attribute. This could lead to accessibility problems. Consider adding an appropriate id attribute to the label or wrapping the label around the form element

All these changes have been incorporated into this snippet

$('#contact-modal').on('show.bs.modal', function() {
  $("[name=name]").val("ëtestí");
})
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#contact-modal">
  modal
</button>

<div id="contact-modal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <a class="close" data-dismiss="modal">◊</a>
        <h3>Contact Form</h3>
      </div>
      <form id="contactForm" name="contact" role="form">
        <div class="modal-body">
          <div class="form-group">
            <label for="contactForm-name">Name</label>
            <input type="text" id="contactForm-name" name="name" class="form-control">
          </div>
          <div class="form-group">
            <label for="contactForm-email">Email</label>
            <input type="email"id="contactForm-email" name="email" class="form-control">
          </div>
          <div class="form-group">
            <label for="contactForm-message">Message</label>
            <textarea id="contactForm-message" name="message" class="form-control"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <input type="submit" class="btn btn-success" id="submit">
        </div>
      </form>
    </div>
  </div>
</div>

Answer №5

When using JQuery:

Use # for id $('#myid'),

<input type="text" id="myid" />

Use . for class $('.myclass'),

<input type="text" class="myclass" />

If id and class are not given, then use other attributes

For example: $("[name=myname]") or $("input[name=myname]")

<input type="text" name="myname" />

For $("input[type=text]") <input type="text" />

$('#contact-modal').on('show.bs.modal', function() {
   $("input[name=name]").val('ëtestí');
 });
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#contact-modal">
  modal
</button>

<div id="contact-modal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <a class="close" data-dismiss="modal">◊</a>
        <h3>Contact Form</h3>
      </div>
      <form id="contactForm" name="contact" role="form">
        <div class="modal-body">
          <div class="form-group">
            <label for="name">Name</label>
            <input type="text" name="name" class="form-control">
          </div>
          <div class="form-group">
            <label for="email">Email</label>
            <input type="email" name="email" class="form-control">
          </div>
          <div class="form-group">
            <label for="message">Message</label>
            <textarea name="message" class="form-control"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <input type="submit" class="btn btn-success" id="submit">
        </div>
      </form>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can state be controlled by both the parent and children within the same element?

I am facing a situation where I have a component that requires updating the value from its parent, but also needs to handle user input changes without having to pass them back to the parent. See this scenario in action with this example: https://codesandbo ...

Is it possible to set a value for a jQuery function after the function has

I am a beginner when it comes to javascript & jQuery. I am currently working on a feature for my website where users can display badges they have earned on their own site by simply copying and pasting a bit of code that I provide. Although the javascript p ...

Ways to display the success value prior to the completion of AJAX jQuery from the PHP page

Here is the AJAX code I am using: $(".content").empty(); $.ajax({ type: 'POST', url: 'xyz.php', data: $('.chk:checked').serialize(), success: function(data) { $(".content").append(data); } }); M ...

jQuery's making an error here - looks like matchExpr[type].exec is missing in action

Today, I encountered an error while running my code. Despite searching for guidance online, resources that could help me were hard to come by. Specifically, after crafting a few JavaScript functions, any attempt to use jQuery's methods on selectors r ...

Adjust the size and alignment of columns within a Bootstrap table by incorporating a nested table

My goal is to adjust the size and alignment of the header components within the thead section of an HTML table to match those of a nested table. The main table handles the alternating row colors, while the nested table enables me to organize the fields ac ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

Do my Dash tutorials appear drastically different from the documentation? Is this normal?

As an experienced back-end engineer, I am delving into the world of browser-based GUI design for the first time, specifically with HTML, CSS, and more. My current project involves building a dashboard using Dash, and I am in the early stages of familiarizi ...

Trouble with initializing the Ionic map controller

I have a mobile app with 5 tabs, one of which features a map. However, the map only loads when directly accessed through the URL bar. It seems that the controller is not loaded when navigating to the map tab through the app, as indicated by console logs. S ...

Emphasize the engaged menu selection when the page is refreshed

My application is a dashboard app built with React, Redux, and Antdesign. I utilized the layout provided by Ant design at https://ant.design/components/layout/. One issue I encountered is that when clicking on side menus, the active menu gets bold but upo ...

What is the reason IE7 does not recognize these two strings as equal?

My event handler is designed to remove an element from a list if the corresponding checkbox is unchecked. When the checkbox is clicked, I first capture the value of the label associated with it: var label = $(this).next().html(); Next, I loop through the ...

Cannot utilize remote.require() in TypeScript due to compatibility issues

Recently, I've been facing a frustrating issue while developing an Electron application in TypeScript. I've been trying to execute a module from a renderer process using the code snippet below: import { remote } from 'electron' const ...

Determine if I'm actively typing in the input field and alter the loader icon accordingly with AngularJS

Just delving into the world of AngularJS and attempting to tweak an icon as I type in an input box. Currently, I can detect when the box is focused using the following code: $scope.loading = false; $scope.focused = function() { console.log("got ...

Despite setting the necessary Access-Control-Allow-* headers, the CORS ajax call still encounters a failure

My ajax call from a third-party-hosted script to my endpoint is encountering some issues. In Chrome, the preflight call appears as follows: GENERAL Request URL: https://my_endpoints_url Request Method: OPTIONS Status Code: 200 Remote Address: 21.188.37.1 ...

When using momentJs to add days, it will return a moment object rather than a

How can I add 7 days to a date using momentJs in my Angular project? let startDate = "2018-08-16T02:00:00.242Z"; let newDate = moment(startDate).add(7, 'days'); I was expecting to receive the date after adding 7 days, but instead I get a momen ...

Unique style pattern for parent links with both nested and non-nested elements

I am in the process of designing a website and I have a specific vision for how I want my links to appear, but I am unsure of how to achieve it. Here is the desired outcome: a red link a green link a red link a green link … Below is the HTM ...

Setting up automatic live reloading and assets compiling using Webpack in a Drupal project: A step-by-step guide

I've successfully configured Webpack to compile Sass and JavaScript in my Drupal custom theme named amazon. The styles.scss and index.js files are compiled from the assets/scss/ and assets/js/ folders respectively, into styles.css and index.js in the ...

Guide to iterating through a JSON object

Initially, I expected a simple question but it's proving to be more challenging than I thought. To provide some context, there is a JSON string returned from the server located within data.occupation. {"occupation": "Boxer", "id": 2},{"occupation": " ...

Creating dynamically-sized arrays in Node.js and using them as response payloads

Hello, I am struggling with populating an empty array with data from a mongo query using a forEach loop in JavaScript. I have been working on this for the past four days and despite my efforts, I can't seem to get it right. As a beginner in JavaScript ...

Passing parameters from a div to a single page component in Vue.js: A complete guide

There is code that appears on multiple pages: <div id="contact-us" class="section md-padding bg-grey"> <div id="contact"></div> <script src="/dist/build.js"></script> </div> Included in main.js is: im ...

NameError: The 'find_all' attribute cannot be found in the object of type 'NavigableString' (AttributeError)

import requests from bs4 import BeautifulSoup url=("http://finance.naver.com/news/mainnews.nhn") r=requests.get(url) soup=BeautifulSoup(r.content) a_data = soup.find_all("li",{"class":"block1"}) for item in a_data: print item.contents[0].find_all("d ...