I'm planning to create a JavaScript prompt where you can enter your name and it will go to the 's value. How can I make the code work? I tried the below code but it seems it needed a jQuery 1.7.1
function getName() {
do {
var name=prompt("Please enter your CLAM username");
}
while(name.length < 4);
$('#myinput').val(name);
}
getName();
HTML
<input id="myinput"/>
I expect the output to be <input id="myinput" value"name from prompt">
答案 0 :(得分:0)
You don't actually need jQuery for this:
function getName() {
do {
var name = prompt("Please enter your CLAM username");
}
while (name.length < 4);
document.getElementById("myinput").value = name;
}
getName();
<input id="myinput" />
If you really want to use jQuery, then import a newer version:
function getName() {
do {
var name = prompt("Please enter your CLAM username");
}
while (name.length < 4);
$("#myinput").val(name);
}
getName();
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<input id="myinput" />
答案 1 :(得分:0)
Because the line of code $('#myinput').val(name)
is jquery syntax.
You can change it to javascript by
document.getElementById('myinput').value = name;
it is equal with $('#myinput').val(name);
function getName() {
do {
var name=prompt("Please enter your CLAM username");
}
while(name.length < 4);
document.getElementById('myinput').value = name;
}
getName();
<input id="myinput"/>
答案 2 :(得分:0)
$('myinput').val(name);
is for jquery only. if you don't want to use jquery then use this
document.getElementById('myinput').value = name;
for a pure javascript..
Here is my answer for this.
<input id="myinput"/>
<script type="text/javascript">
function getName() {
do {
var name=prompt("Please enter your CLAM username");
}
while(name.length < 4);
document.getElementById('myinput').value = name;
}
getName();
</script>
note: don't put your <input id="myinput"/>
at the bottom or else you will get null. put it above the script.