JavaScript - Examples

JavaScript examples for the Message Field application. Each example below shows the full file - copy it as is.

MessageField v5 - JavaScript API Description and Usage Guide

File: MessageField v5 - JavaScript API Description and Usage Guide.md

# API Description and Usage Guide

This API allows you to interact with form fields and a customizable message field within Jira contexts. The main classes include **`Form`**, **`FormField`**, and **`MessageField`**. Additionally, there are two global variables:

- **`JIBROK_MESSAGE_FIELD_CONTEXT`**: Indicates the screen (context) where the code is running, such as `CREATE`, `EDIT`, `VIEW`, `TRANSITION`, `CREATE_SD`, `VIEW_SD`.
- **`messageField`**: A pre-configured `MessageField` instance for showing or updating messages.
- **`form`**: A `Form` instance that provides methods to access and manipulate fields.

## 1. Classes

### 1.1 `Form`

- **`getContext()`**  
  Returns the current context, which equals the value of `JIBROK_MESSAGE_FIELD_CONTEXT`.

- **`getFieldById(fieldId)`**  
  Retrieves a `FormField` object by the specified **`fieldId`**.  
  - In service desk contexts (`CREATE_SD`), the method searches both `id` and `name` attributes.  
  - Returns a `FormField` wrapping the first matching input.

- **`getForm()`**  
  Returns the jQuery-wrapped form element, typically used for more advanced or low-level DOM manipulations.

### 1.2 `FormField`

This class represents a generic field in the form.

- **`val()`**  
  - **Getter**: When no argument is provided, returns the current value of the field.  

- **`val(value)`**  
  - **Setter**: If a value is provided, sets the field’s value accordingly and returns the `FormField` instance (allowing method chaining).

- **`hide(timeOfAnimation = null)`**  
  Hides the field (actually the nearest `div.field-group` around it). Optionally, takes a numeric parameter for animation duration in milliseconds.

- **`show(timeOfAnimation = null)`**  
  Shows the field. Optionally, takes a numeric parameter for animation duration in milliseconds.

### 1.3 `MessageField` (extends `FormField`)

Used for displaying messages or updating them dynamically.

- **`val(message)`**  
 - If you pass a **string** as the `message`, it will be displayed as-is:
  - Simple text without HTML will be shown plainly.
  - A string containing HTML (e.g., `"<b>Important!</b>"`) will be rendered as HTML.
- If you pass an **object**, it will be serialized into JSON internally and used for additional configuration.
Typical object structure can contain:
   
   ```json
    {
      "title": "Message Title",
      "body": "Message body text",
      "type": "info"
    }
    ```
    
Full structure:
    
```json
{
  "title": "Message Title (string)",
  "body": "Message body (string)",
  "type": "error | warning | success | info | change | custom | SIMPLE_VIEW",
  "showForCustomFieldId": "CSS selector that determines where the message should appear. format: customfield_10000 | 10000",
  "asFlag": true,
  "viewVersion": "v1 | v2 | v3 | v1_1 | v1_2 | v2_1 | v2_2 | v3_1 | v3_2",
  "backgroundColor": "#0052CC",
  "textColor": "#FFFFFF",
  "icon": "String (icon)",
  "insert": "prepend | append | after | before",
  "showForCustomFieldId": "String (selector) — the field to attach the message to",
  "selectorViewSD": "CSS selector for the VIEW_SD context",
  "selectorSDCreate": "CSS selector for the CREATE_SD context",
  "selectorCreate": "CSS selector for the CREATE context",
  "selectorEdit": "CSS selector for the EDIT context",
  "selectorTransition": "CSS selector for the TRANSITION context",
  "selectorView": "CSS selector for the VIEW_ISSUE context"
}
```

## 2. Example with Explanations

Below is a code snippet showing how to use the API to:
- Check if the **priority** is set to a “high” value.
- Display a message when the priority is high.
- Show or hide a related **priority reason** field accordingly.

```js
// Retrieve references to relevant fields
let priorityField = form.getFieldById("priority");
let priorityReasonField = form.getFieldById("customfield_10404");

// Assume that the "high" priority has ID = 2
let highPriorityId = 2;

// Get the current value of the priority field
let currentPriority = priorityField.val();

// If the priority is "high" (2), show a message and the reason field
if (currentPriority == highPriorityId) {
    showHighPriorityMessage();
    priorityReasonField.show();
} else {
    cleanMessage();
    priorityReasonField.hide();
}

// This function clears any existing message
function cleanMessage() {
    // Passing null will remove the message entirely
    messageField.val(null);
}

// This function sets a warning message for high priority
function showHighPriorityMessage() {
    messageField.val({
        title: "High priority",
        body: "Please provide a reason for this high priority.",
        type: "warning",
        selectorEdit: "div.field-group:has(#priority)"
    });
}
```

New Public API Methods (v5.1+)

The Message Field now provides public API methods to retrieve form data programmatically. These methods are available on the global MESSAGE_FIELD_OBJECT:

getCurrentFormSelector()

Returns the current form selector based on the page context (Jira or Service Desk) and whether a dialog is opened.

// Get current form selector
const formSelector = MESSAGE_FIELD_OBJECT.getCurrentFormSelector();
console.log('Current form selector:', formSelector);

Returns:

  • string - The form selector for the current context
  • null - If page manager is not initialized

getDataFromDefaultForm()

Retrieves form data from the default form based on the current page context (Jira or Service Desk).

// Get form data from default form
const formData = MESSAGE_FIELD_OBJECT.getDataFromDefaultForm();
console.log('Form data:', formData);

Returns:

  • object - Form data object containing field values
  • null - If page manager is not initialized

getFullDataFromDefaultForm()

Retrieves complete form data including all field information from the default form.

// Get full form data from default form
const fullFormData = MESSAGE_FIELD_OBJECT.getFullDataFromDefaultForm();
console.log('Full form data:', fullFormData);

Returns:

  • object - Complete form data object with detailed field information
  • null - If page manager is not initialized

Note: These API methods work in both Jira and Service Desk contexts and automatically detect the appropriate form based on the current page environment.

Update message on create

File: update message on create.js

require(['jquery'], function($) {
	function setCFValue(customfield_id, value){
		$('#' + customfield_id).val(value).trigger('change')
	}

	function setMessage(title, body, messageType){
		var jsonMessage = {}
		jsonMessage.title = title
		jsonMessage.body = body
		jsonMessage.messageType = messageType
		setCFValue(CF_ID_MESSAGE, JSON.stringify(jsonMessage))
	}
	
	//EDIT HERE
	var CF_ID_MESSAGE = 'customfield_10200'

	setMessage('New title', 
		'Loooong <br>'+
		'Loooong<br>'+
		'Loooong<br>'+
		'message', 
		'error')//info, success, warning, error, change, SIMPLE_VIEW
})

Update message with priority

File: update message with priority.js

require(['jquery'], function($) {
	function setCFValue(customfield_id, value){
		$('#' + customfield_id).val(value).trigger('change')
	}

	function setMessage(title, body, messageType){
		var jsonMessage = {}
		jsonMessage.title = title
		jsonMessage.body = body
		jsonMessage.messageType = messageType
		setCFValue(CF_ID_MESSAGE, JSON.stringify(jsonMessage))
	}
	
	//EDIT HERE
	var CF_ID_MESSAGE = 'customfield_10200'

	$('#priority').on('change', function(){
		if($(this).val() == 1){//1 - priority id
			setMessage('New title', 
			'Blocker<br>'  + 
			'priority', 
			'error')//info, success, warning, error, change, SIMPLE_VIEW
		} else {
			setMessage('Just info', 
			'not blocker', 
			'info')//info, success, warning, error, change, SIMPLE_VIEW
		}
	})
})

Update message with priority and select field

File: update message with priority and select field.js

require(['jquery'], function($) {
	function setCFValue(customfield_id, value){
		$('#' + customfield_id).val(value).trigger('change')
	}

	function setMessage(title, body, messageType){
		var jsonMessage = {}
		jsonMessage.title = title
		jsonMessage.body = body
		jsonMessage.messageType = messageType
		setCFValue(CF_ID_MESSAGE, JSON.stringify(jsonMessage))
	}
	
	function getPriority(){
		return $('#priority').val()[0]
	}

	function getCFValue(customfield_id){
		return $('#' + customfield_id).val()
	}
	//EDIT HERE
	var CF_ID_MESSAGE = 'customfield_10200'
	var CF_ID_SELECT = 'customfield_10301'

	$('#priority').on('change', function(){
		updateMessage()
	})

	$('#' + CF_ID_SELECT).on('change', function(){
		updateMessage()
	})

	function updateMessage(){
		if(['1'].indexOf(getPriority()) > -1){//1 - priority id
			if(['-1'].indexOf(getCFValue(CF_ID_SELECT)) > -1){//-1 - select none
				setMessage('BLOCKER', '<a>BLOCKER and seelct none </a>', 'error')
				return
			}
		} else if(['2'].indexOf(getPriority()) > -1){//2 - priority id
			if(['10104'].indexOf(getCFValue(CF_ID_SELECT)) > -1){//select option id
				setMessage('Critical and select option', 'message', 'success')
				return
			}
		} else if(['3', '4'].indexOf(getPriority()) > -1){
			setMessage('Simple title', 'message', 'info')
			return
		}

		setMessage('DEFAULT TITLE', 'DEFAULT MESSAGE', 'info')
		return 
	}
})

Update message on create(SD)

File: update message on create(SD).js

require(['jquery'], function($) {

	function setMessage(title, body, messageType){
		var jsonMessage = {}
		jsonMessage.title = title
		jsonMessage.body = body
		jsonMessage.messageType = messageType
		jsonMessage.jibrokMessageKey = true //Require for Service Desk (JSM) until v4.14.* of Message field version
		$('#' + CF_ID_MESSAGE).text(JSON.stringify(jsonMessage)).trigger('change')//Service Desk create request
	}
	
	//EDIT HERE
	var CF_ID_MESSAGE = 'customfield_10200'

	setMessage('New title', 
		'Loooong <br>'+
		'Loooong<br>'+
		'Loooong<br>'+
		'message', 
		'error')//info, success, warning, error, change, SIMPLE_VIEW
})

Update message with priority(SD)

File: update message with priority(SD).js

require(['jquery'], function($) {

	function setMessage(title, body, messageType){
		var jsonMessage = {}
		jsonMessage.title = title
		jsonMessage.body = body
		jsonMessage.messageType = messageType
		jsonMessage.jibrokMessageKey = true //Require for Service Desk (JSM) until v4.14.* of Message field version
		$('#' + CF_ID_MESSAGE).text(JSON.stringify(jsonMessage)).trigger('change')//Service Desk create request
	}
	
	//EDIT HERE
	var CF_ID_MESSAGE = 'customfield_10200'

	$('#priority').on('change', function(){
		if($(this).val() == 1){//1 - priority id
			setMessage('New title', 
			'Blocker<br>'  + 
			'priority', 
			'error')//info, success, warning, error, change, SIMPLE_VIEW
		} else {
			setMessage('Just info', 
			'not blocker', 
			'info')//info, success, warning, error, change, SIMPLE_VIEW
		}
	})
})

Update message with priority and select field(SD)

File: update message with priority and select field(SD).js

require(['jquery'], function($) {

	function setMessage(title, body, messageType){
		var jsonMessage = {}
		jsonMessage.title = title
		jsonMessage.body = body
		jsonMessage.messageType = messageType
		jsonMessage.jibrokMessageKey = true //Require for Service Desk (JSM) until v4.14.* of Message field version
		$('#' + CF_ID_MESSAGE).text(JSON.stringify(jsonMessage)).trigger('change')//Service Desk create request
	}
	
	function getPriority(){
		return $('#priority').val()[0]
	}

	function getCFValue(customfield_id){
		return $('#' + customfield_id).val()
	}
	//EDIT HERE
	var CF_ID_MESSAGE = 'customfield_10200'
	var CF_ID_SELECT = 'customfield_10301'

	$('#priority').on('change', function(){
		updateMessage()
	})

	$('#' + CF_ID_SELECT).on('change', function(){
		updateMessage()
	})

	function updateMessage(){
		if(['1'].indexOf(getPriority()) > -1){//1 - priority id
			if(['-1'].indexOf(getCFValue(CF_ID_SELECT)) > -1){//-1 - select none
				setMessage('BLOCKER', '<a>BLOCKER and seelct none </a>', 'error')
				return
			}
		} else if(['2'].indexOf(getPriority()) > -1){//2 - priority id
			if(['10104'].indexOf(getCFValue(CF_ID_SELECT)) > -1){//select option id
				setMessage('Critical and select option', 'message', 'success')
				return
			}
		} else if(['3', '4'].indexOf(getPriority()) > -1){
			setMessage('Simple title', 'message', 'info')
			return
		}

		setMessage('DEFAULT TITLE', 'DEFAULT MESSAGE', 'info')
		return 
	}
})

Update and hide message with 2 conditions by select fields(Service Desk)

File: update and hide message with 2 conditions by select fields(Service Desk).js

require(['jquery'], function($) {
	function setMessage(title, body, messageType){
		var jsonMessage = {}
		jsonMessage.title = title
		jsonMessage.body = body
		jsonMessage.messageType = messageType
		jsonMessage.jibrokMessageKey = true //Require for Service Desk (JSM) until v4.14.* of Message field version
		$('#' + CF_ID_MESSAGE).text(JSON.stringify(jsonMessage)).trigger('change')//Service Desk create request
	}

	function showMessage(isShow){
		if(isShow){
			$('.field-group:has(#'+ CF_ID_MESSAGE + ')').find('.aui-message').show()
			//$('#' + CF_ID_MESSAGE).show() //for Message type: Show as is
		} else {
			$('.field-group:has(#'+ CF_ID_MESSAGE + ')').find('.aui-message').hide()
			//$('#' + CF_ID_MESSAGE).hide() //for Message type: Show as is
		}
	}
	
	function getFieldValue(fieldId) {
	    return $('#' + fieldId).val()
	}

	//EDIT HERE
	var CF_ID_MESSAGE = 'customfield_10013'//set custom field id(Message field)
	var CF_ID_SELECT1 = 'customfield_10200'//set custom field id(Select field)
	var CF_ID_SELECT2 = 'customfield_10201'//set custom field id(Select field)

	var OPTION_ID_HIGH = '10100'//set option id(view in select field config - CF_ID_SELECT1)
	var OPTION_ID_AFFECTED_ALL_USERS = '10103'//set option id(view in select field config - CF_ID_SELECT2)
	
	updateMessage()
	$('#' + CF_ID_SELECT1).on('change', function(){updateMessage()})
	$('#' + CF_ID_SELECT2).on('change', function(){updateMessage()})
	function updateMessage(){
		if(getFieldValue(CF_ID_SELECT1) == OPTION_ID_HIGH && getFieldValue(CF_ID_SELECT2) == OPTION_ID_AFFECTED_ALL_USERS){//or replace on your options
			setMessage('High!', 'text for High and Affected all', 'error')//set message config
			showMessage(true)
		} else {
			showMessage(false)
		}
	}
})

Update and hide message with 2 conditions by select fields

File: update and hide message with 2 conditions by select fields.js

require(['jquery'], function($) {

    function setCFValue(customfield_id, value){
        $('#' + customfield_id).val(value).trigger('change')
    }

    function setMessage(title, body, messageType){
        var jsonMessage = {};
        jsonMessage.title = title;
        jsonMessage.body = body;
        jsonMessage.messageType = messageType;
        setCFValue(CF_ID_MESSAGE, JSON.stringify(jsonMessage))
    }

    function getFieldValue(fieldId) {
        return $('#' + fieldId).val()
    }

    //EDIT HERE
    var CF_ID_MESSAGE = 'customfield_10017'//set custom field id(Message field)
    var CF_ID_SELECT1 = 'customfield_10015'//set custom field id(Select field)
    var CF_ID_SELECT2 = 'customfield_10016'//set custom field id(Select field)

    var OPTION_ID_HIGH = '10000'//set option id(view in select field config - CF_ID_SELECT1)
    var OPTION_ID_AFFECTED_ALL_USERS = '10003'//set option id(view in select field config - CF_ID_SELECT2)

    updateMessage()
    $('#' + CF_ID_SELECT1).on('change', function(){updateMessage()})
    $('#' + CF_ID_SELECT2).on('change', function(){updateMessage()})
    function updateMessage(){
        if(getFieldValue(CF_ID_SELECT1) === OPTION_ID_HIGH && getFieldValue(CF_ID_SELECT2) === OPTION_ID_AFFECTED_ALL_USERS){//or replace on your options
            setMessage('High!', 'text for High and Affected all', 'error')//set message config
        } else {
            //empty message not showing
            setMessage('', '', '')
        }
    }
});

Hide message if all fields are empty(View issue)

The script will check the custom fields on the view issue screen. If all fields are empty, the message banner will be hidden.

Message Field dynamic template demonstration video

File: hide message if all fields are empty(View issue).js

function checkFieldsAreEmptyAndHideMessage(fieldIds, messageFieldId){
 	AJS.$.ajax({
            url: AJS.contextPath() + '/rest/api/2/issue/' + JIRA.Issue.getIssueId() + "?fields=" + fieldIds.join(),
            type: "GET",
            async: false,
            success: function(issue) {
            	if(areAllFieldsEmpty(issue, fieldIds)){
            		hideMessage(messageFieldId)
            	}
            }
        });
}
 
 function hideMessage(messageFieldId){
 	AJS.$("#rowFor" + messageFieldId).hide()
 }

 function areAllFieldsEmpty(issue, fieldIds){
 	for(var i = 0; i < fieldIds.length; i++){
		var fieldId = fieldIds[i]
		if(issue.fields[fieldId] != null){
			return false
		}
	}
	return true
 }


//The script will check the custom fields on the view issue screen. If all fields are empty, the message banner will be hidden.
if(JIBROK_MESSAGE_FIELD_CONTEXT == "VIEW_ISSUE"){//version 3.1.7+ or set JavaScript context - Issue view screen
	var customFieldIds = ["customfield_10201", "customfield_10202"]//fields will be check on null value
	var messageFieldId = "customfield_10013"
	checkFieldsAreEmptyAndHideMessage(customFieldIds, messageFieldId)
}

Update message with bundled select(SD-create)

Message Field extensions for Jira demo

File: update message with bundled select(SD-create).js

require(['jquery'], function($) {
	var lastSelectedOption = null;

	function setMessage(message){
		message.jibrokMessageKey = true //Require for Service Desk (JSM) until v4.14.* of Message field version
		AJS.$('#' + CF_ID_MESSAGE).text(JSON.stringify(message)).trigger('change')//Service Desk create request
	}

	//edit here ->
	var CF_ID_MESSAGE = 'customfield_10200'
	var bundledFieldId = 10201;
	var bundledSelectFieldName = "example select";
	var optionName1 = "test option 1";
	var optionName2 = "test option 2";
	var optionName3 = "test option 3";
	var optionName4 = "";

	var defaultMessage = {
		title: 'DEFAULT TITLE',
		body: 'DEFAULT MESSAGE',
		messageType: 'info'
	};

	var messageForOption1 = {
		title: 'first',
		body: '<a>test option 1 </a>',
		messageType: 'error'
	};
	var messageForOption2 = {
		title: '2',
		body: 'test option 2',
		messageType: 'success'
	};
	var messageForOption3_4 = {
		title: 'Simple title',
		body: 'message',
		messageType: 'warning'
	};

	function updateMessage(){
		var selectedValue = getBundledSelectText()
		if(selectedValue == lastSelectedOption){
			return;
		}
		if(optionName1 == selectedValue){
			setMessage(messageForOption1)
			return
		} else if(optionName2 == selectedValue){
			setMessage(messageForOption2)
			return
		} else if([optionName3, optionName4].indexOf(selectedValue) > -1){
			setMessage(messageForOption3_4)
			return
		}	

		setMessage(defaultMessage)
		lastSelectedOption = selectedValue;
		return 
	}
	//edit here <-

	if(JIBROK_MESSAGE_FIELD_CONTEXT == 'CREATE_SD'){

		function getBundledSelectField(){
			return AJS.$('#jsdbundled-' + bundledFieldId).find('label:contains(' + bundledSelectFieldName + ')').parent().find('select');
		}

		function getBundledSelectText(){
			return getBundledSelectField().find('option:selected').text();
		}

		setInterval(function(){
			updateMessage()
		}, 1000)
	} 
});