我需要你的帮助。我有这个fiddle,正如你所看到的那样,用新名称克隆原始div并选择了文本,现在我想验证创建的选择,如果他们选择的选项是"选择"警告用户并专注于该选择,
我认为在这样的事情中,检查名称以" newDiv"开头的div。并选择内部文本等于"选择"
$('button#validate').live('click', function() {
var wrong = $('div[name^="newDiv"] select option').filter(':selected').text();
if ( wrong == "Select" )
{
alert("Please select an option");
$(this).focus();
$(this).css("background-color","red");
}
});
我希望你理解我的意思,谢谢。
答案 0 :(得分:1)
JSFiddle:http://jsfiddle.net/TrueBlueAussie/2Lgumtp8/3/
各种修正:
我突出显示错误选项的最近父选择
$(document).ready(function(){
var counter = 2;
$("input#clone").click(function () {
//Let's make a copy to work with
var originalDiv = $("div#old");
var cloneDiv = originalDiv.clone();
//Renaming cloneDiv
cloneDiv.attr('id', 'newDiv' + counter);
//Renaming inputs in cloneDiv
$("[name='id']", cloneDiv).attr('name', 'id' + counter);
$("[name='email']", cloneDiv).attr('name', 'email' + counter);
$("[name='emails']", cloneDiv).attr('name', 'emails' + counter);
//Value first textfield
$("[name='id" + counter + "']", cloneDiv).val(+counter);
//Value Select
$("[name='email" + counter + "']", cloneDiv).val($("[name='email'] option:selected", originalDiv).val());
$("[name='emails" + counter + "']", cloneDiv).val($("[name='emails'] option:selected", originalDiv).val());
//Append to originalDiv container whatever it is...
originalDiv.parent().append(cloneDiv);
//OR Append to body after old div
//$('.old:last').after(cloneDiv);
//Increment counter
counter++;
});
$("input#remove").click(function (e) {
if (counter > 2) {
$('#newDiv' + (counter - 1)).remove();
counter--;
}
});
$('#validate').click(function () {
$('div[id^="newDiv"] select').css("background-color", "");
$('div[id^="newDiv"] select option').filter(':selected').each(function () {
var select = $(this);
if (select.text() == "Select") {
alert("Please select an option");
select.closest('select').focus().css("background-color", "red");
return false;
}
});
});
});