简体   繁体   中英

Get value from input jQuery

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM