I'm having a little problem with my rails app, I've created a cascade city selection system, we first select the country and then I make an internal call to receive the state json of the states linked to the country and then once the state is selected, I do the same for the city, everything works fine except for a small bug.
When I load the page for the first time, I can change the city and it saves properly. on the other hand if I change country, state and city, then the country is safeguarded as it should be, the state too but not the city. when the page and returned after saving the city and is always the 1st of the list and it is only at this moment that if I change only the city it is saved well.
On the ruby side, I put a byebug in a before_update and I noticed that in the first case the one where the city is badly saved, it's the index of the city that I receive and not the full name of the city, whereas in the other case when it saves itself properly it's the name of the city that I get.
side js I recover the value of the dropdown in an onchange event that I send in console, and in any case it is the name of the city that appears.
person_settings.js
// This is executed when contry_select is changed
$('#person_country_of_birth').on('change', function(event) {
var stateInput = $("#person_state_of_birth");
var country_code = $('#person_country_of_birth :selected').val();
var sendDatas = { "country_code": country_code };
getDatas(sendDatas, stateInput, "update_states");
});
// This is executed when state_select is changed
$('#person_state_of_birth').on('change', function(event) {
var cityInput = $("#person_city_of_birth");
var country_code = $('#person_country_of_birth :selected').val();
var state_code = $('#person_state_of_birth :selected').val();
var sendDatas = { "country_code": country_code, "state_code": state_code};
getDatas(sendDatas, cityInput, "update_cities");
});
// Check value when change (test)
$('#person_city_of_birth').on('change', function(e) {
console.log(this.options[e.target.selectedIndex].text)
// $('#person_city_of_birth').text(this.options[e.target.selectedIndex].text);
});
// This function send selected data to get cascading response
function getDatas(sendDatas, inputTarget, urlAction){
var url = window.location.origin + "/dynamic_select/"
$.ajax({
type: "GET",
url: url + urlAction,
dataType: "json",
data: sendDatas,
success: function(response){
if(getType(response) == "[object Array]"){
console.log(response)
console.log(sendDatas)
appendStateData(response, inputTarget);
}
else if(getType(response) == "[object Object]"){
appendCityData(response, inputTarget);
}
},
error: function(resp) {
alert(resp)
console.log(resp)
}
});
};
// Append states datas on state_select
function appendStateData(datas, state_input){
state_input.empty();
$.each(datas, function(index, value) {
state_input.append("<option value="+index+">"+value+"</option>");
});
};
// Append cities datas on city_select
function appendCityData(datas, city_input){
city_input.empty();
$.each(datas, function(index, value) {
city_input.append("<option value="+index+">"+value+"</option>");
});
};
// This function check the type of response
// State datas is an object
// City datas is an array
function getType( obj ){
return Object.prototype.toString.call(obj).toString();
};
contact.haml
.row
.col-6
.inline-label-container
= form.label :spoken_languages, #spoken_languages_title
%span.alert-box-icon
= icon_tag("information", ["icon-fix"])
%small
= t("settings.profile.spoken_languages_description")
= form.select(:spoken_languages, #spoken_languages_datas.each { |p| [p] }, {prompt: 'Select a language'}, {multiple: true, size: #spoken_languages_datas.count, style: 'height: 180px;'})
.col-3
= form.label :birth_date, t("settings.profile.birth_date")
= form.date_field :birth_date, :class => "date_field", :maxlength => "10", paceholder: "30/12/2018", style: "height: 40px; width: 250px;"
.col-3
= form.label :nationality, t("settings.profile.nationality")
= form.select(:nationality, #nationality_datas)
.col-3
= form.label :country_of_birth, t("settings.profile.country_of_birth")
= form.country_select :country_of_birth, priority_countries: eu_countries_codes, include_blank: false
.col-3
= form.label :state_of_birth, t("settings.profile.state_of_birth")
= form.select(:state_of_birth, CS.states(target_user.country_of_birth).each { |sym, state| [sym, state]}.to_a.map {|arr| arr.reverse!})
.col-6
= form.label :city_of_birth, t("settings.profile.city_of_birth")
= form.select(:city_of_birth, CS.cities(target_user.state_of_birth, target_user.country_of_birth))
It solved, the problem came from the fact that for cities it was an array and not a hash that I received from the hit the index was used as a value, I added a javascript method that does the conversion for me after I received the answer and everything works.
// This function covert array into object
// and set keys == value ex : {lisboa: "lisboa"}
function toObject(arr) {
console.log(arr)
var rv = {};
for (var i = 0; i < arr.length; ++i)
rv[arr[i]] = arr[i];
console.log(rv)
return rv;
}
Related
I'm attempting to populate the options on a select element on a parent window with data returned from an ajax call that's called from a child (popup) form. The child form is called from the parent with window.open.
The odd thing is removing the select options works; this succeeds:
$('#selElement', opener.document).find('option').remove().end();
But appending as shown below, throws SCRIPT5022: Exception thrown and not caught.
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
I've also tried
$('#selElement', opener.window.document).append($("<option />").val('').text('---Select---'));
here's the code:
// the line below works; it removes all of the options from the drop-down
$('#selElement', opener.document).find('option').remove().end();
// the ajax call below returns the right data
$.ajax({
url: 'actions.cfc?method=getOptions&returnFormat=json',
dataType: 'json',
// the value being sent here just limits the options returned in the results
data: {myType: $('#myType').val()},
async:false,
success: function(response) {
// getting the right data back
console.log(response);
// the line below results in SCRIPT5022: Exception thrown and not caught
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
// never get this far unless I comment out the line above; then the error is thrown here
for (var i = 0; i < response.DATA.length; i++) {
$('#selElement', opener.document).append($("<option />").val(response.DATA[i][0]).text(response.DATA[i][1]));
}
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
}
});
Any ideas?
If you want to create the element in another document, you have to specify it in the creation like in the target as well:
$('#selElement', opener.document).append($("<option />", opener.document).val('').text('---Select---'));
//Specify the document where the element will be created ^
Otherwise the element will be created in the child document and an error will be thrown when the code tried to add it to the parent document.
Also, you can simplify the option creation:
$("<option value=''>---Select---</option>", opener.document)
Use .map to create you option list and append it to select tag.
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
$('#selElement', opener.document).append('<select>' + option.join('') + '</select>')
const response = { DATA: [
['Mary', 'Mary'],
['Peter', 'Peter'],
['John', 'John'],
['Abel', 'Abel'],
['Mike', 'Mike']
]}
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
option.unshift('<option>-----Select-----</option>');
function myFunction() {
const div = document.getElementById('test');
div.innerHTML = ('<select>' + option.join('') + '</select>');
}
<button onclick="myFunction()">Try it</button>
<div id="test"></div>
This a hybrid jquery/javascript solution I use sometimes ...
var mySubtype = document.getElementById("uploadSubtype");
//Create arrays of options to be added
if(filetype == "2D"){
var array = ['','Proofs','Graphic','Other'];
} else if(filetype == "3D"){
var array = ['','Prelims','Presentation','Controls','Final'];
} else if(filetype == "Accounting"){
var array = ['','W-9','Other'];
}
$( "#uploadSubtype" ).append("<span class='subtype_form_label'>Subtype</span>");
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "subtype";
selectList.name = "subtype";
selectList.classList.add("form_field");
mySubtype.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i];
selectList.appendChild(option);
}
I am new to suitescript. Openly telling I hardly wrote two scripts by seeing other scripts which are little bit easy.
My question is how can read a data from sublist and call other form.
Here is my requirement.
I want to read the item values data highlighted in yellow color
When I read that particular item in a variable I want to call the assemblyitem form in netsuite and get one value.
//Code
function userEventBeforeLoad(type, form, request)
{
nlapiLogExecution('DEBUG', 'This event is occured while ', type);
if(type == 'create' || type == 'copy' || type == 'edit')
{
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
//var itemfield = nlapiGetFieldValue('item')
//nlapiLogExecution('DEBUG','This value is = ',itemfield);
var formname = nlapiLoadRecord('itemreceipt',itemfield);
nlapiLogExecution('DEBUG','This value is = ',formname);
}
}
}
How can I proceed further?
I want to read that checkbox field value in the following image when i get the item value from above
I recommend looking at the "Sublist APIs" page in NetSuite's Help; it should describe many of the methods you'll be working with.
In particular you'll want to look at nlobjRecord.getLineItemValue().
Here's a video copmaring how to work with sublists in 1.0 versus 2.0: https://www.youtube.com/watch?v=n05OiKYDxhI
I have tried for my end and got succeed. Here is the answer.
function userEventBeforeLoad(type, form, request){
if(type=='copy'|| type =='edit' || type=='create'){
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
var itemcount = nlapiGetLineItemCount('item');
nlapiLogExecution('DEBUG','This value is = ',+itemcount);
for(var i=1;i<=itemcount;i++)
{
var itemvalue = nlapiGetLineItemValue('item','itemkey',i);
nlapiLogExecution('DEBUG','LineItemInternalID = ',itemvalue);
var itemrecord = nlapiLoadRecord('assemblyitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
if(itemrecord == null){
var itemrecord = nlapiLoadRecord('inventoryitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
}
var value = itemrecord.getFieldValue('custitem_mf_approved_for_dock_to_stock');
nlapiLogExecution('DEBUG',"Checkboxvalue = ",value);
if(value == 'F'){
nlapiSetLineItemValue('item','location',i,9);
nlapiSetLineItemDisabled ('item','location',false,i );
}
else{
nlapiSetLineItemValue('item','location',i,1);
nlapiSetLineItemDisabled ('item','location',true,i );
}
}
}
}
}
So I have a registration form for archery contests and I want users to select 2 things (their age category and their bow type).
Once those 2 are selected, I want the next field (select) to show up and be populated with information from my mysql database.
This field is a selection of shooting levels, differenciated in classes.
In the database, I have 4 tables.
1 for age category (id, name)
1 for bow type (id, name)
1 for shoot level (id, name)
1 table to link all above (id, ac_id, bt_id, sl_id)
So based on radio 1 being clicked and radio 2 being clicked, I want to fire a query on the link table to only get the shooting levels which belong to the 2 radio values..
Can anyone please help me with this?
Try this:
$('#age').click(function(){
var age = $(this).val();
var bow = $('#bow').val();
function getShootingLevel(age, bow);
});
$('#bow').click(function(){
var age = $('#age').val();
var bow = $(this).val();
function getShootingLevel(age, bow);
});
function getShootingLevel(age, bow)
{
// ajax call
}
P.S. You can also check if radio is selected or not.
I got it :)
$(document).ready(function() {
$('input[type=radio][name=leeftijdscategorie]').change(function() {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
$('input[type=radio][name=schiettechniek]').change(function() {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
});
function removeOptions(selectbox) {
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--) {
selectbox.remove(i);
}
}
function GetLevels(agetype,bowtype) {
removeOptions(document.getElementById(\"schietklasse\"));
$.ajax({
url: '/info/wscript.php',
data:
{
agetype: agetype,
bowtype: bowtype
},
type: 'post',
dataType: 'json', // returns response data as json//
success: function(output) {
var selectBox = document.getElementById(\"schietklasse\");
var options = output; //JSON.parse(output);
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add( new Option(option.text, option.value, option.selected) );
}
}
});
}
I basically made this radio check seperate (so double) because I want people to be able to change their choice. Now, it fires a POST to a php file which gets the information and returns it as JSON.
Hi here is a jquery function i am working on i have appended a particular div. The div has 2 inputs I am trying to capture the input values in data_to_send array but it only captures one input because the names are not unique.
function() {
$('#si-goal-link-btn').click(function() {
$('#si-goal-links').append('<div class="goal-link si-goal"><label for="iconURL">Icon URL</label><input class="si-goal-link form-control" type="file" name="iconURL"><br><label for="title">Title</label><input type="text" placeholder="Enter title" class="si-goal-link form-control" name="title"><br><hr></div>')
})
$('form #si-btn').click(function(e) {
e.preventDefault()
var self = $(this)
var data_to_send = {}
$('form').find('.si-input').each(function() {
if ( $(this).attr('name') != undefined) {
if ($(this).hasClass('si-wysiwyg')){
data_to_send[$(this).attr('name')] = $(this).code()
}
if ($(this).hasClass('si-goal-link')) {
//UNABLE TO STORE THE VALUE HERE
data_to_send[$(this).attr('name')] = $(this).val()
}
data_to_send[$(this).attr('name')] = $(this).val()
}
})
var url = $('form').data('si-location')
$.post(url, data_to_send, function(data) {
})
})
}
How do i capture this data and store it as an array within an array over here ?
To get array-within-array-like behavior in Javascript, you will need to make an array a property of your data object, and then push() the same named values onto that array.
var data_to_send = {};
data_to_send.si-goal-link = [];
//inside loop or wherever is needed
data_to_send.si-goal-link.push($(this).val());
$.post(url, $('form').serialize(), function(data) {
})
I am trying to populate a sublist in a suitelet with data from a custom saved search that I have already created. My problem is that the sublist is only populating data from fields that correspond to the "type" of saved search I am doing. For example, in this instance the saved search is a "transaction" type search. If, for example, I want to reference a customer field withing the saved search, say "Name" and "Billing Address", this data will not populate the sublist in the suitelet. All other fields that are being referenced in the Transaction record itself populate the sublist fine. I was just wondering if anyone has ever run into the same issue, anyways here's the code I'm trying to implement.
var form,
sublist;
//GET
if (request.getMethod() == 'GET')
{
//create form
form = nlapiCreateForm('Test Custom Suitelet Form', false);
//create sublist to show results
sublist = form.addSubList('custpage_sublist_id', 'list', 'Item List');
//form buttons
form.addSubmitButton('Submit');
form.addResetButton('Reset');
// run existing saved search
var searchResults = nlapiSearchRecord('transaction','customsearchID');
var columns = searchResults[0].getAllColumns();
// Add the search column names to the sublist field
for ( var i=0; i< columns.length; i++ )
{
sublist.addField(columns[i].getName() ,'text', columns[i].getLabel() );
nlapiLogExecution('DEBUG', 'Column Label',columns[i].getLabel());
}
//additional sublist fields
sublist.addMarkAllButtons();
sublist.addField('custfield_selected', 'checkbox', 'Selected');
sublist.setLineItemValues(searchResults)
response.writePage(form);
}
If you review the nlobjSublist docs you'll see that sublist.setLineItemValues can also take an array of hashes. What does work is:
function getJoinedName(col) {
var join = col.getJoin();
return join ? col.getName() + '__' + join : col.getName();
}
searchResults[0].getAllColumns().forEach(function(col) {
sublist.addField(getJoinedName(col), 'text', col.getLabel());
nlapiLogExecution('DEBUG', 'Column Label', col.getLabel());
});
var resolvedJoins = searchResults.map(function(sr) {
var ret = {
id: sr.getId()
};
sr.getAllColumns().forEach(function(col) {
ret[getJoinedName(col)] = sr.getText(col) || sr.getValue(col);
});
return ret;
});
sublist.setLineItemValues(resolvedJoins);