我想为20个输入框运行此语句。有没有一种干净的组合方式?似乎会有很多陈述。设计为捕获输入到输入中的数据,然后在单击按钮后将其显示为HTML。目前只有1行代码有效,需要将其添加几行。
$(".showreg").click(function(){
var pagetitle = $('#f_k_page_title').val();
if(!pagetitle)
{pagetitle = "Oop's No value entered";}
$('#theValue').html(pagetitle);
});
$(".showreg").click(function(){
var nametitle = $('#f_name_title').val();
if(!nametitle)
{nametitle = "Oop's No value entered";}
$('#theValue2').html(nametitle);
});
的HTML
<span id="theValue"></span>
<span class="txt_111 s17" id="theValue2">Title:</span>
<span class="txt_555 s17" id="theValue3"></span>
<div class="btn blue next-btn r-btn regclick3 capture_button showreg mt10">Next</div>
表单HTML
<form>
<input id="f_k_page_title"/>
<input id="f_name_title"/>
<input class="btn blue createacc-btn " type="submit" name="submit" value="Create account"/>
</form>
最佳答案
只需在所有需要验证的对象上设置事件处理程序(此处提供CSS类帮助):
$(".validateForEmpty").on("blur", function(evt){
var input = $(this);
// Get index number of the input within its group.
var idx = $(".validateForEmpty").index(input);
// Get reference to span corresponding to that same index
var span = $(".output").get(idx);
// Validate element that just lost the focus
if(input.val().trim() === ""){
$(span).text(input.attr("name") + " Can't be empty!"); // Put message corresponding span
} else {
$(span).text(input.attr("name") + " contains: " + input.val()); // Put value in corresponding span
}
});
.output { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="a" class="validateForEmpty">
</div>
<div>
<input type="text" name="b" class="validateForEmpty"><span class="error"></span>
</div>
<div>
<input type="text" name="c" class="validateForEmpty"><span class="error"></span>
</div>
<div>
<input type="text" name="d" class="validateForEmpty"><span class="error"></span>
</div>
<div>
<input type="text" name="e" class="validateForEmpty"><span class="error"></span>
</div>
<div>
<input type="text" name="f" class="validateForEmpty"><span class="error"></span>
</div>
<div>
<input type="text" name="g" class="validateForEmpty"><span class="error"></span>
</div>
<div>
<input type="text" name="h" class="validateForEmpty"><span class="error"></span>
</div>
<div>
<input type="text" name="i" class="validateForEmpty"><span class="error"></span>
</div>
<div class="outputElements">
<span class="output"></span>
<span class="output"></span>
<span class="output"></span>
<span class="output"></span>
<span class="output"></span>
<span class="output"></span>
<span class="output"></span>
<span class="output"></span>
<span class="output"></span>
</div>
关于javascript - 如何整合多条陈述,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44266714/