Change liferay-ui:input-localized XML with javascript - javascript

I have the following tag in my view.jsp:
<liferay-ui:input-localized id="message" name="message" xml="" />
And I know that I can set a XML and have a default value on my input localized. My problem is that I want to change this attribute with javascript. I am listening for some changes and call the function "update()" to update my information:
function update(index) {
var localizedInput= document.getElementById('message');
localizedInput.value = 'myXMLString';
}
Changing the value is only updating the currently selected language input (with the whole XML String). The XML String is correct, but I am not sure on how to update the XML for the input with javascript.
Is this possible?
PS: I have posted this in the Liferay Dev forum to try and reach more people.

After a week of studying the case and some tests, I think that I found a workaround for this. Not sure if this is the correct approach, but it is working for me so I will post my current solution for future reference.
After inspecting the HTML, I noticed that the Liferay-UI:input-localized tag creates an input tag by default, and then one more input tag for each language, each time you select a new language. Knowing that I created some functions with Javascript to help me update the inputs created from my liferay-ui:input-localized. Here is the relevant code:
function updateAnnouncementInformation(index) {
var announcement = announcements[index];
// the announcement['message'] is a XML String
updateInputLocalized('message', announcement['message']);
}
function updateInputLocalized(input, message) {
var inputId = '<portlet:namespace/>' + input;
var xml = $.parseXML(message);
var inputCurrent = document.getElementById(inputId);
var selectedLanguage = getSelectedLanguage(inputId);
var inputPT = document.getElementById(inputId + '_pt_PT');
inputPT.value = $(xml).find("Title[language-id='pt_PT']").text();
var inputEN = document.getElementById(inputId + '_en_US');
if (inputEN !== null) inputEN.value = $(xml).find("Title[language-id='en_US']").text();
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
var inputLabel = getInputLabel(inputId);
if (selectedLanguage == 'pt-PT') inputLabel.innerHTML = '';
else inputLabel.innerHTML = inputPT.value;
if (selectedLanguage == 'pt-PT') inputCurrent.value = inputPT.value;
else if (inputEN !== null) inputCurrent.value = inputEN.value;
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
}
function getSelectedLanguage(inputId) {
var languageContainer = document.getElementById('<portlet:namespace/>' + inputId + 'Menu');
return languageContainer.getElementsByClassName('btn-section')[0].innerHTML;
}
function getInputLabel(inputId) {
var boundingBoxContainer = document.getElementById(inputId + 'BoundingBox').parentElement;
return boundingBoxContainer.getElementsByClassName('form-text')[0];
}
function waitForElement(elementId, inputCurrent, inputId, xml) {
window.setTimeout(function() {
var element = document.getElementById(elementId);
if (element) elementCreated(element, inputCurrent, inputId, xml);
else waitForElement(elementId, inputCurrent, inputId, xml);
}, 500);
}
function elementCreated(inputEN, inputCurrent, inputId, xml) {
inputEN.value = $(xml).find("Title[language-id='en_US']").text();
var selectedLanguage = getSelectedLanguage(inputId);
if (selectedLanguage == 'en-US') inputCurrent.value = inputEN.value;
}
With this I am able to update the liferay-ui:input-localized inputs according to a pre-built XML String. I hope that someone finds this useful and if you have anything to add, please let me know!

To change the text value of an element, you must change the value of the elements's text node.
Example -
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "new content"
Suppose "books.xml" is loaded into xmlDoc
Get the first child node of the element
Change the node value to "new content"

Related

How to read a sublist data in netsuite?

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

Check if a text is HTML or not

I am using Meteor and I am trying to check if a text is html. But usual ways do not work. This is my code:
post: function() {
var postId = Session.get("postId");
var post = Posts.findOne({
_id: postId
});
var object = new Object();
if (post) {
object.title = post.title;
if ($(post.content).has("p")) { //$(post.content).has("p") / post.content instanceof HTMLElement
object.text = $(post.content).text();
if (post.content.match(/<img src="(.*?)"/)) {
object.image = post.content.match(/<img src="(.*?)"/)[1];
}
} else {
console.log("it is not an html------------------------");
object.text = post.content;
}
}
return object;
}
Actually, this is the most "working" solution I have used up to now. Also, I pointed out the two most common ways which I use (next to the if statement). Is it possible to happen without regex.
Can use approach you already started with jQuery but append response to a new <div> and check if that element has children. If jQuery finds children it is html.
If it is html you can then search that div for any type of element using find().
// create element and inject content into it
var $div=$('<div>').html(post.content);
// if there are any children it is html
if($div.children().length){
console.log('this is html');
var $img = $div.find('img');
console.log('There are ' + $img.length +' image(s)');
}else{
console.log('this is not html');
}
Use the jquery $.parseHTML function to parse the string into an array of DOM nodes and check if it has any HTMLElement.
var htmlText = "----<b>abc</b>----<h3>GOOD</h3>----";
htmlText = prompt("Please enter something:", "----<b>abc</b>----");
var htmlArray = $.parseHTML(htmlText);
var isHtml = htmlArray.filter(function(e){ return e instanceof HTMLElement;}).length;
console.log(htmlText);
//console.log(htmlArray);
if (isHtml)
console.log(isHtml + " HTML Element(s) found.");
else
console.log("No HTML Elements found!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

"FORBIDDEN You don't have permission to access /greenfloyd/php/bm_edit_xml.php on this server."

I've been sweating over this the last three days, I am baffled!
The input html launches an xml scan of a web site to gather text, images and links which populate a form for the user to select what they want to save. (The output eventually becomes a bookmark stored at greenfloyd.org.) The problem began a month or so ago, the scan started crashing with a "Forbidden 403" error pointing to my php code file, on the gf server (dir/file permission at 0644). The problem revolves around the links (url and text) gathered and placed into a box , the url is put in the value, and the link text into the innerHTML. The default is that none of the links are selected, the user can then select one or more links from this box, or manually add a link via two fields that get put into the select box, and become part of the form.
<form id = "bmInputForm" onsubmit = "bmSub(); return false;" onreset = "bmInputFormReset();" action = "http://greenfloyd.org/greenfloyd/php/bm_input_xml.php" method = "post" enctype = "multipart/form-data" class = "readerBox">...
<code><input type = "url" id = "link1Url" class = "input_size" size = "40" maxlength = "250" value ="" onclick = "this.select();" title = "Enter a standard url for this related link.">
<input id = "link1Title" class = "input_size" size = "40" maxlength = "150" value = "" onclick = "this.select();" title = "Enter a short title for this related link.">
<button type = "button" onclick = "relatedAdd()" title = "Add to related links list.">[+]</button>
<hr style="width:25%;">
<select id = "relatedSelect" name = "related_select[]" multiple title = "To select/unselect hold down the Ctrl key and click an option." onchange = "relatedCheck();" style = "width:80%;"></select></code>
The scan is an ajax xml call and returns elements from the target url, including the following:
<code>//echo "<related url='".rawurlencode($valid_url)."' txt='".htmlspecialchars($related_text, ENT_QUOTES,'UTF-8')."'></related>";
err = false;
try { var relatedNode = ( xmlDoc.getElementsByTagName("related") ) ? xmlDoc.getElementsByTagName("related") : false; }
catch(err) { err = true; relatedNode = false; }
result += ( !relatedNode ) ? "<li>Scanner unable to retrieve relatedNode || "+err+"</li>" : "<li>Link scan found: "+relatedNode.length+" entries.</li>";
if( relatedNode.length > 0 )
{
clearCache("relatedSelect");
var selObj = document.getElementById("relatedSelect");
for(var i = 0; i < relatedNode.length; i++)
{
val = unescape(relatedNode[i].getAttribute("url"));
str = unescape(relatedNode[i].getAttribute("txt"));
opt = document.createElement("option");
opt.value = val;
opt.innerHTML= ( str.length > 50 ) ? str.substring(0,48)+"..." : str;
selObj.appendChild(opt);
}
}
</code>
All the above is working fine. But everything goes south at submit time when the urls, (the value), are external relative to greenfloyd.org. Then, I get the "Go away and don't come back message..." On the other hand, if the urls point to greenfloyd there's no problem and the bookmark is published, with links. It's almost like I were trying to call the local script from some other domain. The uls are not in any linkable context, they are treated as plain text in the value attribute of the option. Although I do combine the url with the text using a seperator (,) between them so that php can unpack the value to produce seperate url and text fields that are stored on msqli... it's hacky, but it works, or at least it use to and I've yet to find a better alternative. One other odd thing: when I gather the links in greenfloyd.org there are a couple external links and they are accepted!?
<code>
function bmSub()
{
...
var selObj = document.getElementById("relatedSelect");
var url, txt, val, sendCt=0;
for ( var i = 0; i < selObj.options.length; i++ )
{
if ( selObj.options[i].selected )
{
url = selObj.options[i].value.trim();
txt = selObj.options[i].innerHTML;
val = url+"*,*"+txt; // pack url and txt into the value attribute, php unpacks it into 2 db fields
selObj.options[i].value = val;
sendCt +=1;
}
}
resultDisplay("Link count: "+sendCt);
var formElement = document.getElementById("bmInputForm");
var formData = new FormData(formElement);
var urlX = encodeURI("http://greenfloyd.org/greenfloyd/php/bm_input_xml.php?sid="+Math.random());
xmlObj = GetXmlHttpObject();
xmlObj.open("POST", urlX, false);
xmlObj.send(formData);
// pause echo "<return err='$err' msg='$msg'></return>";
try
{
xmlDoc = xmlObj.responseXML;
var returnNode = xmlDoc.getElementsByTagName("return");
err = ( returnNode[0].getAttribute("err") == "1" ) ? true : false;
msg = unescape(returnNode[0].getAttribute("msg"));
}
catch(e)
{
msg = "bmSub status : "+e+"<br>xml: "+xmlObj.statusText+", "+xmlObj.status+", size: "+xmlObj.responseText.length;
err = true;
}
resultDisplay(msg);
if ( err ) return;
</code>

Javascript - How to enable/disable text input in IE9

The following script worked in IE8 but not in IE9:
function toggleSelect(fieldName)
{
var idx = fieldName.lastIndexOf("_");
var sub = fieldName.substring(19,idx);
if (document.findForm["cb_Row_PageAutoDelete_" + sub].checked) {
document.findForm["SHIP_QTY_" + sub].disabled=false ;
} else {
document.findForm["SHIP_QTY_" + sub].disabled=true ;
}
return true;
}
I can display the value of the SHIP_QTY field so I know it's on the page but the disable function does not work.
Thanks for your help.
If findForm is the name of the form, you want window.findForm rather than document.findForm. You can also just use the result of the other field's checked property directly rather than an if/else. So your code changes to:
function toggleSelect(fieldName)
{
var idx = fieldName.lastIndexOf("_");
var sub = fieldName.substring(19,idx);
window.findForm["SHIP_QTY_" + sub].disabled = window.findForm["cb_Row_PageAutoDelete_" + sub].checked;
return true;
}

Explanation of this JavaScript Code

I'm not too good on the whole JavaScript (I can do some basic validations) but this isn't my zone
I've got a piece of code below that I'm trying to understand what it does, I can read any code and understand a few parts, but this just stumped me.
Here:
function tm_search_click() {
if (document.getElementById('tm').value == 'Enter your trademark') {
document.getElementById('tm').style.backgroundColor = '#fcc';
return false;
} else {
window.location = '?tm=' + escape(document.getElementById('tm').value);
return true;
}
}
function qs(a) {
a = a.replace(/[[]/, "\[").replace(/[]]/, "\]");
var b = "[\?&]" + a + "=([^&#]*)";
var c = new RegExp(b);
var d = c.exec(window.location.href);
return d == null ? "" : decodeURIComponent(d[1]).replace(/+/g, " ")
}
if (qs("tm") != "") {
tm_trademark = document.getElementById("tm").value = unescape(qs("tm"));
tm_partner = "migu2008";
tm_frame_width = 630;
tm_frame_height = "auto";
tm_trademark_country_code = "GB";
tm_css_url = "http://remarqueble.com/api/theme/search_corporate.css";
document.getElementById("tmLoading").style.display = "block";
tm_on_search_result = function () {
document.getElementById("tmLoading").style.display = "none";
document.getElementById("tmLoaded").style.display = "block"
}
} else {
tm_search_method = "none"
}
That is all of it without the <script> tags.
Could I also edit this code so that it searches are made based on what option the user inputs?
I think it works like this (assuming that this is in tags inside html page)
Page loads.
The script checks if URL has 'tm' parameter. If it has, then it sets bunch of tm_.. parameters and callback function. I don't know how they are used.
User clicks something that triggers the tm_search_click
Script sets new URL for the page and browser starts loading that
Goto step 1.

Categories

Resources