Use jQuery to insert the TEXT heading as an input value

Can anyone help me with copying text from a heading to an input value? Here's an example:

<h2 class="customTitleHead">This is a Heading</h2>

I want to transfer the text from the heading into an input field like this:

<input type="text" value="" name="rProvider" class="rr_small_input" />

The desired output should be the text from the heading inside the input value:

<input type="text" value="This is a Heading" name="rProvider" class="rr_small_input" />

I've attempted to use the following code, but my input remains empty:

jQuery(function () {
  jQuery(".rr_small_input[name='rProvider']").val(jQuery("h2.customTitleHead").val());
});

Answer №1

val() retrieves or updates the value attribute of certain elements like input, select, textarea, and progress. It's important to note that the H2 element does not have a value attribute. To extract the inner text of an element, you can use the text() method.

jQuery(".rr_small_input[name='rProvider']").val(jQuery("h2.customTitleHead").text());

Answer №2

.val() is specifically designed to retrieve values from input, select, textarea, and progress elements, as these are the only ones with a value property. For all other elements, including custom ones, you should use jQuery's .text() method:

jQuery("h2.customTitleHead").text();

Answer №3

<h2 id='myHeader' class="customTitleHead">Welcome to the Jungle</h2>
<input id='myInput' type="text" value="Welcome to the Jungle" name="rProvider" class="rr_small_input" />


<script>
    jQuery(document).ready(function() {
        $('#myInput').val($('#myHeader').val());
    });
</script>

Answer №4

Here is my preferred method:

$('input').val($('.customTitleHead').html())

This code snippet grabs the content within the .customTitleHead class and sets it as the value of the input. It's a straightforward process.

Keep in mind: You have the option to use .text() instead of .html(), although I personally prefer using .html()

VIEW LIVE DEMO


If you need to target a specific input, refer to it by its class rather than just using input. For example:

$('.specific_input_class').val($('.customTitleHead').html())

ANOTHER DEMO HERE

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

Retrieve the value of a JSON array containing only a single object using jQuery

In my project, I have a jQuery file and a PHP file. If the PHP file successfully completes the process, it returns the value 2 using `echo json_encode(2)`. I am able to catch this value in the jQuery file and display a string on an HTML div without any iss ...

Are these objects enclosed within a JavaScript array?

Are square brackets used to define arrays and curly brackets used for objects? Can you explain the following data structure: Some.thing = [ { "swatch_src" : "/images/91388044000.jpg", "color" : "black multi", "inventory" : { "F" : [ 797113, 797 ...

Struggling to pass express.js router requests and responses to a class method

I am struggling with setting up an Express JS router. I am facing difficulty passing req and res to my class method. Not Working app.get('/', controller.index) Working app.get('/', (res,req) => controller.index(req,res) The routi ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

"Creating a link to a button with the type of 'submit' in HTML - a step-by-step

Found the solution on this interesting page: In a list, there's a button: <form> <ul> <li> <a href="account.html" class="button"> <button type="submit">Submit</button> ...

Stripping the prefix from a string using the .split function leads to an error message stating "Unexpected

When dealing with a string containing a unique prefix, I attempted to separate it into an array after the backslash character "\" by using the split function. Here is the string: i:0#.w|itun\allepage_fg This was my approach: function claimOrder ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...

What is the best way to populate nested elements with jQuery?

I am trying to showcase the latest NEWS headlines on my website by populating them using Jquery. Despite writing the necessary code, I am facing an issue where nothing appears on the webpage. Below is the HTML code snippet: <div class="col-md-4"> ...

The Service Worker seems to be neglecting to serve the sub-pages at

I've successfully implemented a service worker on my website. The home page loads correctly from the Service Worker cache, and when I visit previously viewed 'posts' while online in Chrome, they load and show as 'from ServiceWorker&apos ...

Trigger an event, pause, and subsequently trigger another one within Vue

I have successfully emitted the following events to the parent component: this.$emit('sendToParent1', true); this.$emit('sendToParent2'); this.$emit('sendToParent3'); this.$emit('sendToParent4', true); this.$emit(&ap ...

Adjust the text according to the selected checkbox option

I am attempting to update the displayed text based on whether a checkbox is currently checked or not. The value of the viewable text should reflect the user's selection. I believe I am close, but the functionality is not working as expected. <html ...

Retrieving a variable value from an AJAX call for external use

Looking for a solution to pass the generated JSON response from an ASMX web service accessed via AJAX to an outside variable in another function. Below is the code snippet for reference: function setJsonSer() { var strWsUrl = &apo ...

Injecting jQuery into dynamically loaded contentORLoading jQuery within

Is it necessary to call jQuery again when loading content via ajax that contains additional ajax interactions? Should scripts/plugins specific to the loaded content be called only within the loaded content or in the parent file? Appreciate your response! ...

Invalid label detected - Syntax Error in the response from Jsonp/Ajax!

I have a snippet of code that I'm having trouble with. It's shown below: <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script type="text/javascript"> jQuery.getJSO ...

I am facing difficulty in getting React to recognize the third-party scripts I have added to the project

I am currently working my way through the React Tutorial and have encountered a stumbling block. Below is the HTML markup I am using: <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=devi ...

Step-by-step guide on utilizing the .change method in order to deactivate a

Can someone help me with a quick solution for this issue? I need to know how to disable a select option once the value has been changed. The option should be available on initial load, but after the user selects it for the first time, it should be disable ...

After upgrading from Vuetify version 1.5 to 2.0.18, an issue arises with modules not being found

I encountered the following error: module not found error To address this issue, I took the following steps: Commented out import 'vuetify/src/stylus/main.styl' in the src/plugins/vuetify.js file. Added import 'vuetify/src/styles/main. ...

Which is more effective: using the try-catch pattern or the error-first approach

My main focus is on node.js and express.js, although I am relatively new to JavaScript overall. When it comes to error handling, the official recommendation is to use the try-catch pattern. However, some developers argue in favor of sticking with the tradi ...

Issue with bootstrap 4 CDN not functioning on Windows 7 operating system

No matter what I do, the CDN for Bootstrap 4 just won't cooperate with Windows 7. Oddly enough, it works perfectly fine on Windows 8. Here is the CDN link that I'm using: <!doctype html> <html lang="en> <head> <!-- Req ...

Endless loop issue in Reactjs encountered when utilizing React Hooks

Delving into React Hooks as a newcomer, I encountered an error that has me stumped. The console points to an infinite loop in the code but I can't pinpoint the exact line responsible. Too many re-renders. React limits the number of renders to prevent ...