How to get dropdown clicked item value angular js - javascript

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);
}
}

Related

Show/Hide div Ajax Jquery

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();
}
});
});

Clear jeasyui form fields after successful submit

I'm using a jeasyui form, inside a xoops module, in which I'm trying to clear all the form fields once the data has successfully submitted.
I've already consulted this question, but it didn't solve the problem in my case.
My HTML:
<div class="easyui-panel" title="Capture Reqs" style "width:100%;
max-width:600px; padding:30px 60px;">
<form action = "captureReqs_Save.php" id ="ff" class = "easyui-form"
method ="post" data-options = "novalidate:true">
<div style="margin-bottom:20px"> Area <br>
<input id="idArea" class="easyui-combobox" style="width:260px" name="idArea"
data-options="
url:'areasJson.php?idZona=<?php echo $idZone; ?>',
label:'Area:',
valueField: 'id',
textField: 'desc',
required:true
">
</div>
<div style="margin-bottom:20px"> Material
<input id="IdMaterial" class="easyui-combobox" style="width:100%"
name="IdMaterial" data-options="
loader: myloader,
mode: 'remote',
valueField: 'code',
textField: 'desc',
required:true
">
<div style="margin-bottom:20px"> Qty
<input class="easyui-textbox" name="quantity" style="width:100%"
data-options="label:'Qty:',required:true, validType:'number'">
</div>
<div style="margin-bottom:20px">
</form>
<div style="text-align:center;padding:5px 0">
<a href="javascript:void(0)" class="easyui-linkbutton"
onClick = "submitForm()" style="width:80px"> Submit</a>
<a href="javascript:void(0)" class="easyui-linkbutton"
onClick = "resetForm()" style = "width:80px"> Clear </a>
</div>
</div>
Script:
<script>
var myloader = function (param, success, error) {
var q = param.q || '';
if (q.length <= 2) {
return false
}
$.ajax({
url: 'materialJson.php?idArea=' + $('#idArea').combobox('getValue'),
dataType: 'json',
data: {
q: q
},
success: function (data) {
var items = $.map(data, function (item, index) {
return {
code: item.code,
desc: item.desc
};
});
success(items);
},
error: function () {
error.apply(this, arguments);
}
});
}
function submitForm() {
$('#ff').form('submit', {
onSubmit: function () {
return $(this).form('enableValidation').form('validate');
}
});
}
function resetForm() {
$('#ff')[0].reset();
}
</script>
Try calling resetForm. I converted to use promise style ajax and added resetForm
var myloader = function (param, success, error) {
var q = param.q || '';
if (q.length <= 2) {
return false
}
$.ajax({
url: 'materialJson.php?idArea=' + $('#idArea').combobox('getValue'),
dataType: 'json',
data: {
q: q
}
}).then(function (data) {
var items = $.map(data, function (item, index) {
return {
code: item.code,
desc: item.desc
};
});
success(items);
}).fail(function () {
error.apply(this, arguments);
});
}
function submitForm() {
$('#ff').submit(function () {
if ($(this).form('enableValidation').form('validate')) {
$.post($(this).attr('action'), $(this).serialize(), function (response) {
clearForm();
});
}
return false;
});
}
function resetForm() {
$('#ff')[0].reset();
}

Knockoutjs foreach n rows check if dropdown has value

I have this html markup:
<!-- ko foreach: Orders -->
<div class="row">
<div>
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }">
</select>
</div>
<div>
<a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right">
<span class="glyphicon glyphicon-cloud-download"></span> Download
</a>
</div>
</div>
<!-- /ko -->
There will be n number of items in the foreach loop, that will not be known in the moment of development.
What I want to do is when the $root.RequestImage is clicked, the code needs to check if there is selection made in the respected dropdown for that row, if the selection is made then proceed further, otherwise display alert box with 'error' message.
So in the RequestImage that action should happen, this is the RequestImage function currently:
self.RequestImage = function () {
};
How can I achieve this?
Update
OrdersVM:
var self = this;
self.Orders = ko.observableArray([]);
$.ajax({
type: "POST", url: "/webservices/InfoWS.asmx/GetOrders",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
var orderIds = [];
ko.utils.arrayForEach(data.d, function (item) {
item._teacherOrders = ko.observable();
$.ajax({
type: "POST",
url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount",
contentType: "application/json; charset=utf-8",
data: "{'orderId': " + JSON.stringify(item.OrderId) + "}",
dataType: "json",
success: function (data) {
if (data) {
return item._teacherOrders(data.d);
}
},
error: function (n) {
alert('Error retrieving teachers for orders, please try again.');
}
});
item.TeacherNames = ko.computed(function () {
return item._teacherOrders();
});
self.Orders.push(item);
orderIds.push(item.OrderId);
});
}
},
error: function (data) {
var response = JSON.parse(data.responseText);
console.log("error retrieving orders:" + response.Message);
}
});
I would do it this way:
add an observable selectedTeacher to every order object
add value: selectedTeacher to your selects:
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select>
check that observable in your RequestImage event
if ( !data.selectedTeacher() ) {
alert('Error: select teacher')
} else {
alert('Success')
}
A working demo - Fiddle

React State change is not Rendering

I'm fairly new to React and I'm having an issue where my initial state is rendering, but when the state is changed via AJAX call (successful) is not causing the function to render again. So what happens is the 'getInitialState' sets a static list of categories and 'componentDidMount' gets a new list from my API. The call executes correctly and triggers a success, so I don't know why the dropdown isn't updating.
var Dropdown = React.createClass({
getInitialState: function() {
return {
listVisible: false,
display: ""
};
},
select: function(item) {
this.props.selected = item;
},
show: function() {
this.setState({ listVisible: true });
document.addEventListener("click", this.hide);
},
hide: function() {
this.setState({ listVisible: false });
document.removeEventListener("click", this.hide);
},
render: function() {
return <div className={"dropdown-container" + (this.state.listVisible ? " show" : "")}>
<div className={"dropdown-display" + (this.state.listVisible ? " clicked": "")} onClick={this.show}>
<span>{this.props.selected.name}</span>
<i className="fa fa-angle-down"></i>
</div>
<div className="dropdown-list">
<div>
{this.renderListItems()}
</div>
</div>
</div>;
},
renderListItems: function() {
var categories = [];
for (var i = 0; i < this.props.list.length; i++) {
var category = this.props.list[i];
categories.push(<div onClick={this.select.bind(null, category)}>
<span>{category.name}</span>
<i className="fa fa-check"></i>
</div>);
}
return categories;
}
});
var GridFilter = React.createClass({
getInitialState: function() {
return {categoryList: [{
name: "Cat1",
value: "#F21B1B"
}, {
name: "Cat2",
value: "#1B66F2"
}, {
name: "Cat3",
value: "#07BA16"
}] };
},
getCategories: function() {
var nextPage = 1; //increase the page count
ajax_url = "http://127.0.0.1:8200/api/categories/";
ajax_type = "GET";
ajax_data = {};
$.ajax({
url: ajax_url,
type: ajax_type,
contentType: 'application/x-www-form-urlencoded',
data: ajax_data,
dataType: 'json',
success: function(data) {
this.setState({
data: this.state.categoryList,
});
//loading("off");
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}, //end function
componentDidMount: function() {
this.getCategories();
},
render: function() {
return (
<div id="filter-bar" className="stamp">
<Dropdown list={this.state.categoryList} selected={this.state.categoryList[0]} />
<p className="filter-select">Categories <i className="fa fa-angle-down"></i></p>
<p className="filter-select">Type <i className="fa fa-angle-down"></i></p>
<p className="filter-text">Filters:</p>
</div>
);
}
});
if youre trying to change the categoryList state with your incoming data you need to change your set state to
this.setState({
categoryList: data,
});
what youre currently doing is adding a state with key data (even though there is no data key in your getInitialState function). and since youre not using this.state.data anywhere, nothing is changing, and so your ui does not appear to be updating

Jquery light switch setting starting state

I'm using this setup to show if light is turned on or off:
http://www.jquery2dotnet.com/2012/11/jquery-light-switch-on-off-using-css3.html
How can i choose wich switch state to start?
As of now I have a lightvalue in my database, 1 = on 0 = off. I use sql to retrieve this value and load the appropriate light bulb.
But how would i do this with the switch? I don't have switch1 and switch2 so i can load the one i want based on lightvalue.
here is the code:
light.js
var lightVal = document.getElementById("light-bulb2");
function getLightValue(r) {
var lightValue;
$.ajax({
url: 'Database/checklight.php',
type: "POST",
data: {room: r},
success: function(data) {
data1 = JSON.parse(data);
$.each(data1, function(key, val) {
lightValue = val.light;
lightVal.style.opacity = lightValue;
});
},
async: false
});
}
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {light: val, room: room},
success: function(data) {
data2 = JSON.parse(data);
if (data2 < 1) {
alert("Not Updated");
}
},
async: false
});
}
light.php
<div id="temptre">
<div id="light-bulb" class="off ui-draggable" >
<div id="light-bulb2" style="opacity: 0">
<script src="JS/light.js">
</script>
</div></div>
<div class="cube-switch">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
</div>
<script>
getLightValue(<?php echo $_SESSION['sess_room']; ?>);
$('.cube-switch .switch').click(function() {
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({'opacity': '0'});
updateLight(0, <?php echo $_SESSION['sess_room']; ?>);
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({'opacity': '1'});
updateLight(1, <?php echo $_SESSION['sess_room']; ?>);
}
});
</script>
If you want to make switch work, then you need to trigger the click event, so that it can be switch on and off (based on value).
// call(trigger) click event on success
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {
light: val,
room: room
},
success: function (data) {
data2 = JSON.parse(data);
if (data == 1) {
$('.cube-switch .switch').trigger('click', [{
forceStart: true
}]);
} else {
$('.cube-switch .switch').trigger('click', [{
forceStart: false
}]);
}
},
async: false
});
}
// change your click event to handle the passed argument
$('.cube-switch .switch').click(function (e, data) {
if (typeof data !== 'undefined') {
if (data.forceStart) {
// remove the active class, so that it can add the active class later to match switch on
$('.cube-switch').removeClass('active');
} else {
$('.cube-switch').addClass('active')
}
}
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({
'opacity': '0'
});
updateLight(0, <? php echo $_SESSION['sess_room']; ?> );
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({
'opacity': '1'
});
updateLight(1, <? php echo $_SESSION['sess_room']; ?> );
}
});
JSFIDDLE: http://jsfiddle.net/4rkQZ/152/
I'm not very good with php, but give div.cube-switch a class of 'active' if it's on, and remove the inline opacity style (tidy up the php by all means!)
<div href="" class="cube-switch <?php if ($on) { echo ' active'; } ?>">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
<div id="light-bulb" class="off ui-draggable">
<div id="light-bulb2" <?php if (!$on) { echo 'style="opacity:0"'; } ?>></div>
</div>

Categories