I had thought these two were the same, but they appear to not be. I've generally been using $obj.attr("value") to work with form fields, but on the page I'm currently building, $obj.attr("value") does not return the text I enter in my field. However, $obj.val() does.
On a different page I've built, both $obj.attr("value") and $obj.val() return the text entered in the form field.
What could account for $obj.attr("value") working as expected in one case but not in another?
What is the proper way to set and retrieve a form field's value using jQuery?
There is a big difference between an objects properties and an objects attributes
See this questions (and its answers) for some of the differences: .prop() vs .attr()
The gist is that .attr(...) is only getting the objects value at the start (when the html is created). val() is getting the object's property value which can change many times.
Since jQuery 1.6, attr() will return the original value of an attribute (the one in the markup itself). You need to use prop() to get the current value:
var currentValue = $obj.prop("value");
However, using val() is not always the same. For instance, the value of <select> elements is actually the value of their selected option. val() takes that into account, but prop() does not. For this reason, val() is preferred.
PS: This is not an answer but just a supplement to the above answers.
Just for the future reference, I have included a good example that might help us to clear our doubt:
Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected:
The HTML code is below:
<html>
<body>
<form action="#" method="post">
<input id ="myfile" type="file"/>
</form>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="code.js"> </script>
</body>
</html>
The code.js file contains the following jQuery code. Try to use both
of the jQuery code snippets one by one and see the output.
jQuery code with attr('value'):
$('#myfile').change(function(){
alert($(this).attr('value'));
$('#mybutton').removeAttr('disabled');
});
jQuery code with val():
$('#myfile').change(function(){
alert($(this).val());
$('#mybutton').removeAttr('disabled');
});
Output:
The output of jQuery code with attr('value') will be 'undefined'.
The output of jQuery code with val() will the file name that you selected.
Explanation:
Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.
In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.
<input id ="myfile" type="file" value='test'/>
I hope it was useful to you.
Let's learn from an example.
Let there be a text input field with default value = "Enter your name"
var inp = $("input").attr("value");
var inp = $("input").val();
Both will return "Enter your name"
But suppose you change the default text to "Jose" in your browser.
var inp = $("input").attr("value");
will still give the default text i.e. "Enter your name".
var inp = $("input").val();
But .val() will return "Jose", i.e. the current value.
Hope it helps.
The proper way to set and get the value of a form field is using .val() method.
$('#field').val('test'); // Set
var value = $('#field').val(); // Get
With jQuery 1.6 there is a new method called .prop().
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.
In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.
jQuery('.changer').change(function () {
var addressdata = jQuery('option:selected', this).attr('address');
jQuery("#showadd").text(addressdata);
});
jQuery(".morepost").live("click", function() {
var loadID = jQuery(this).attr('id'); //get the id
alert(loadID);
});
you can also get the value of id using .attr()
this example may be useful:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>
<body>
<input id="test" type="text" />
<button onclick="testF()" >click</button>
<script>
function testF(){
alert($('#test').attr('value'));
alert( $('#test').prop('value'));
alert($('#test').val());
}
</script>
</body>
</html>
in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert.
attr('value') doesn't work with jquery version 1.9.1 or newer.
Example more... attr() is various, val() is just one! Prop is boolean are different.
//EXAMPLE 1 - RESULT
$('div').append($('input.idone').attr('value')).append('<br>');
$('div').append($('input[name=nametwo]').attr('family')).append('<br>');
$('div').append($('input#idtwo').attr('name')).append('<br>');
$('div').append($('input[name=nameone]').attr('value'));
$('div').append('<hr>'); //EXAMPLE 2
$('div').append($('input.idone').val()).append('<br>');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VAL
$('div').append($('input.idone').val('idonenew')).append('<br>');
$('input.idone').attr('type','initial');
$('div').append('<hr>'); //EXAMPLE 3 - MODIFY VALUE
$('div').append($('input[name=nametwo]').attr('value', 'new-jquery-pro')).append('<br>');
$('input#idtwo').attr('type','initial');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" class="idone" name="nameone" value="one-test" family="family-number-one">
<input type="hidden" id="idtwo" name="nametwo" value="two-test" family="family-number-two">
<br>
<div></div>
jquery - Get the value in an input text box
<script type="text/javascript">
jQuery(document).ready(function(){
var classValues = jQuery(".cart tr").find("td.product-name").text();
classValues = classValues.replace(/[_\W]+/g, " ")
jQuery('input[name=your-p-name]').val(classValues);
//alert(classValues);
});
</script>
If you get the same value for both property and attribute, but still sees it different on the HTML try this to get the HTML one:
$('#inputID').context.defaultValue;
In attr('value') you're specifically saying you're looking for the value of an attribute named vaule. It is preferable to use val() as this is jQuery's out of the box feature for extracting the value out of form elements.
I have always used .val() and to be honest I didnt even know you could get the value using .attr("value"). I set the value of a form field using .val() as well ex. $('#myfield').val('New Value');
I have such html code:
<div>
<div id="text">text></div>
<script>$("#text").val('some value');</script>
</div>
I copy this html through .clone() and edit html inside. Result:
<div>
<div id="1-text">text></div>
<script>$("#text").val('some value');</script>
</div>
I want to change id inside tags script. $("#1-text").val('other value');
How can I do it?
You can simply add a variable to the outside that dynamically tells you what to select. so if you were to iterate through your values using a loop you can do something like this:
$("#text_"+i).val('other value');
You could also set a counter and as new divs are added the i increments. So it is flexible.
I'm not exactly sure what your end goal is but I wouldn't recommend this methodology if you're attempting to manipulate the javascript in the <script> tag. As I believe that would be cumbersome.
If you want to copy entire html block, you should bind your inline javascript code to this block as a container. Not id. So when you move or copy the block your script will be able to find any elements related to container.
<div id="containerOne" class="js-container">
<div class="js-text" data-text="some value">some value</div>
<script>
var $el = $("script").last().closest(".js-container").find(".js-text");
$el.text($el.data("text"));
</script>
</div>
Hereby you obtain access to elements by class not id. Note using "js-" prefix is just for javascript manipulation not for css styling.
Also you don't need to change script itself. You can change values via "data-" attributes.
In your external script you can encapsulate any clone logic by various methods. For example:
var myModule = {
clone: function(containerSelector) {
var $donorEl = $(containerSelector);
var $donorScript = $donorEl.find('script');
$script = $("<script />");
$script.text($donorScript.text());
$recipientEl = $donorEl.clone();
$recipientEl.attr('id', 'containerTwo');
var newValue = 'other value';
$('.js-text', $recipientEl).data('text', newValue);
$('body').append($recipientEl);
$('script', $recipientEl).replaceWith($script);
}
};
myModule.clone('#containerOne');
You can see the working example.
I'm trying to make a add to favorite system. I have a function which alerts the proper id I want to add.
I use:
<script type="text/javascript">
function addfavo(state_name)
{
alert(state_name);
}
</script>
And in my html I have a loop (with php) which shows all the images with the add to favorite links which looks like.
<div style="margin-top:40px;">
<a onclick="addfavo('<?php echo $imgid ?>')"><b>Add to favourits</b></a>
</div>
So what happens is I have a lot of links to the same function with different parameters, but I only want the link that I click to change the text (to something like added to favorites)
Can some one help me in the right direction?
I have tried adding:
$(this).innerHTML("test");
but it didn't work.
You might want to use the html method:
$(this).html('test');
While html is a jQuery method, innerHTML is a property of a DOM element. If you were using pure JavaScript, you'd probably use:
this.innerHTML = 'test';
However, as you are using the onclick attribute on your HTML tag, this will not point to your current DOM element inside your function scope. In your case, I'd add a class to your elements, like add_favorite and add your text to another attribute:
<div style="margin-top:40px;">
<b>Add to favourits</b>
</div>
And then apply a jQuery event to it:
<script type="text/javascript">
$(function() {
$('.add-favorite').click(function(e) {
var text = $(this).data('text'); // store the text in a variable
$(this).html(text); // replace your element's html with your text
e.preventDefault();
});
});
</script>
Fiddle: http://jsfiddle.net/MH6vY/
I have a simple question - is it even possible to get element's HTML with styles from DOM? I don't need any jQuery object, just plain HTML with all styles.
I would use it in case were I have grid with different styles across rows and I would like to get that html and styles and sent it to server where I would use it in a mail body - programatically ofcourse.
Is there an elegant way to do that?
Tnx for answers
$.html() (with no arguments) does exactly this: http://api.jquery.com/html/
From the example on the page:
<p>
<b>Click</b> to change the <span id="tag">html</span>
</p>
<script>
$("p").click(function () {
var htmlStr = $(this).html();
$(this).text(htmlStr);
});
</script>
When the function is called, the contents of htmlStr is
<b>Click</b> to change the <span id="tag">html</span>
(as a string)
I can dynamically append "select" control to DOM,after appending it to DOM,I wanna change the html content of the last "select"(the latest "select" added dynamically),but it failed...
(I cannot set options value in param_html,becuase I should set them by using ajax request later.)
<script>
$(function(){
var param_html = '<select class="params"></select>';
$("input[value='+']").click(function(){
$('#parameters').append(param_html);
$('.params :last').html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
});
});
</script>
<div id="parameters">
<input type="button" value="+">
<select class="params"><option>1</option><option>2</option></select>
</div>
any suggestion is appreciated.
take out the space between params and :last
$('.params:last').html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
your content seems to be added after the dom has been loaded.
try live http://api.jquery.com/live/
Well your CSS selector is imporper should be $('.params:last-child') or $('.params:last') i think the space bar is not allowed there.
Also no one forbis You from using the object you've created:
$(function(){
var param_html = '<select class="params"></select>';
$("input[value='+']").click(function(){
$('#parameters').append(param_html);
$(param_html).html('<option>aaa</option><option>keyword in profile</option><option>last tweet</option>');
});
});
If you are going to use AJAX in future then the same idea will work instead of reselecting the object use to one you've created.