简体   繁体   中英

How to get attribute of HTML element using JavaScript

This is a newb question, but it makes me pulling my hairs:

<div class="search-input-field">
  <input type="text" value="amazon" placeholder="Search" name="search" id="search">
</div>

I would like to get the value of this input when user mouseOut. How can I do this using jQuery/javaScript?

Thank you.

You can use .val() to get the value of a form element:

var value = $('#search').val();

You can also use .attr() to get an attribute for an element:

var placeholderText = $('#search').attr('value');

Docs:

An example of your desired code:

$('#search').on('mouseout', function () {
    alert(this.value);
});

Notice that you can get the value of an input element inside an event handler with this.value which will perform much faster than using $(this).val() .

[Suggestion] - If you want to get the value after the user has finished editing the value of the input then I suggest using the blur event ( mouseout fires when the user moves the cursor over the element, then away):

$('#search').on('blur', function () {
    alert(this.value);
});

Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind() .

You going to need to implement the mouseout event handler first and then you can use this.value the value of the input and .attr to get the value of any non-standard attribute.

var $search = $('#search');
$search.mouseout(function () {
   alert(this.value);
   alert(this.name);
});

DEMO

Further Reading,

.val()

.attr()

.mouseout

Plain JS way:

var myValue = document.getElementsByName("search")[0].value;

or

var myValue = document.getElementById("search").value;

Cross browser binding is sometimes problematic, but it's basicly something like:

document.getElementById("search").addEventListener('onmouseout',function () {
    var myValue = this.value;
},false);

jQuery way:

var myValue = $('#search').val();

or

var myValue = $('input[name="search"]').val();

binding

$('#search').on('click', function() {var myValue = this.value});
$(document).ready(function () {

        $('div.search-input-field').mouseout(function () {

            alert($('div.search-input-field input:first').val());

        });

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM