简体   繁体   中英

How to check if a form has no input fields and if so set the focus to an anchor element

Is there any way to check if a specific form has any input fields in it? Or if it has no input fields?

Update:

Also how do I return the focus to a button on page load if the condition is met? The below doesn't seem to work

var numInputs = $("#forgotPassword").find("input:visible").length;
if(numInputs == 0){
$('.button-class > a').focus(); 
}

I would just select all the inputs inside the form and check to see how many come back

var numInputs = $("#formId input").length;

if (numInputs === 0)
   console.log("no inputs");

And of course if you'd like to include textareas and selects

var numInputs = $("#formId input, #formId textarea, #formId select").length;

or more simply:

var numInputs = $("#formId").find("input, textarea, select").length;

EDIT

To exclude hidden inputs, you can use the :visible pseudoselector

var numInputs = $("#formId input:visible").length;

只需检查选择器结果是否包含任何元素(在此我假设通过输入字段表示文本输入字段):

$('#myform').find('input[type="text"]').length

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM