我正在尝试编写一种表单,该表单根据用户选择的输入来创建自定义句子。例如,我的表单有一个书面输入和两个下拉菜单。我希望将此数据添加到我的innerHTML中。假设我想为狗创建一个自定义句子,其布局应如下所示:
我的狗的名字是(输入1的值)。 (下拉式选单1的价值)爱 玩取球。我的狗是(下拉菜单2中的值)。
function sentence() {
document.getElementById("s1").innerHTML = "My dog's name is (value from input 1). (Value from dropdown 1) loves to play fetch. My dog is (value from dropdown 2).";
}
table,
td,
th {
margin-left: auto;
margin-right: auto
}
.display {
display: flex;
align-items: center;
justify-content: center;
}
p {
text-align: center;
}
<table>
<tr>
<td> <input type="text" placeholder="Your Dog's Name" name="name" maxlength="100"></td>
<td>
<select name="gender">
<option value="He">He</option>
<option value="She">She</option>
</select>
</td>
<td>
<select name="size">
<option value="Big">Big</option>
<option value="Medium">Medium</option>
<option value="Small">Small</option>
</select>
</td>
</table>
<br>
<hr>
<br>
<p id="s1">
</p>
<br>
<div class="display">
<button onclick="sentence()"> Button </button>
</div>
<p id="s1">
</p>
答案 0 :(得分:1)
以下代码将解决问题!
function sentence()
{
const v1 = document.getElementsByTagName('input')[0].value,
v2 = document.getElementsByTagName('select')[0].value,
v3 = document.getElementsByTagName('select')[1].value
document.getElementById("s1").innerHTML="My dog's name is " + v1 + ". " + v2 + "loves to play fetch. My dog is " + v3 + ".";
}
答案 1 :(得分:1)
尝试此代码:)
function sentence() {
var nameDog = document.getElementById( "name" ),
genderDog = document.getElementById( "gender" ),
sizeDog = document.getElementById( "size" ),
result = document.getElementById( "s1" );
if ( nameDog.value == "" ) {
result.innerHTML = "Write name your dog's";
} else {
result.innerHTML = "My dog's name is " + nameDog.value + ", " + genderDog.value + " loves to play fetch. My dog is " + sizeDog.value;
}
};
table, td, th {
margin-left: auto;
margin-right: auto
}
.display {
display: flex;
align-items: center;
justify-content: center;
}
p {
text-align: center;
}
<table>
<tr>
<td><input id="name" placeholder="Your Dog's Name" type="text">
</td>
<td><select id="gender">
<option value="he">
he
</option>
<option value="she">
she
</option>
</select>
</td>
<td><select id="size">
<option value="big">
big
</option>
<option value="medium">
medium
</option>
<option value="small">
small
</option>
</select>
</td>
</tr>
</table>
<br>
<hr>
<br>
<div class="display">
<button onclick="sentence()">Button</button>
</div>
<p id="s1">
</p>