这将获取包含值,选择或选中的元素的ID。不过,我尝试识别包含值的最新 ID,在表单中选择或检查。
如何解决这个问题的任何解决方案都将是一个很大的帮助!
$('#submit').live('click', function() {
$(".analytics").each(function() {
var getid = $(this).attr('id');
if ($(this).is('input:text') && $(this).val() != "") {
alert(getid);
} else if ($(this).is('select') && $(this).val() != "") {
alert(getid);
return false;
} else if ($(this).is(':checked')) {
alert(getid);
return false;
}
});
return false;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<p>Select a value at the top and a value at the bottom and submit</p>
<form id="myForm">
1) Please Select Your First Car
<BR>
<select id="car1" class="analytics">
<option value="">Please Select</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<BR>
<BR>2) Please Select Your Second Car
<BR>
<select id="car2" class="analytics">
<option value="">Please Select</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<br>3) First name:
<br>
<input type="text" id="firstname" name="firstname" class="analytics" value="">
<BR>
<BR>4) Last name:
<br>
<input type="text" id="lastname" name="lastname" class="analytics">
<br>
<br>5) Select your Newsletter:
<BR>
<input type="checkbox" id="news1" name="newsletter" value="" class="analytics">Daily
<br>
<input type="checkbox" id="news2" name="newsletter" value="" class="analytics">Weekly
<br>
<br>6) Select your Gender:
<BR>
<input type="radio" id="gender1" name="gender" value="" class="analytics">Male
<br>
<input type="radio" id="gender2" name="gender" value="" class="analytics">Female
<br>
<br>7) Do you like books?
<BR>
<input type="radio" id="question_yes" name="question" value="" class="analytics">Yes
<br>
<input type="radio" id="question_no" name="question" value="" class="analytics">No
<input type="submit" id="submit">
</form>
&#13;
答案 0 :(得分:1)
$('#submit').live('click', function() {
// Retrieve the last element with inputs
var $last = $(".analytics").filter(function() {
// Filter based on the same filters you're already using
return ($(this).is('input:text') && $(this).val() != "") ||
($(this).is('select') && $(this).val() != "") ||
$(this).is(':checked');
}).last()
alert($last.attr("id"));
return false
});
<强> Updated Fiddle 强>
我还建议使用.on
来附加事件,尤其是因为jQuery的以后版本中不推荐使用.live
(并删除了):
$(document).on('click', '#submit', function() {
答案 1 :(得分:0)
我相信这就是你的意思....
获取表单元素的总数。然后向后遍历元素。像这样....
var i = document.getElementById("myForm").elements.length;
var count = i;
while(count > 0)
{
if(document.getElementById("myForm").elements[count].value)
{
alert("Found it!! ID: " + document.getElementById("myForm").elements[count].id);
}
count--;
}