最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How can I set the input value of a form in javascript? - Stack Overflow

programmeradmin3浏览0评论

Suppose that I have defined a form (my_form) that has an input named myInput. I would like to set the value of myInput to be my_string.

$('#my_form textarea[name=myInput]').value = my_string;

I've tried the above line, and this works for most browsers, but not for Opera/Safari. I know it doesn't work for Opera/Safari because the line

console.log($('#my_form textarea[name=myInput]').value + " was the string");

logs undefined was the string to the screen instead of the actual value of my_string (which is not undefined).

How can I achieve this for these browsers?

Suppose that I have defined a form (my_form) that has an input named myInput. I would like to set the value of myInput to be my_string.

$('#my_form textarea[name=myInput]').value = my_string;

I've tried the above line, and this works for most browsers, but not for Opera/Safari. I know it doesn't work for Opera/Safari because the line

console.log($('#my_form textarea[name=myInput]').value + " was the string");

logs undefined was the string to the screen instead of the actual value of my_string (which is not undefined).

How can I achieve this for these browsers?

Share Improve this question asked Jul 6, 2016 at 13:54 Everyone_ElseEveryone_Else 3,2645 gold badges34 silver badges58 bronze badges 2
  • 2 It looks like you're using jQuery. Try .val() instead of .value. – RobertAKARobin Commented Jul 6, 2016 at 13:56
  • 2 api.jquery./val – Jack Commented Jul 6, 2016 at 13:56
Add a ment  | 

2 Answers 2

Reset to default 3

Try this example:

$(document).ready(function () {
    $("#btn1").click(function () {
        $("#test1").text("Hello world!");
    });
    $("#btn2").click(function () {
        $("#test2").html("<b>Hello world!</b>");
    });
    $("#btn3").click(function () {
        $("#test3").val("Dolly Duck");
    });
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<p id="test1">This is a paragraph.</p>
<p id="test2">This is another paragraph.</p>

<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>

<button id="btn1">Set Text</button>
<button id="btn2">Set HTML</button>
<button id="btn3">Set Value</button>

You have to use .val() instead of .value. And quotes for a string.

So the final code will be:

$("#my_form textarea[name=myInput]").val("my_string_with_quotes_before_and_after");

or with variable

var string="some text";
$("#my_form textarea[name=myInput]").val(string);
发布评论

评论列表(0)

  1. 暂无评论