Kinda stuck a lot of hrs on this
but i cant find out .parent() or next() or .next All() for this
I want to show div named .SubQuestion on ajax success when .input-range slider value is something
Eveything work perfect except
$(this).next(".SubQuestion").show();
and
$(this).next(".SubQuestion").hide();
i can not find my div class display and css does not work
<div class="row">
<div class="col-9 my-1 input-ranges" id="range">
#{ var questionId = Model.QuestionAndAnswer[i].QuestionId;
var AcceptableScore = Model.QuestionAndAnswer[i].QuestionAcceptableScore;
}
#Html.TextBoxFor(model => model.QuestionAndAnswer[i].Ans_Score, htmlAttributes: new { #id = questionId, #tag = AcceptableScore, #class = "input-range", #min = "1", #max = "10", #step = "1", #type = "range" })
YourScore <span class="range-value">1</span>
</div>
<div class="col-3">
<a data-toggle="collapse" href="#ScoreComment_#i" role="button" aria-expanded="false" aria-controls="collapseExample">
<div class="fs-3x text-center text-info"><i class="la la-comment-o"></i></div>
</a>
</div>
<div class="col-12 bg-info SubQuestion" style="display:none">
<h1>Result</h1>
</div>
<div class="col-12">
<div class="collapse my-1" id="ScoreComment_#i">
#Html.TextAreaFor(model => model.QuestionAndAnswer[i].Ans_Score_Note, new { #class = "form-control p-1 w-100", #maxlength = "4000", #rows = "4", #placeholder = "توضیحات" })
</div>
</div>
</div>
<script>
$(function ($) {
console.log($.ajax);
$('.input-range').on('change', function () {
$(this).next('.range-value').html(this.value);
var questionId = $(this).attr("id");
var QAScore = $(this).attr("tag");
var rangevalue = $(this).nextAll('.range-value').first().text();
if (rangevalue < QAScore) {
$.ajax({
url: "/Question/GetSubQuestion",
type: "POST",
datatype: "json",
data: { QuestionId: questionId },
success: function (data) {
$(this).next(".SubQuestion").html(data);
$(this).next(".SubQuestion").show();
}
});
}
else {
$(this).parent().nextAll(".SubQuestion").hide();
}
});
});
</script>
Here was the solution
Thanks to #AndrewLohr
$(function ($) {
$('.input-range').on('change', function () {
$(this).next('.range-value').html(this.value);
let subQuestion = $(this).parent().nextAll(".SubQuestion").show();
var questionId = $(this).attr("id");
var QAScore = $(this).attr("tag");
var rangevalue = $(this).nextAll('.range-value').first().text();
if (rangevalue < QAScore && rangevalue!=10) {
$.ajax({
url: "/Question/GetSubQuestion",
type: "POST",
datatype: "json",
data: { QuestionId: questionId },
success: function (data) {
subQuestion.html(data);
subQuestion.show();
}
});
}
else {
$(this).parent().nextAll(".SubQuestion").hide();
}
});
});
Related
In my view I'm displaying a table and in table I strongly typed dropdown list and as you change selected item it calls getPrice(int product_id) function through ajax call and returns price of selected item but it only works for 1st row.
HTML
<tr class="tr_clone" id="1">
<td>
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"}
</td>
<td class="product_price" id="product_price" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product_price, "", "") </td></tr>
<tr class="tr_clone1" id="2">
<td>
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"})
</td>
<td class="product_price" id="product_price1" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product_price, "", "")</td></tr>
Ajax call
$(function () {
$('#product_id').change(function () {
$.ajax({
type: "POST",
url: "/Home/GetPrice",
datatype: "Json",
data: { product_id: $('#product_id').val() },
success: function (data) {
document.getElementById('product_price').innerHTML = data;
multiply();
},
error: function (data = 0) {
document.getElementById('product_price').innerText = 0;
multiply();
}
});
});
});
html
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel", #onchange = "gg(this)" })
ajax call
<script>
function gg(x) {
$.ajax({
type: "POST",
url: "/Home/GetPrice // GetPrice is name of actionmathod of controller",
datatype: "Json",
data: { product_id: $(x).val() },
success: function (data) {
//your code here
},
error: function () {
// your code here
}
});
}
</script>
You need to set 2 different ids for each dropdown.
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #id = "ddl_product_id_1", #class = "form-control sel"}
#Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { #id = "ddl_product_id_2", #class = "form-control sel"})
And write change event of individual that dropdown id.
Since you are selecting 2 different products, you model should have 2 id properties - product1_id and product2_id and 2 price properties - product1_price and product2_price
So fix your view accordingly
<tr class="tr_clone" id="1">
<td>
#Html.DropDownListFor(model => model.product2_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"}
</td>
<td class="product_price" id="product_price" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product1_price, "", "") </td></tr>
<tr class="tr_clone1" id="2">
<td>
#Html.DropDownListFor(model => model.product2_id, ViewBag.ProductList as SelectList, "--select product--", new { #class = "form-control sel"})
</td>
<td class="product_price" id="product2_price" style="text-align: center; font-size: 16px;">#Html.DisplayFor(model => model.product2_price, "", "")</td></tr>
and you should 2 separate on change too
$(function () {
$('#product1_id').change(function () {
$.ajax({
type: "POST",
url: "/Home/GetPrice",
datatype: "Json",
data: { product_id: $('#product1_id').val() },
success: function (data) {
document.getElementById('product1_price').innerHTML = data;
multiply();
},
error: function (data = 0) {
document.getElementById('product1_price').innerText = 0;
multiply();
}
});
});
$('#product2_id').change(function () {
$.ajax({
type: "POST",
url: "/Home/GetPrice",
datatype: "Json",
data: { product_id: $('#product2_id').val() },
success: function (data) {
document.getElementById('product2_price').innerHTML = data;
multiply();
},
error: function (data = 0) {
document.getElementById('product2_price').innerText = 0;
multiply();
}
});
});
});
I have 2 buttons with this ajax and they both show on the page,how can i make it that only Add to favorites button is shown and when i click it the Remove From Favorites button takes it place ?
function Fav(gameId) {
var url = '#Url.Action("AddToCollection", "UserCollection")';
$.ajax({
url: url,
type: 'GET',
data: {
gameId: gameId,
},
});
};
function UnFav(gameId) {
var url = '#Url.Action("RemoveFromCollection", "UserCollection")';
$.ajax({
url: url,
type: 'GET',
data: {
gameId: gameId
},
});
};
<button class="btn-link" onclick="Fav(#Model.Id)"><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link " onclick="UnFav(#Model.Id)"><i class="fa fa-heart-broken"></i>Remove From Collection</button>
Try something like this.
DRY (Don't Repeat Yourself)
const urls = {
"AddToCollection": '#Url.Action("AddToCollection","UserCollection")',
"RemoveFromCollection": '#Url.Action("RemoveFromCollection","UserCollection")'
}
function Fav(gameId, action) {
$.ajax({
url: urls[action],
type: 'GET',
data: {
gameId: gameId,
},
});
};
$(function() {
const whichButton = "AddToCollection"; // set which one to show here using whatever method
$(".btn-link[data-action="+whichButton+"]").show();
$(".btn-link").on("click", function() {
Fav(this.dataset.id, this.dataset.action)
$(this).siblings().hide();
});
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="favDiv">
<button class="btn-link hide" data-action="AddToCollection" data-id=""><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link hide" data-action="RemoveFromCollection" data-id=""><i class="fa fa-heart-broken"></i>Remove From Collection</button>
</div>
This is the final result that i was looking for
const urls = {
"AddToCollection": '#Url.Action("AddToCollection","UserCollection",new { gameId = Model.Id })',
"RemoveFromCollection": '#Url.Action("RemoveFromCollection","UserCollection",new { gameId = Model.Id })'
}
function Fav(gameId, action) {
$.ajax({
url: urls[action],
type: 'GET',
data: {
gameId: gameId,
},
});
};
$(function() {
const whichButton = "AddToCollection"; // set which one to show here using whatever method
$(".btn-link[data-action=" + whichButton + "]").show();
$(".btn-link").on("click", function() {
Fav(this.dataset.id, this.dataset.action)
$(this).siblings().hide();
$(this).siblings().show();
$(".btn-link[data-action=" + whichButton + "]").hide();
});
});
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="favDiv">
<button class="btn-link hide" data-action="AddToCollection" data-id=""><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link hide" data-action="RemoveFromCollection" data-id=""><i class="fa fa-heart-broken"></i>Remove From Collection</button>
</div>
so I have a razor form and I want to disable a button during ajax request.
Also I want to be able to send only one request to controller - (disable any flood attempt)
This is my html:
<div class="row">
<div class="col-md-8 col-md-offset-2">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "contactForm" }))
{
<div class="clearfix">
<div class="cf-left-col">
<div class="form-group required">
#Html.TextBoxFor(m => m.CheckInCheckOutDate, new { #class = "form-control input-md round", #required = "required", #autocomplete = "off", #id = "input-id", #placeholder = Resources.Resources.CheckInCheckOutPlaceholderKey })
<div>
#Html.ValidationMessageFor(m => m.CheckInCheckOutDate, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control input-md round", #required = "required", #placeholder = "Name" })
<div>
#Html.ValidationMessageFor(m => m.Name, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.MobilePhone, new { #class = "form-control input-md round mobile", #required = "required", #placeholder = "Mobile phone" })
<div>
#Html.ValidationMessageFor(m => m.MobilePhone, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.EMail, new { #class = "form-control input-md round", #required = "required", #placeholder = "E-Mail" })
<div>
#Html.ValidationMessageFor(m => m.EMail, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.AdultsNumber, new { #class = "form-control input-md round person", #required = "required", #placeholder = "Guests" })
<div>
#Html.ValidationMessageFor(m => m.AdultsNumber, null, new { #class = "text-danger" })
</div>
</div>
<div class="form-group required">
#Html.TextBoxFor(m => m.ChildrenNumber, new { #class = "form-control input-md round person", #placeholder = "Children" })
</div>
</div>
<div class="cf-right-col">
<div class="form-group required">
#Html.TextAreaFor(m => m.MessageBody, new { #class = "form-control input-md round", #rows = 10, #placeholder = "Message" })
<div>
#Html.ValidationMessageFor(m => m.MessageBody, null, new { #class = "text-danger" })
</div>
</div>
#*localhost*#
#*<div class="g-recaptcha" data-sitekey="6LdKaUAUAAAAAMi2MkpRBxJYnmqWJmnJmF22RsRF1"></div>*#
</div>
</div>
#Html.HiddenFor(m => m.MobilePrefixCountry)
#Html.HiddenFor(m => m.ApartmentName)
#Html.HiddenFor(m => m.NumberOfNights)
<br />
<div class="align-left pt-10">
<div class="form-group">
<input id="submitBtn" class="btn btn-default" type="submit" value="Send Message" />
</div>
</div>
<div id="successAlert" class="alert alert-success collapse">
×
<strong>Success!</strong> You have successfully send email. Our staff will respond in shortest amount of time.
</div>
<div id="errorAlert" class="alert alert-danger collapse">
×
<strong>Sending failed!</strong> Please fill all neccessery fields and try again.
</div>
}
</div>
</div>
I have this js:
$("#contactForm").submit(function (e) {
var form = $(this);
$('#submitBtn').attr("disabled", true);
$("#submitBtn").attr("value", 'Sending...');
//$.ajax({
// type: "POST",
// async:false,
// url: "/Home/SendEmail",
// data: form.serialize(), // serializes the form's elements.
// success: function (data) {
// if (data == "True") {
// $('#successAlert').show('fade')
// .delay(9000)
// .fadeOut(function () {
// $(this).remove();
// });
// }
// else if (data == "False") {
// $('#errorAlert').show('fade')
// .delay(6000)
// .fadeOut(function () {
// $(this).remove();
// });
// }
// }
//});
setTimeout(function () {
$('#submitBtn').attr("disabled", false);
$("#submitBtn").attr("value", 'Send Message');
}, 3000);
e.preventDefault();
});
This works just fine, but when I uncomment ajax section, I am not able to see transition of toggling button disable/enable. I've put async:false.
UPDATED (still not working):
$("#contactForm").submit(function (e) {
var form = $(this);
$('#submitBtn').attr("disabled", true);
$("#submitBtn").attr("value", 'Sending...');
$.ajax({
type: "POST",
async: false,
url: "/Home/SendEmail",
data: form.serialize(), // serializes the form's elements.
success: function (data) {
if (data == "True") {
$('#successAlert').show('fade')
.delay(9000)
.fadeOut(function () {
$(this).remove();
});
}
else if (data == "False") {
$('#errorAlert').show('fade')
.delay(6000)
.fadeOut(function () {
$(this).remove();
});
}
$('#submitBtn').attr("disabled", false);
$("#submitBtn").attr("value", 'Send Message');
},
error: function () {
$('#submitBtn').attr("disabled", false);
$("#submitBtn").attr("value", 'Send Message');
}
});
e.preventDefault();
});
Change async: false to async: true and enable button again in some callback of ajax request. As long as you keep async: false you are blocking main thread and changes for GUI elements will not take effect till function returns.
async from false to true is the only change to #adaptable.services' code.
Place your button enable code inside the ajax success.
This will enable the disabled button after ajax completion.
first make your <input type="submit"> to <button type="submit">Send Message</button>
and then try this..
<script>
$("#contactForm").submit(function (e) {
e.preventDefault();
var form = $(this);
$('#submitBtn').attr("disabled", true);
$("#submitBtn").html('Sending...');
$.ajax({
type: "POST",
async:false,
url: "/Home/SendEmail",
data: form.serialize(), // serializes the form's elements.
success: function (data) {
if (data == "True") {
$('#submitBtn').prop("disabled", false);
$('#submitBtn').html("Send Message");
$('#successAlert').show('fade')
.delay(9000)
.fadeOut(function () {
$(this).remove();
});
}
else if (data == "False") {
$('#submitBtn').prop("disabled", false);
$('#submitBtn').html("Send Message");
$('#errorAlert').show('fade')
.delay(6000)
.fadeOut(function () {
$(this).remove();
});
}
},
error: function () {
$('#submitBtn').prop("disabled", false);
$('#submitBtn').html("Send Message");
}
});
});
</script>
$('#button').attr("disabled", true);
$.ajax({
url: url,
data: data,
type: 'post',
dataType: 'json',
cache: false,
async: true,
complete: function(response){
$('#button').attr("disabled", false);
},
});
I created a function name is rate. When the page load the function is working. Ajax method is getting result from API. When the function done ng-repeat is working correctly. Later when I click dropdown menu item the function is running, but I want to get clicked dropdown menu item value to insert {{status.value}}. Also I have a different problem. When the loop is working browser is freezing. How can I solve this problem?
HTML code
<div class="analysisItem col-sm-6" ng-if="status">
<div class="item">
<div class="dropdown">
<div class="analysisbutton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div class="container">
<div class="row">
<div class="a col-12">Arz<br><span class="value">{{status.value}}</span><span class="dropdown-arrow"></span></div>
</div>
</div>
</div>
<div class="dropdown-menu w-100">
<a class="dropdown-item" ng-repeat="i in statusRes" data-type="status" data-value="{{i.valueint}}" ng-click="rate();">{{i.value}} <span class="float-right">%{{i.factor}}</span></a>
</div>
</div>
</div>
</div>
JS code
$scope.type = ["status", "category", "subCategory", "room", "buildingAge", "sfloor", "floor", "square", "price", "currency", "value", "feedback"];
$scope.rate = function (type) {
if (type) $scope.type[type] = type;
for (var i = 0; i < $scope.type.length; i++) {
setTimeout(function (i) {
$scope.params = {
lat: $scope.lat,
lng: $scope.lng,
time: $scope.time,
type: $scope.type[i]
}
$.ajax({
type: 'post',
url: "index.php",
dataType: 'json',
async: false,
cache: false,
xhrFields: {
withCredentials: true
},
data: $scope.params,
success: function (data) {
if (data.response) {
if ($scope.type[i] == "status") {
if (data.response == null || data.response == "") {
} else {
$scope.status = data.response[0];
$scope.statusRes = data.response;
}
}
if ($scope.type[i] == "category") {
if (data.response == null || data.response == "") {
} else {
$scope.category = data.response[0];
$scope.categoryRes = data.response;
}
}
if (!$scope.$$phase) $scope.$apply();
} else if (data.response == null) {
} else if (data.error) {
}
},
error: function (data) {
}
});
}, i * 2000, i);
}
}
I'm trying to send a post request to the Action with the Model data after the value of some of it's properties is changed :
#{
JsonSerializerSettings jss = new JsonSerializerSettings {
ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
}
<div id="contents">
<!--Lead Stage-->
#if (Model.LeadStagesNav != null)
{
for (int i = 0; i < Model.LeadStagesNav.Count; i++)
{
#Html.HiddenFor(a => a.LeadStagesNav[i].PermissionId)
<div class="form-group" style="margin-bottom:10px">
#Html.Label("Lead Stage", new { #class = "col-md-2" })
<div style="display:inline-block;position:relative">
#Html.DropDownListFor(model => model.LeadStagesNav[i].Name, null, new { #class = "form-control", #style = "width:200px", onchange = "ChangeValue()" })
</div>
#if (ViewData["LeadStagesNav[" + i + "].LeadStatus"] != null)
{
<!--Lead Status-->
#Html.Label("Lead Status", new { #style = "margin-left:15px;margin-right:15px" })
<div style="display:inline-block;position:relative">
#Html.DropDownListFor(model => model.LeadStagesNav[i].LeadStatus, null, new { #class = "form-control", #style = "width:200px", onchange = "ChangeValue()" })
</div>
if (ViewData["LeadStagesNav[" + i + "].LeadSubStatus"] != null)
{
#Html.Label("Lead Sub Status", new { #style = "margin-left:15px;margin-right:15px" })
<div style="display:inline-block;position:relative">
<!--Lead Sub Status-->
#Html.DropDownListFor(model => model.LeadStagesNav[i].LeadSubStatus, null, new { #class = "form-control", #style = "width:200px" })
</div>
}
}
</div>
<!--Delete Button-->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Delete Lead Stage"
onclick="document.getElementById('index').value = #i"
name="submit" class="btn btn-default" />
<input type="hidden" id="index" name="index" />
</div>
</div>
}
}
</div>
<script type="text/javascript">
window.ChangeValue = function () {
var model = #Html.Raw(JsonConvert.SerializeObject(Model, Formatting.Indented, jss));
$.ajax({
method: "POST",
url: "/CmsPermissions/Edit",
data: { permission: model },
success: function (data) {
$("#contents").html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
};
the thing is the The problem is that I get the old model data
posted to the Action instead of the
new data after the dropdown selected value has changed,
Anyone has any idea ?
that is because you are passing the old model as data
var model = #Html.Raw(JsonConvert.SerializeObject(Model, Formatting.Indented, jss));
you need to serialize your form and pass it an example is
function SubmitForm() {
var data = $("#YourFormID").serialize();
var url = "/YourURL/ACtion"
var form = $('#policyForm')[0]
var formdata = false;
if (window.FormData) {
formdata = new FormData(form);
}
return $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formdata ? formdata : data,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
error: function () {
$('#imgLoadingForPortal').modal('hide');
Lobibox.notify('error', {
size: 'mini',
rounded: true,
delay: false,
position: 'center top', //or 'center bottom'
msg: 'Something went wrong..please try again later',
sound: false,
delay: 5000,
});
}
})
}