How to know if it is empty or null on field by ID in Javascript

2

I have this:

<select id="division" multiple="multiple" title="Equipos seleccionados" style="width:143px;height:125px;overflow:scroll;">
<option value="1" title="Bundesliga">Bundesliga</option>
</select>

I'm doing this to you:

_spBodyOnLoadFunctionNames.push("hideFields");

function hideFields() {
    var control = findcontrol("equipo");
    control.parentNode.parentNode.parentNode.style.display = "none";
}

function showFields() {
    var control = findcontrol("equipo");
    control.parentNode.parentNode.parentNode.style.display = "block";
}

function findcontrol(field) {
    var arr = document.getElementById(field);
    return arr;
}

var values = document.getElementById('division').val();;
if (values != null || values != ''){
    showFields();
}

but it does not happen to the function showFields();

What I want is that when there is nothing in division that does not show me the equipo and when there is something in division that the equipo appears

How do I do it in Javascript? Javascript without any bookstore. The code is generated by Sharepoint

Visually:

  • When loading the default page

  • Passing a division to the right or selecting it

    
asked by Paolo Frigenti 24.04.2018 в 15:43
source

3 answers

1

This answer has successive editions due to the editions of the answer in which more data have been provided:

Edited to take your last edition into account:

var values = document.getElementById('division').val();
if (values != null || values != ''){
    showFields();
}

The .val() method does not exist in a DOM node of the HTML document, only in jQuery. In this case, the result is a matrix with each and every one of the selected elements:

  

When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .val() returns an array containing the value of each selected option . As of jQuery 3.0 , if no options are selected, it returns an empty array; Prior to jQuery 3.0 , it returns null .

In Spanish:

  

When the first item in the collection is a select-multiple (ie, a select element with the multiple attribute activated), .val() returns an array containing the value of each selected option . As of jQuery 3.0 , if there are no options selected it will return an empty array; before jQuery 3.0 returned null .

The content of values should not be converted to a character string because its content is an array. You could use the property .length to know the number of elements that There is in it:

var values = $('#division').val();
if (values != null || values.length > 0){
    showFields();
}

This way you cover any version of jQuery.

On the other hand, that code will be executed only once during the loading of the page. You need to add an event that is executed every time you click on Agregar > (for example).

Your code and your problem is no longer trivial and it becomes somewhat complex when you do not provide us with more information about the origin of the data, if you can select more than one team from one or more divisions or not.

Either way, you have made it clear that you can only have a single active division at all times, so you no longer need the multiple attribute. It is not necessary if you only want to select only one element at a time, just use size to get the same visual appearance:

// Simulo _spBodyOnLoadFunctionNames.push("hideFields");
document.addEventListener("DOMContentLoaded", function() {
  /* Precargamos estos objetos del DOM */
  var division = document.getElementById('division');
  var division_sel = document.getElementById('division_sel');
  var equipo = document.getElementById('equipo');
  /* Llamamos a la función que oculta los equipos,
      aunque debería estar oculto por defecto */
  hideFields();
  /* Rellenamos los campos de las divisiones */
  for (var elemento in datos) {
    /* Creamos un objeto "option" */
    var option = document.createElement('option');
    /* Le asignamos los valores "name" y el contenido de texto */
    option.name = elemento;
    option.appendChild(
      document.createTextNode(datos[elemento].nombre)
    );
    /* Agregamos el nodo al select */
    division.appendChild(option);
  }
  /* Ahora agregamos el código para agregar elementos de la selección */
  document.getElementById('agregar_division').addEventListener('click', function() {
    /* Limpiamos la cajita de división seleccionada */
    while (division_sel.firstChild) {
      division_sel.removeChild(division_sel.firstChild);
    }
    /* Ahora agregamos el elemento seleccionado */
    for (i = 0; i < division.options.length; i++) {
      if (division.options[i].selected == true) {
        /* Agregamos un nodo clonado del original (con mismo contenido) */
        division_sel.appendChild(division.options[i].cloneNode(true));
        /* Limpiamos el contenido previo de los equipos (debería estar borrado) */
        while (equipo.firstChild) {
          equipo.removeChild(equipo.firstChild);
        }
        /* Y ahora introducimos sus equipos en la caja de abajo */
        for(var elemento in datos[division.options[i].name].equipos) {
          /* Creamos un objeto "option" */
          var option = document.createElement('option');
          /* Le asignamos los valores "name" y el contenido de texto */
          option.name = elemento;
          option.appendChild(
            document.createTextNode(
              datos[division.options[i].name].equipos[elemento]
            )
          );
          /* Agregamos el nodo al select */
          equipo.appendChild(option);
        }
        /* Mostramos la caja de equipos */
        showFields();
      }
    }
  });
  /* Ahora agregamos el código para quitar elementos de la selección */
  document.getElementById('quitar_division').addEventListener('click', function() {
    /* Limpiamos la cajita de división seleccionada */
    while (division_sel.firstChild) {
      division_sel.removeChild(division_sel.firstChild);
    }
    /* Limpiamos la cajita de equipos */
    while (equipo.firstChild) {
      equipo.removeChild(equipo.firstChild);
    }
    /* Ocultamos el campo de equipos */
    hideFields();
  });
});

function hideFields() {
    /* No uses "parentNode...parentNode", es una mala práctica, se complicará
        mantener el código HTML. Mejor selecciona el nodo exacto que quieras */
    equipo.style.display = "none";
}

function showFields() {
    equipo.style.display = "block";
}

/* Datos de ejemplo */
var datos = {
  'liga_es': {
    nombre: 'Liga Española',
    equipos: {
      'equipo_esp_1': 'Equipo Español 1',
      'equipo_esp_2': 'Equipo Español 2',
      'equipo_esp_3': 'Equipo Español 3',
    },
  },
  'liga': {
    nombre: 'Liga Extranjera',
    equipos: {
      'equipo_ext_1': 'Equipo Extranjero 1',
      'equipo_ext_2': 'Equipo Extranjero 2',
      'equipo_ext_3': 'Equipo Extranjero 3',
    },
  },
};
/* Centramos los contenidos en la celda */
table td {
  text-align: center;
  vertical-align: middle;
}
/* Hacemos que los botones ocupen el ancho de la celda */
table button {
  width: 100%;
  margin: 2px 0px;
}
<table>
  <tr>
    <td>
      <select id="division" size="3" title="División"
          style="width: 143px; overflow: scroll;">
      </select>
    </td>
    <td>
      <button id="agregar_division">Agregar &gt;</button>
      <button id="quitar_division">&lt; Quitar</button>
    </td>
    <td>
      <select id="division_sel" size="3" title="División Seleccionada"
          style="width: 143px; overflow: scroll;">
      </select>
    </td>
  </tr>
  <tr>
    <td></td>
  </tr>
</table>
<!-- Simulamos tres niveles de profundidad para tu campo -->
<div><div><div>
<select id="equipo" size="5"
    title="Equipos seleccionados"
    style="width: 143px; height: 125px; overflow: scroll;">
</select><br/>
</div></div></div>
    
answered by 24.04.2018 / 16:21
source
1

When performing:

document.getElementById('division')

You get the DOM object of a select, to know if it has any selected element, you should consult its property .value . This property has the first element selected.

Example:

function divisionChange() {
  var select = document.getElementById('division');
  if (select.value) {
    console.log("llamar a showFields()");
  } else {
    console.log("llamar a hideFields()");
  }
}
<select id="division" multiple onchange="divisionChange()">
  <option value="1">Uno</option>
  <option value="2">Dos</option>
</select>
    
answered by 24.04.2018 в 16:27
1

To get the value is with $("#id").val(); .

I leave you a short example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="miId" multiple="multiple">
    <option value="1">Cafe</option>
    <option value="2">Chocolate</option>
    <option value="3">Coca Cola</option>
    <option value="4">Snacks</option>
    <option value="5">Vino</option>
</select>
<input type="button" onclick="miFuncion();" value="Obtener Valores">
<script>
function miFuncion(){
var values = $('#miId').val();
  if(values == "" || values == null){
  alert("no posee valores");
  }else{
  alert(values);
  }

}//end function

</script>

To validate use the%% of%, in this way you get the values by ID and then valid if they are || or empty.

    
answered by 24.04.2018 в 15:56