Everyone_Else Everyone_Else - 1 month ago 8
Javascript Question

How can I set the input value of a form in javascript?

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?

Answer

Just through this example Hope it will work for you :)

    <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(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>
</head>
<body>

<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>

</body>
</html>