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 = '/'; //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 = '/'; //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="/">
Why am I failing writing text field's value
attribute? How can I write actually?
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./'; //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./'; //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./">
Why am I failing writing text field's value
attribute? How can I write actually?
-
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 );
– Satpal Commented May 11, 2015 at 11:58 - 1 @Satpal please make it an answer. It's THE answer. :) – Mayeenul Islam Commented May 11, 2015 at 11:59
4 Answers
Reset to default 2The 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);
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);
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.
This will work:
$("#show-val").attr("value",url);