Reputation: 4762
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?
Upvotes: 0
Views: 10058
Reputation: 6732
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);
Upvotes: 2
Reputation: 31749
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.
Upvotes: 0
Reputation: 133403
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);
Upvotes: 1