У меня есть диалоговое окно jquery, в котором используется функция javascript без jquery для завершения работы в зависимости от выбранной кнопки. Я добавил флажок в диалоговом окне, который пользователь должен проверить, чтобы понять, что произойдет.Работа с флажком в диалоговом окне jquery
Когда я добавляю тестирование проверенного состояния на jQuery без jquery, проверенное состояние всегда возвращается как false.
Ниже приведен код. Первые два предупреждения и оператор возврата предназначено для тестирования:
function acceptPitch()
{
// the two alerts and return false are for testing only
alert('jq=' + $('#understand').prop("checked"));
alert('checkbox=' + document.getElementById('understand').checked);
return false;
if (document.getElementById('understand').checked)
{
handleUserDelay();
$('#decision').val('yes');
document.forms['cancellationForm'].submit();
return true;
}
else
{
alert('[appropriate message here]');
return false;
}
}
Если флажок не в диалоговом окне, то данная функция работает, как ожидалось. Но когда он помещается внутри диалогового окна, тесты для «checked» всегда возвращают false.
Вот основной код для диалога:
var $dialog_cancel = $('#rh-dialog.cancel');
$dialog_cancel.dialog(
{
autoOpen:false,
width:500,
modal:true,
draggable:true,
resizable:false
});
$('#reason').change(function()
{
var reason1 = $(this).val().substr(0,1);
if (reason1 == 'n')
{
$('#pitch').html($('#pitch-no').html());
$('#acceptPitchButton').val($('#free-button-text').html());
}
else if (reason1 == 'y')
{
$('#pitch').html($('#pitch-yes').html());
$('#acceptPitchButton').val($('#perp-button-text').html());
}
else
{
validCancelReason();
}
});
$('#requestCancelButton').click(function()
{
if (validCancelReason())
{
$dialog_cancel.dialog('open');
}
});
Ниже разметки взята из «источника» просмотр списка. Пожалуйста, обратите внимание, что JQuery используется для отображения только два из последних четырех див, и некоторые другие настройки производятся с помощью JQuery:
<div id="rh-dialog" class="cancel" title="Confirm Cancellation">
<p>
This will request cancellation of your continuing subscription service.<br />
</p>
<div id="pitch"></div>
<p style="font-style: italic; margin-top:10px;">
Please click <strong>YES!</strong> to continue your plan, or <strong>No, Thank You</strong> to cancel.
</p>
<div>
<div id="rh-dialog-button-1">
<input type="button" id="acceptPitchButton" value="Don't Cancel" onclick="bar1.showBar(); acceptPitch();" />
</div>
<div id="rh-dialog-button-2">
<input type="button" id="rejectPitchButton" value="No, Thank You, Just Cancel" onclick="bar1.showBar(); rejectPitch();" />
</div>
</div>
</div>
<div id="pitch-no" class="no-disp"><strong>GET ONE FREE MONTH!</strong><br />It is very important to us that all of our subscribers have success with our service, not only in speaking with reps but in actually growing your business. Given you are canceling because you were unsatisfied, we would like to offer you <strong>one FREE month.</strong><br /><br />To take advantage of this offer simply click <strong>Yes! Free Month</strong> and your credit card or PayPal account will not be charged for the next month.<br /><br />After your free month, you can choose to cancel your subscription or continue on with our Maintenance plan.<br/><br/><form id="agree-form"><input type="checkbox" id="understand"><strong>I understand</strong> that by requesting a free month I am not canceling my subscription, and that after the free month is over, my credit card or PayPal account will be charged for the next month of service and again every month thereafter until I do cancel.</input></form></div>
<div id="pitch-yes" class="no-disp"><strong>BARGAIN PRICE PERPETUITY PLAN!</strong><br />You realize that placing quality sales reps requires a continual effort trolling for reps at all times because timing is of the essense. For that reason, we would like to offer you our <strong>Perpetuity Plan</strong>.<br /><br />This plan is only USD $79/month, cancel anytime, and you can lock into that rate for life.<br /><br />Click <strong>Yes! Perpetuity Plan</strong> to switch to the Perpetuity Plan.</div>
<div id="free-button-text" class="no-disp">Yes! Free Month - Continue Subscription</div>
<div id="perp-button-text" class="no-disp">Yes! Perpetuity Plan</div>
Кроме того, я добавляю снимок экрана:
может быть здорово показать некоторую разметку материала, на который ссылаются. –
Прежде чем увидеть ответ ниже от Sheikh Heera, я нашел эту другую страницу, которая, похоже, может обеспечить решение: http://stackoverflow.com/questions/757232/jquery-ui-dialog-with-asp-net-button- постбэк. Мне нужно будет проверить ответ ниже, и если это не сработает, то советы с этой другой страницы (которые в основном говорят, что jquery перемещает диалог из формы, и другие трюки должны использоваться, чтобы заставить его работать) , –
У меня есть ответ.По сути, подход, который я использовал из этого другого вопроса, был показан следующим образом: dlg.parent(). AppendTo (jQuery ("form: first")); В моем случае я адаптировал этот подход, добавив этот оператор jQuery после определения моего диалога: $ dialog_cancel.parent(). AppendTo ($ ('# cancelationForm')); После того, как это заявление присутствует, работают как jQuery, так и простые javascript-подходы. То есть можно использовать любой из двух следующих операторов: alert ('jq =' + $ ('# understand'). Prop ("checked")); alert ('checkbox =' + document.getElementById ('понимать'). Checked); –