Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Getting values from select2 box and passing it to a string field.

Livee
Tera Contributor

So I'm using the select2 box to query from a table because we want the functionality of a choice list and a textbox in one.

This was implemented as a UI macro and it works fine and I'm pulling the necessary data into the select2 field, however I'm unable to get the selected result and copy it into another field.

The code I have is:

<?xml version="1.0" encoding="utf-8" ?>  

<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">

  <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />

  <script></script>

  <body>

  <script>

  $j(document).ready(function() {$j(".js-example-basic-single").select2();});

  </script>

  <g:macro name="Input" label="Select Categories" value="" onchange="onChange('${jvar_name}');" onclick_label="" mandatory="false"/>

  <table class="wide">

  <tr>

  <td id="label.${jvar_name}" class="label" nowrap="true" type="string" choice="0" oncontextmenu="${jvar_oncontextmenu}">

  <g:form_label onclick="${jvar_onclick_label}" for="${jvar_name}">

  ${jvar_label}<j2:if test="$[GlideMobileExtensions.getDeviceType() != 'doctype']">:</j2:if>

  </g:form_label>

  </td>

  <td nowrap="true" style="width:100%">

  <g:evaluate>

  var table = new GlideRecord('sys_choice');

  table.addQuery('element','=','subcategory');

  table.orderBy('label');

  table.query();

  </g:evaluate>

  <select class="js-example-basic-single" style="width: 63%">

  <j:while test="${table.next()}">

  <option value="${table.name}">${table.label}</option>

  </j:while>

  </select>

  <g2:evalutate var="jvar_page" jelly="true">

$('.js-example-basic-single').select2().on("change", function(e) {

      var obj = $(".js-example-basic-single").select2("data");

      console.log("change val=" + obj[0].id);   // 0 or 1 on change

});

  </g2:evalutate>

  </td>

  </tr>

  </table>

  </body>

</j:jelly>  

I've attached a screenshot of the form. The Select Categories field is the select2box, and the Subcategory field is where I want to copy the selected value to.

1 REPLY 1

fredi_fr
ServiceNow Employee
ServiceNow Employee

Hi,


How do you populate $(".js-example-basic-single")? Does it have an array "data"?



Have a look at Examples - Select2 the example, also uses onChange event and gets the selected object to print a log.



Regards,


Guillermo