March 18, 2012

How do I add text inside of an input field using jQuery?

Question by John Anderson

This should be easy, but nothing seems to work. I have a jQuery function that contains two parameters. The first parameter (pageID) is supposed to be inserted into a hidden field. It works correctly. I want the second parameter to be inserted into an html input field. That is, I want to see the contents of the parameter ‘pageName’ inside the form field as if I had just typed it in myself. Here is the code:

function insertIntoHiddenField(pageID,pageName)
{
    $('input[name=page_id]').val(pageID);
    $('input[name=page_name]').val(pageName);
}

When I look at the source code, I find that the value attribute in the input tag contains the value from the parameter ‘pageName’. But, the input field itself is empty. I want to see that value in the input field. What am I doing wrong?

By the way, I also tried (without success) the following:

$('input[name=page_name]').text(pageName);
$('input[name=page_name]').innerhtml(pageName);
$('input[name=page_name]').append(pageName);

Answer by Starx

Give an id to the hidden element. Just to be on the safe side and use .val()

$('#page_name').val('newtext');
$('#page_id').val('newtext');

Demo

However, your method works perfectly for me. Check here

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!