How to handle checkbox in this case? - javascript

I am sending some data to the database through a post request, and I have a checkbox in my app that I need to handle with a state
I am using this library which is confusing me a bit.
Here I have my checkbox in the render method
<Checkbox value="Active" ref="Active" defaultChecked={true} onCheck={this._isChecked} />
and the function to handle it
_isChecked = () => {
console.log('Checked: ');
}
I need it to be checked = true by default.
Now, here I have the function I am using in order to send the data to the post request
_addDealer = () => {
CreateDealersActions.createDealer({
DealerName : this.refs.DealerName.getValue(),
CardId : this.refs.CardId.getValue(),
NickName : this.refs.NickName.getValue(),
Picture : 'http://lorempixel.com/150/150/',
Active : // HERE I NEED TO SET THE VALUE OF THE CHECKBOX
LegalId : this.refs.LegalId.getValue(),
TypeId : this.refs.TypeId.getValue(),
});
}
Look at the Active : // HERE I NEED TO SET THE VALUE OF THE CHECKBOX part in that function, there is where I need to put the value of the check box.
So, what should I know in order to send the proper data in the key Active, as I am using this library, do I need to put state? Or is there any other way?

I am going to answer this question because probably some of you doesn't know the library I am using which is a pain in the ass and the docs are horrible.
You don't need to set an initial state because the checkbox component brings one attached already. So, in order for you to get the value of the checkbox, you don't need to set a function. With this I did is enough:
<Checkbox value="Active" ref="Active" defaultChecked={true} />
_addDealer = () => {
CreateDealersActions.createDealer({
DealerName : this.refs.DealerName.getValue(),
CardId : this.refs.CardId.getValue(),
NickName : this.refs.NickName.getValue(),
Picture : 'http://lorempixel.com/150/150/',
Active : this.refs.Active.state.switched,
LegalId : this.refs.LegalId.getValue(),
TypeId : this.refs.TypeId.getValue(),
});
}
so: this.refs.Active.state.switched is enough to get the proper value of the checkbox.

Related

Kendo Combo Box Scroll: automatically call function

I am new to Kendo and creating a project using it. I have encountered a very unique kind of problem. I am using select options in kendoCombox. What I am doing is that I am just updating the select box value on click of the edit button. The value is updated successfully but when I scroll, it automatically calls the function where I get all values. Here is my code:
I am updating the value using this:
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
<select class="span12" onchange="rackChange()" id="rackModelName" name="rackModelName"
tabindex="6">
</select>
The below function automatically calls on scroll change:
function getRackFun(libraryDeviceId,dataCenterId,type){
console.log("calling");
if(libraryDeviceId && dataCenterId){
$.ajax({
type : "GET",
dataType : "json",
url : "${getRacksByLocationId}&libraryDeviceId=" + libraryDeviceId+"&dataCenterId=" +dataCenterId,
success : function(result) {
if(result.length>0){
var jsonObject = jQuery.parseJSON(JSON.stringify(result));
$("#rackModelName").data("kendoComboBox").setDataSource(jsonObject);
}else{
if(type!="edit"){
$("#rackModelName").data("kendoComboBox").value("");
$("#rackModelName").val("");
$("#rackModelName").data("kendoComboBox").setDataSource([]);
$("#rackStartUnit").empty();
$("#rackStartUnit").append($('<option>',{
value : '',
text : '<liferay-ui:message key="inventory.please_select"></liferay-ui:message>'
}));
$("#rackEndUnit").val('');
}
}
}
});
}else{
$("#rackModelName").data("kendoComboBox").value("");
}
}
change the way you initialize the combobox to
$("#rackModelName").kendoComboBox({
...
change: rackChange, //your change function name
...
});
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
remove the on change from the html element
To know more about events trigger check this https://demos.telerik.com/kendo-ui/combobox/events

Changing ng-class of current element in execution

I have a form which gets generated at runtime. I'm trying to update the class of the input box if validation fails. I'm performing validation on ng-blur = "chaeckValidation()" Now if I'm using ng-class = "active" and set the variable in controller for $scope.active = "has-error-class".
What this is doing is updating class of all the elements in form to error-class css but I want to attach error-class css only to the element which failed validation.
I tried but couldn't find any success. I can't hardcode anything in form as the form is completely dynamic and moreover I'm performing validation through regular expression in function and want to display error message based on which regular expression failed.
Code:
prop.json
[
{ label : Application Name
cid : uniqueId
typeApex : CURRENCY
fieldPath : application_Name__c
type : NUMBER
value : ''
dbRequired : true
isRequired : false
},
{...similar array of JSON object ...},
{}
]
view.html
<div ng-if="prop.type != 'picklist' && prop.type != 'reference'">
<label for="{{prop.label}}">{{prop.label}}</label>
<input type="{{prop.type}}" id="inputFields{{prop.fieldPath}}" ng-blur="fieldValidation(prop.fieldPath, prop.typeApex, $event)" ng-model-options="{updateOn: 'blur'}"
class="form-control" name="{{prop.fieldPath}}" ng-model="fieldPathValue[prop.fieldPath]"
ng-required="isRequired({{prop.dbRequired}}, {{prop.required}})" ng-class ="active"/>
</div>
Controller
$scope.fieldValidation = function(fieldPath, type, $event) {
console.log('fieldPath in fieldValidation ',fieldPath);
var myMap = new Map();
myMap.set("Term__c","^[0-9]+$");
myMap.set("Loan_Amount__c","[0-9]+(\.[0-9][0-9]?)?");
//console.log("fieldPathValue ",$.parseJSON(JSON.stringify($scope.fieldPathValue)));
//console.log("fieldPathValue ",$scope.fieldPathValue);
var value = $event.target.value;
console.log("value ",value);
var reg = new RegExp(myMap.get(fieldPath));
console.log("regex test result ",reg.test(value));
console.log("event ",$event);
if(!reg.test(value)) {
//add error message classs to selected field
//display error message on top of field
$timeout(function(){
$scope.$apply(function () {
$scope.active = "has-error";
});
}, 0);
}
Result Image:
I have made an error in first input field which accepts float numbers and I have provided alphabets, so it throws error but that error is propogated to entire form and not only to the element which triggers it.
How can I make sure only element that fails validation on ng-blur gets the error-class-css attached.
I have tried doing this using getElementById but no success. Added the questions link below.
I have described more on my questions form element in one of my questions. DOM elements not getting updated from angular controller

Magento - reloadPrice() modifications

My client needs to make an operation on products custom options.
Using Magento CE, I create a product, and give it some custom options from within the built-in left hand side menu in "Manage products" > "Add new product", such as "mm" (millimeters) and "mt" (meters)
This product will have both radio options and a textbot input.
Let's say we have
Base price: 0
MM:
Radio option A which costs 0,9
Radio option B which costs 1,2
Radio option C which costs 2,3
MT:
Textbox value = unknown yet
Let's say user chooses Radio option B and enters 10 in the textfield
Price should be updates as such:
1,2 * 10 + 0
Which is
radio value cost * textbox value + base price
Is there any way to tell the code to take the value of the radio button, multiply it for the value of the textbox and sum it all to the base price?
Where could I look to see the current behavior of a product's custom options?
EDIT
I saw that whenever a value is selected, the reloadPrice() function is called.
I thought to check if both inputs are radio and text, then get the value of the text and multiply it for the value of the radio.
Is that right? Can you point me better?
This helps me, I hope this will also helps you
initialize : function(config){
this.config = config;
this.reloadPrice();
document.observe("dom:loaded", this.reloadPrice.bind(this));
},
reloadPrice : function(){
price = new Number();
config = this.config;
skipIds = [];
skipIds = [];
relatedword = [];
relatedvalue = [];
relatedid = [];
counter_each=0;
counter=1;
first=0;
areaValue=1;
submitbutton=true;
$$('body .product-custom-option').each(function(element){
var optionId = 0;
element.name.sub(/[0-9]+/, function(match){
optionId = match[0];
});
if (this.config[optionId]) {
if (element.type == 'checkbox' || element.type == 'radio')
{
if (element.checked)
{
if (config[optionId][element.getValue()])
{
<?php if(Mage::getVersion() >= 1.7): ?>
price += parseFloat(config[optionId][element.getValue()].price);
<?php else: ?>
price += parseFloat(this.config[optionId][selectOption.value]);
<?php endif; ?>
}
}
}
}
reloadPrice() does not update product price at server level. One way to do this product price update is by implementing checkout_cart_product_add_after event.
Do you custom logic at client level with javascript in detail page. Assign this value to some hidden variable under the form product_addtocart_form. A better way is to save to session to reduce client side vulnerabilities or you can find your own better way. Or Implement your login only in Observer method. Whatever you find secure.
Rewrite the class Mage_Checkout_Model_Cart to modify as,
public function addProduct($productInfo, $requestInfo=null)
{
...
Mage::dispatchEvent('checkout_cart_product_add_after', array('quote_item' => $result, 'product' => $product,'request_data'=>$request));
...
}
In your yourmodule/etc/config.xml:
<config>
...
<frontend>
...
<events>
<checkout_cart_product_add_after>
<observers>
<unique_name>
<class>modulename/observer</class>
<method>customPrice</method>
</unique_name>
</observers>
</checkout_cart_product_add_after>
</events>
...
</frontend>
...
</config>
And then create an Observer class at yourmodule/Model/Observer.php
class <namespace>_<modulename>_Model_Observer
{
public function customPrice(Varien_Event_Observer $observer)
{
// Get the quote item
$item = $observer->getQuoteItem();
$request=$observer->getRequestData();
// Ensure we have the parent item, if it has one
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
// Load the custom price
$price = "custom price logic";//whatever from your hidden value or by some other mean.
// Set the custom price
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
// Enable super mode on the product.
$item->getProduct()->setIsSuperMode(true);
}
}
For more information check here

Angular js, on select element i want to POST data to save it in the database then i want to update it with PUT without page reload

I have a table which had a select field in it which I'd like to save into database if it dosnt exist yet through POST data. If it does exist then I'd like to update the already existing row in the database.
This can be found in the tbody in which i have my tablerow with an ng-repeat to display all data from a json.
<td>
<select id="statusSelect{{anime.id}}" ng-model="statusId" ng-options="animeStatus.id as animeStatus.status for animeStatus in animeStatuses"
ng-change='addUserAnime( "<?php echo Yii::app()->user->id; ?>", anime.id, statusId )'>
</select>
</td>
Next this is my code for what im trying to do in the angular controller:
$scope.addUserAnime = function( userId, animeId, statusId, userAnime )
{
if ( userId == '' ) {
//alert user that he/she needs to log in first
} else {
//loop through my json where i saved from which user which anime is saved with which status
for (var i = 0; i < $scope.usersAnime.length; i++) {
//if there is an already existing entry then i want to update it if not then i want to introduce it into DB with POST
if ($scope.usersAnime[i].anime_id == animeId && $scope.usersAnime[i].user_id == userId) {
$scope.userAnime = $.extend({}, $scope.usersAnime[i]);
$scope.userAnime.status_id = statusId;
$scope.userAnime.date_modified = today;
saveUserAnime();
return;
}
}
$scope.userAnime = {
id: 0,
user_id: userId,
anime_id: animeId,
status_id: statusId,
rating: '',
date_modified: today
};
saveUserAnime();
}
};
Problem is that if i POST a new entry it gets saved in the database, but if i dont reload the page and i change the select again giving it a new option it gets POSTed again instead of using PUT for update.In the end i end up with two entries instead of one. I want to introduce it to database on first select and i want to update it if its changed after. Is that possible. I tryed doing it with $dirty using the table as form but thats a nono.
In the saveUserAnime() function its correctly deffined to use POST if its new entry and use PUT if its an existing one. I have another form for which it works. The problem must be in this current function.
Just put that code where you get the object with the animeStatus and put that in a function and call it directly after that. Now you can call that function when your POST is done, so the new data will be loaded.
Otherwise you could also check through SQL, if that value exists in your table, so you don't need your check in angularjs, that would be easier than this one.

JSTL checkbox not working

Situation:
When we tick the checkbox, a post request is send with checkbox value as false
And we set the Model as true in the validation.
Issue
But the issue is this Model object which is also a session attribute do not reflect this change on the jsp. so the issue is obj.value is always false in both situations ?
<div class="block">
<label class="medium">Attach authority:</label>
<input type="checkbox" value="${Model.noticeDetailsModel.fullAuthority}"
<c:if test="${Model.noticeDetailsModel.fullAuthority}">checked="checked"</c:if>
id="fullAuthority" onchange="javascript: setNoticeDetails(this);"/>
</div>
//set up details
function setNoticeDetails(obj) {
$.post("generateNotice.do", {
value : obj.value,
name : obj.id,
stage : "setNoticeDetails"
});
}
Situation 2: When we tick off the checkbox, a post request is again send with checkbox value as false rather than true ( as we set the value as true in the model object namely "Model") after the first request was send
As I cant see the Controller code, I assume that the java side, i.e receiving of post request works ok
However :
Your function setNoticeDetails sends an ajax request, the response of which is ignored by your code because you have not implemented a success handler. See http://api.jquery.com/jquery.post/ for more details.
So because its an ajax request, the html/page is not reloaded - instead you should manipulate the html through javascript - e.g if you just want to change the value of the checkbox, do this :
function setNoticeDetails(obj) {
$.post("generateNotice.do", {
value : obj.value,
name : obj.id,
stage : "setNoticeDetails",
success: function(data) {
if ( $("#fullAuthority").val() === "true" ){
$("#fullAuthority").val("false");
} else {
$("#fullAuthority").val("true");
}
}
});
}

Categories

Resources