我正在尝试使用javascript从同一页面上的表单输出数据。我已经让它工作了。但我想添加一些我无法工作的东西。
正如您在下面的代码段中看到的那样,当您按提交时,数据会从输入输出在同一页面上。现在我正在尝试添加自定义BBCode,以便我的员工可以在论坛上发布输出。(这是一个采访记录器(。
示例:[b][/b] 应该在某些字段上输出,....我尝试在javascript或输出范围中添加这个bbcode,但这破坏了整个脚本。
我还有一个问题。如果我添加带有通过或失败的下拉列表或单选按钮。我将如何进行输出更改。(示例:如果通过:[颜色 = 绿色] 用户已通过面试 [/颜色],如果失败:[颜色 = 红色] 用户已通过面试。原因:。。。[/颜色]
提前谢谢。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("user_input").value;
}
</script>
</head>
<body>
<form>
<label><b>Enter a Message</b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showInput();"><br/>
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
您可以使用 .attr(( 按标签属性进行搜索。
尝试使用一个constant
来映射所需内容的id
,添加[B]
标记并使用<input type="radio">
的value
属性来获取所需的内容。
样本:
const idToBold = [ 'user_input1' ];
var formInfo = {};
function showInput() {
$('input').each(function(){
var input = $(this);
var value = null, label = null;
//here you check every <input type="text">
if(input.attr('type') == 'text'){
value = input.val();
//check if the id is in the constant of ids that need to add the [B] tag
if(idToBold.includes(input.attr('id'))){
value = '[B]' + value + '[/B]';
}
label = $("label[for='"+input.attr('id')+"']").text();
}
//here will check the radio with this name only, and return the checked (in case you want more radios)
if(input.attr('name') == 'passCondition' && input.is(':checked')){
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'pass'){
value = '[Color = Green]User has passed the interview [/color]';
}else{
value = '[Color = Red]User hase failed the interview. Reason: ...';
};
label = $("label[for='"+input.attr('name')+"']").text();
}
if(label != null && label != '' && value != null && value != ''){
formInfo[label] = value;
}
});
//you can remove this, just for output purpose
var formInfoFormated = '';
jQuery.each(formInfo, function(key, value){
formInfoFormated += key + ' : ' + value + '<br>';
});
$('#display').html(formInfoFormated);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<body>
<form>
<label for="user_input1"><b>Enter a Message1</b></label>
<input type="text" name="message" id="user_input1">
<br>
<label for="user_input2"><b>Enter a Message2</b></label>
<input type="text" name="message" id="user_input2">
<br><br>
<label for="passCondition"><b>Passed?</b></label><br>
<input type="radio" name="passCondition" value="pass">Pass<br>
<input type="radio" name="passCondition" value="fail">Fail<br>
<br><br>
</form>
<input type="submit" onclick="showInput();"><br/>
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>