0

I have an input field, input type text:

<input type="text" id="show-val" value="">
<button id="get-val">Val</button>

On button click it's taking a URL from somewhere else, I need to place the value into the text field's value attribute.

What I could is:

$('#get-val').on('click', function(){
    var url = 'http://example.com/'; //suppose this is our grabbed URL
    $('#show-val').val( url );
});

But if you inspect the input text then can see it's not writing the url into the value attribute, it's just pasting the value into the text field.

What I tried:

$('#get-val').on('click', function(){
    var url = 'http://example.com/'; //suppose this is our grabbed URL
    $('#show-val').prop( 'value', url ); //failed
    $('#show-val').prop( 'placeholder', url ); //passed
});

Output is:

<input type="text" id="show-val" value placeholder="http://example.com/">

Why am I failing writing text field's value attribute? How can I write actually?

2
  • 1
    value is a property so $('#show-val').val( url ); is correct, However if you want to modify the value attribute the use $('#show-val').attr( 'value', url ); Commented May 11, 2015 at 11:58
  • 1
    @Satpal please make it an answer. It's THE answer. :) Commented May 11, 2015 at 11:59

4 Answers 4

2

The prop() function is used to set values for attributes like checked, disabled. You should use val() or attr() functions for setting values in HTML form fields.

Examples:

$('input#show-val').val(url);

or

$('input#show-val').attr('value', url);
Sign up to request clarification or add additional context in comments.

Comments

1

Value is a property so $('#show-val').val(url); is correct.

However if you want to modify the value attribute the use $.fn.attr( attributeName, value)

Set one or more attributes for the set of matched elements.

Code

$('#show-val').attr('value', url);

Comments

0

You can set the value attribute by -

$('#show-val').attr('value', url );

But

$('#show-val').val( url );

also set the value but not the way you want.

Comments

0

This will work:

$("#show-val").attr("value",url);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.