-2

I am trying to get the value from the first name input and pass it to the bootstrap alert when the user clicks the submit button, but can't manage to do that.

Here is my snippet:

$(document).ready(function() {
  $("#submit-button").click(function() {
    $("#myAlert").show("fade"), $("#fname").attr("value");
    event.preventDefault();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name..">

<div id="myAlert" class="alert alert-success collapse">
  <a href="#" class="close" data-dismiss="alert">&times;</a>Thank you for contacting us,
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • 2
    Wherre is fname? – Ibu Jun 19 '19 at 23:04
  • Possible duplicate of [Get the value in an input text box](https://stackoverflow.com/questions/4088467/get-the-value-in-an-input-text-box) – Bosco Jun 19 '19 at 23:07
  • 1
    You cannot separate commands with a `,` in Javascript. Next, `$("#fname").attr("value")` only **gets** the value **attribute** of that element (a) you want the property, not the attribute (which holds only the initial value), b) you want to do something with the value you got). – connexo Jun 19 '19 at 23:38

1 Answers1

0

I assume you wish to use the input value to complete the Bootstrap's alert text...

You will need an element to place that value in I suggest a span. Use the .val() method to get the input value... Then .text() to insert it in the span.

$(document).ready(function() {
  $("#submit-button").click(function() {
    $("#firstName").text($("#fname").val()); // Use the input's value for the span's text
    $("#myAlert").show("fade");  // Show the Bootstrap's alert
    event.preventDefault();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

Enter your first name: <input id="fname"><br>
<button id="submit-button">Submit</button>
<div id="myAlert" class="alert alert-success collapse">
  <a href="#" class="close" data-dismiss="alert">&times;</a>Thank you for contacting us, <span id="firstName"></span>
</div>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64