Pass different values from the same button

0

Basically I'm changing a screen from where I had 4 inputs and 4 buttons (each input associated with a button for each). In the Onclick event of the button I called a jquery that calls a php to show an image according to the criteria established in the parameters I sent it:

onclick="mostrar_imagen(document.getElementById('por_numero').value,'','','1');"

This worked. Currently I put together a horizontal menu, in which I have 2 items with subitem that show an input and require entry of a value, 1 item without subitem that also shows an input, and all the other items that, when clicked, execute the already established criteria In the code. I can not find the way to use the same input and button and pass different values to the function that calls PHP. Step 4 criteria to the function show_image. Hope it's understandable. I copy the code, I hope your help!

<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="estilos.css">
	<script language="javascript" src="js/jquery-1.2.6.min.js"></script>

   <script type="text/javascript">

        function mostrar_imagen(num,nom,sec,otro) {
            document.getElementById('carga_img').style.display='block';
            document.getElementById('boton_x').style.display='block';

            var ruta="plano_de_imagen.php?num="+num+"&nom="+nom+"&sec="+sec+"&otro="+otro;
            $("#carga_imagen").load(ruta);
        };

	    function nomostrar_volver() {
	        document.getElementById('carga_img').style.display='none';
	        document.getElementById('boton_x').style.display='none';
	    };

    </script>

</head>

<body>
	<div id="contenedor">
		<nav id="menu">
				<li id="nav_mobile">Menú <img src="ham.png" style="width: 16px; margin-bottom: -3px"></li>
				<div id="oculto">
					<li><a href="#" id="inicio" >Inicio</a></li>
					<li>Busca Foto <img src="flechita.png" width="13" height="12">
						<ul style="display:none">
						    <li><a class="opciones" id="por_numero" href="#">Por ID</a></li>
						    <li><a class="opciones" id="por_nombre" href="#">Por Nombre</a></li>        
						 </ul>
					</li>
					<li><a id="por_seccion" href="#">Busca x Sector</a></li>
					<li>Habilitados <img src="flechita.png" width="13" height="12">
						<ul style="display:none">
						    <li><a class="opciones" id="01" href="#">Sector01</a></li>
						    <li><a class="opciones" id="02" href="#">Sector02</a></li>
						    <li><a class="opciones" id="03" href="#">Sector03</a></li>
						    <li><a class="opciones" id="04" href="#">Sector04</a></li>
						    <li><a class="opciones" id="05" href="#">Sector05</a></li>
						    <li><a class="opciones" id="06" href="#">Sector06</a></li>		        
						 </ul>
					</li>
				</div>				
		</nav>

		<div id="cabeza">
			<div id="marco">
				<span id="nombre_campo">Ingrese el Nº : </span><input type="number" id="cajita" name="ingreso" autofocus>
				<input type="button" id="boton1" name="enviar" onclick="mostrar_imagen(document.getElementById('por_numero').value,'','','1');" value="Buscar">
			</div>
		</div>
	</div>
    
	<div id="carga_img"></div>
	<a href="#" id="boton_x" class="botonx" style="display:none;" onclick="javascript:nomostrar_volver();">X</a>

		
	</div>

	<script>

	//Desplegar al hacer clic
	$('#menu li').click(function(){	
		$(this).find('ul').slideToggle('fast');	
	});

	$('#nav_mobile').click(function(){	
		$('#oculto').slideToggle('fast');	
	});

	$(document).ready(function() {

		$('#inicio').click(function(){
			$('#cabeza').css('display', 'none');
		});

	    $('#por_numero').click(function(){
	    	$('#cabeza').css('display', 'Block');
	        $('span#nombre_campo').text('Ingrese el Nº : ');
	        $('#cajita').focus();
	    }); 

	    $('#por_nombre').click(function(){
	    	$('#cabeza').css('display', 'Block');
	        $('span#nombre_campo').text('Ingrese el Nombre : ');
	        $('#cajita').focus();
	    }); 

	    $('#por_seccion').click(function(){
			if($('#cabeza').css('display') == 'none')
			{
		    	$('#cabeza').css('display', 'Block');
		        $('span#nombre_campo').text('Ingrese Nº del Sector : ');
		        $('#cajita').focus();
			}else {
				$('#cabeza').css('display', 'none');
			}
	    }); 

	    $('#01').click(function(){
	    	$('#cabeza').css('display', 'None');
	    }); 

	    $('#02').click(function(){
	    	$('#cabeza').css('display', 'None');
	    }); 

	    $('#03').click(function(){  
	        $('#cabeza').css('display', 'None');
	    }); 

	    $('#04').click(function(){
	        $('#cabeza').css('display', 'None');
	    }); 

	    $('#05').click(function(){
	        $('#cabeza').css('display', 'None');
	    }); 
    	
       	$('#06').click(function(){
       		$('#cabeza').css('display', 'None');
       	});

	});  

	</script>


</body>

</html>
    
asked by look68 06.12.2018 в 14:48
source

2 answers

2

Your approach is not very clear, the only thing I have understood is that you want to pass several values through the click of a button.

There are many ways to do this and everything will depend on your application. You can for example have inputs of the same class as that button where you collect the data and when you click on the button the values of the inputs of that class are collected.

This would be particularly useful when the user has to explicitly write the values. Then you would have each input to tell the user what data to write.

Let's see an example of groups of input by classes and buttons. Here there are two groups that are listened to independently as one button is pressed another. For simplicity I have assigned the same function to the click of each button. If needed, you can assign a different function to each click of the button, grouping in that case directly by the most particular class of the divs, that is, by the classes grupo1 and grupo2 :

var allButtons = document.querySelectorAll(".estudiante button");

allButtons.forEach(function(btn) {

  btn.addEventListener('click', function(e) {
    var selector = '.${this.name} input';
    var allInputs = document.querySelectorAll(selector);

    allInputs.forEach(function(input) {
      var test = '${input.name} : ${input.value}';
      console.log(test);
    });
    
  });
  
});
<div class="estudiante">
  <div class="grupo1">
    <input type="text" name="ibxName" placeholder="Escriba el nombre" />
    <br />
    <input type="text" name="ibxApellido" placeholder="Escriba el apellido" />
    <br />
    <input type="text" name="ibxCiudad" placeholder="Escriba la ciudad" />
    <br />
    <button id="boton1" name="grupo1">Acción Grupo 1</button>
  </div>
  <hr />
  <div class="grupo2">
    <input type="text" name="ibxProfesor" placeholder="Escriba el profesor" />
    <br />
    <input type="text" name="ibxAsignatura" placeholder="Escriba asignatura" />
    <br />
    <button id="boton2" name="grupo2">Acción Grupo 2</button>
  </div>
</div>

Another way to pass multiple values is through the attributes data* . This can be particularly useful when you want to pass fixed values (in which the user does not intervene in a direct way). That is, it is not the same as a input . But it does not mean that they are static values. The data attributes can be changed. Think for example of a stock value where an item is discounted in each click. The existence can be in the data attribute and each time an item is added to the cart, this attribute can be decreased by one and updated.

Here I show an example where, in the same button we save three different information through the attributes data . By clicking on the button we can recover separately the value of each one of those attributes.

Just as we do it with a button, we can do it with a input or with any other element. The data attributes are very useful for saving information that does not need to be presented on the screen, or for saving structured information that is retrieved and / or updated dynamically.

var btnData = document.getElementById('btnData');
btnData.addEventListener('click', function(event) {
  var dataSet = this.dataset;
  console.log(dataSet);
  console.log(dataSet.name);
  console.log(dataSet.lastname);
  console.log(dataSet.age);
});
<button id="btnData" data-name="Pedro" data-lastname="Pérez" data-age="24">Mostrar Datos</button>

I hope both possibilities are useful to you.

  

NOTE: In the code I have given preference to pure Javascript code. It is advisable to do so whenever possible, thus avoiding the use of   external libraries that slow down the execution, of course.

    
answered by 06.12.2018 / 18:40
source
1

I send you an answer that I hope will serve as a reference:

First I advise you not to call the function in the "onclick" event and better do it from an external .js or within a "script" block that is inside your page, so that the code that I suggest work first replace:

<input type="button" id="boton1" name="enviar" onclick="mostrar_imagen(document.getElementById('por_numero').value,'','','1');" value="Buscar">

for this:

<input type="button" id="boton1" name="enviar" value="Buscar">

Inside a "script" block add this and modify the selectors by yours:

<script>
    // al hacer click en el botón ejecutar la función:
    $('.boton1').click(function(){
        // obtener los valores de los diferentes selectores que necesites
        var valor1 = $('#por_numero').val();
        var valor2 = $('#selector').val();
        var valor3 = $('#selector2').val();
        var valor4 = $('#selector3').val();
        // enviarlos a la funcion que deseas que los procese
        mostrar_imagen(valor1,valor2,valor3,valor4);
        // con esto debería funcionar como quieres
    });
</script>

Greetings.

    
answered by 06.12.2018 в 17:05