在输入文本框中获取值

JavaScript

理查德Near小宇宙

2020-03-16

使用jQuery获取和呈现输入值的方法有哪些?

这是一个:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#txt_name").keyup(function(){
            alert($(this).val());
        });
    })
</script>

<input type="text" id="txt_name"  />

第1645篇《在输入文本框中获取值》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
樱神奇神无 2020.03.16

I think this function is missed here in previous answers

.val( function(index, value) ) 
小卤蛋小宇宙 2020.03.16

You have to use various ways to get current value of an input element.

METHOD - 1

If you want to use a simple .val(), try this:

<input type="text" id="txt_name" />

Get values from Input

// use to select with DOM element.
$("input").val();

// use the id to select the element.
$("#txt_name").val();

// use type="text" with input to select the element
$("input:text").val();

Set value to Input

// use to add "text content" to the DOM element.
$("input").val("text content");

// use the id to add "text content" to the element.
$("#txt_name").val("text content");

// use type="text" with input to add "text content" to the element
$("input:text").val("text content");

METHOD - 2

Use .attr() to get the content.

<input type="text" id="txt_name" value="" />

I just add one attribute to the input field. value="" attribute is the one who carry the text content that we entered in input field.

$("input").attr("value");

METHOD - 3

you can use this one directly on your input element.

$("input").keyup(function(){
    alert(this.value);
});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android