You don't want to use prevUntil
, from the docs you will see:
Description: Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.
As a result, $(this).prevUntil('.regfieldlabel')
is actually empty.
For Example 2, you still want to use just prev
:
$(this).prev('.regfieldlabel').find('input')
For a general solution, you will have to check which situation you are in, in order to do the correct thing:
$("span.reqd").each(function(){
var $this = $(this);
var $prev = $this.prev();
var $input = $([]); // init to empty
if($prev.is("input")){
// EXAMPLE 1
$input = $prev;
} else if($prev.is(".regfieldlabel")){
var $innerInput = $prev.find("input");
if($innerInput.length > 0){
// EXAMPLE 2
$input = $innerInput;
} else {
$prev = $prev.prev(".regfieldlabel");
$innerInput = $prev.find("input");
if($innerInput.length > 0){
// EXAMPLE 3
$input = $innerInput;
} else {
// unknown case, maybe do something here
}
}
} else {
// unknown case, maybe do something here
}
$input.attr('data-rule-required', true).attr('data-msg-required', 'This field is required');
});