How to activate and deactivate JavaScript button

1

I can not find the solution for once I click on "remove" the button Buy re-enabled. I tried to put an if in the addCard function || put an if in the delete function. I've even tried doing another function for enable and call it on the purchase button with two functions the same onclick. Thank you very much.

var datos = [];
datos[0] = ["Calcetines Rotos", 16, "img/libro1.jpg"];
datos[1] = ["Patria", 15.9, "img/libro2.jpg"];
datos[2] = ["Los Ritos Del Agua", 21.8, "img/libro3.jpg"];
datos[3] = ["El Extraño Verano de Tom Harvey", 20, "img/libro4.jpg"];
datos[4] = ["La Habitación en Llamas", 21.5, "img/libro5.jpg"];
datos[5] = ["El secreto de Ile-de-sein", 16.5, "img/libro6.jpg"];
datos[6] = ["Ocho días de Marzo", 15.9, "img/libro7.jpg"];
datos[7] = ["Cinco dias de Octubre", 15.9, "img/libro8.jpg"];
var salida = "";
var compra = [];

function carrito() {
    for (i = 0; i < datos.length; i++) {
        if (i == 0) {
            salida += '<div class="row">';
        }
        else if ((i % 4) == 0) {
            salida += '</div> <div class="row">';
        };
        salida += '<div style="height:300px" class="col-md-3 producto"> <img style="width:20%" src=' + datos[i][2] + ' class="img-rounded"><h3 class="text-primary text-center">' + datos[i][0] + '</h3>' + datos[i][1] + ' € <br> <button onclick = "addCart(this,'+i+')"  onchange = "devolver(this,'+i+')" type="button" style="margin-top:15px" class= "btn btn-primary active btn-default">Comprar</button></div>';
        document.getElementById("hello").innerHTML = salida;
    };
    if (i != 0) {
        salida += "</div>";
    };
};

function addCart(boton, libro) {
    compra.push([libro, 1]);
    boton.disabled = true;
//    if(borrarCart()){
//        boton.disabled=false;
//    };
    refreshCarrito();
};

function cantidad(posicion, incremento) {
    compra[posicion][1] += incremento;
    if (compra[posicion][1] < 1) {
        compra[posicion][1] = 1;
    };
    refreshCarrito();
};

function refreshCarrito() {
    tablaCompra();
};

function tablaCompra() {
    var imprimir = "";
    for (i = 0; i < compra.length; i++) {
        var x = compra[i][0];
        imprimir += "<tr><td>" + (i + 1) + "</td><td>" + datos[x][0] + "</td><td><button onclick = 'cantidad("+i+", -1 )'>-</button>" + compra[i][1] + "<button onclick = 'cantidad("+i+", 1 )'>+</button></td><td>" + datos[x][1] + " €</td><td><button onclick= 'borrarCart(" + i + ")' >Eliminar</button></td></tr>"
    };
    document.getElementById("tabla-compra").innerHTML = imprimir;
};

function borrarCart(k) {
    compra.splice(k, 1);
//    if(boton.disabled=true){
//        boton.disabled=false;
//    }
    refreshCarrito();
}
carrito();


function devolver(boton,libros){
    if(compra.length=datos[libros]){
    boton.disabled =false;
}
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Compra Libros Online</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
    	.producto{

    		padding: 30px 10px;
    		border-radius: 10px;
    		border: 1px solid #ccc;
    		text-align: center;

    	}
    </style>
  </head>
  <body>

    <div class="container-fluid">
	<div class="row">
		<div class="col-md-12">
			<h3>
				Compra libros online
			</h3>
		</div>
	</div>
	<div id="hello">
	</div>
    
	<div class="row">
		<div class="col-md-12" style="border-bottom: 1px solid #ccc; margin-bottom: 30px;">
			<h3>
				Carrito de Compras:
			</h3>
		</div>
	</div>
	<div class="row">
		<div class="col-md-6">
			<table class="table table-condensed">
				<thead>
					<tr>
						<th>
							#
						</th>
						<th>
							Producto
						</th>
                        <th>
							Cantidad
						</th>
						<th>
							Precio
						</th>
                        <th>
							Eliminar
						</th>
					</tr>
				</thead>
				<tbody id= "tabla-compra">
					
				</tbody>
			</table>
		</div>
		<div class="col-md-6">
			<table class="table table-condensed" style="margin-top: 30px;">
				<tbody>
					<tr>
						<td>
							Total Compra:
						</td>
						<td>
							00.00
						</td>
						
					</tr>
					<tr class="active">
						<td>
							Descuento:
						</td>
						<td>
							00.00 (5%)
						</td>
						
					</tr>
					<tr class="active">
						<td>
							IVA: (21%)
						</td>
						<td>
							00.00
						</td>
					</tr>
					<tr class="success">
						<td>
							Importe Total:
						</td>
						<td>
							00.00
						</td>
						
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>

    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/scripts.js"></script>
  </body>
</html>
    
asked by Pau Romero 29.08.2017 в 17:01
source

4 answers

0

One solution would be that by clicking on the buy button, you will save a reference to the button clicked on an object. The keys of the object could be the product id that they have selected to buy and the value is a reference of the button that would be the word "this".

After removing the product, you know the product that you are going to delete, then you look in the button object for the product id to be deleted and you enable the button. I hope it serves you, it's a quick solution.

Other solutions: -    - EL pattern pub / sub    - Rxjs

    
answered by 29.08.2017 / 21:16
source
0

What, what you could do is identify each button with a value so you can enable or disable the one you need, this can be with a value or with a name, so I see in your code, you never specify to what button must be affected.

    
answered by 29.08.2017 в 17:52
0

Good morning, first I tell you if you are loading the JQuery library, I recommend you to use it instead of using native JS, since JQuery contains methods that can help you perform what you require.

On the other hand, on a button, the simple appearance of the disabled attribute disables the button. It is not necessary to set disabled="true", so to eliminate it you need to remove the attribute, in JS it can be done with the function:

objetoDOM.removeAttribute("disabled");

However to access that function you need the DOM object, or obtain it through your ID, so it would be advisable to assign your id's to your buttons and when you add one to the cart, add the id as well, so that when you want to delete it just send the id and invoke the method to remove attributes.

I repeat if you use JQuery instead of native JS you can do the same simpler procedure by using:

$(objetoDOM).attr("disabled");//desabilita boton
$(objetoDOM).removeAttr("disabled");//habilita boton
    
answered by 29.08.2017 в 18:17
0

What you add this commented for more understanding, you only had to add an ID to your purchase buttons, I did it dynamically with a counter, then you have to access that button by means of the ID to remove the disabled attribute . It should be noted that I only did the check for the first 3 buttons, as an example. I hope you serve, greetings.

//declaro esta variable para usarla como contador para ir asignando id dinamico al boton comprar, esto sirve para identificarlo al momento de quererlo volver a mostrar
var pulsar = 1;
    var datos = [];
    datos[0] = ["Calcetines Rotos", 16, "img/libro1.jpg"];
    datos[1] = ["Patria", 15.9, "img/libro2.jpg"];
    datos[2] = ["Los Ritos Del Agua", 21.8, "img/libro3.jpg"];
    datos[3] = ["El Extraño Verano de Tom Harvey", 20, "img/libro4.jpg"];
    datos[4] = ["La Habitación en Llamas", 21.5, "img/libro5.jpg"];
    datos[5] = ["El secreto de Ile-de-sein", 16.5, "img/libro6.jpg"];
    datos[6] = ["Ocho días de Marzo", 15.9, "img/libro7.jpg"];
    datos[7] = ["Cinco dias de Octubre", 15.9, "img/libro8.jpg"];
    var salida = "";
    var compra = [];

    function carrito() {
        for (i = 0; i < datos.length; i++) {
            if (i == 0) {
                salida += '<div class="row">';
            }
            else if ((i % 4) == 0) {
                salida += '</div> <div class="row">';
            };
            salida += '<div style="height:300px" class="col-md-3 producto"> <img style="width:20%" src=' + datos[i][2] + ' class="img-rounded"><h3 class="text-primary text-center">' + datos[i][0] + '</h3>' + datos[i][1] + ' € <br> <button onclick = "addCart(this,'+i+')"  onchange = "devolver(this,'+i+')" type="button" style="margin-top:15px" class= "btn btn-primary active btn-default">Comprar</button></div>';
            document.getElementById("hello").innerHTML = salida;
        };
        if (i != 0) {
            salida += "</div>";
        };
    };

    function addCart(boton, libro) {
        compra.push([libro, 1]);
        boton.disabled = true;
        //aqui agregamos un id al boton comprar, en este caso los id seran 1,2,3,4,5,6,7,8..... porque sera solo un caontador, en este caso le llame pulsar
        boton.setAttribute("id", pulsar);
        pulsar++;
//    if(borrarCart()){
//        boton.disabled=false;
//    };
refreshCarrito();
};

function cantidad(posicion, incremento) {
    compra[posicion][1] += incremento;
    if (compra[posicion][1] < 1) {
        compra[posicion][1] = 1;
    };
    refreshCarrito();
};

function refreshCarrito() {
    tablaCompra();
};

function tablaCompra() {
    var imprimir = "";
    for (i = 0; i < compra.length; i++) {
        var x = compra[i][0];
        imprimir += "<tr><td>" + (i + 1) + "</td><td>" + datos[x][0] + "</td><td><button onclick = 'cantidad("+i+", -1 )'>-</button>" + compra[i][1] + "<button onclick = 'cantidad("+i+", 1 )'>+</button></td><td>" + datos[x][1] + " €</td><td><button onclick= 'borrarCart(" + i + ")'>Eliminar</button></td></tr>"
    };
    document.getElementById("tabla-compra").innerHTML = imprimir;
};

function borrarCart(k, boton) {
    compra.splice(k, 1);
    //aqui es donde hace la comprobacion, la hice manual, creo que puedes meterla en un ciclo o algo asi
    //ten en cuenta que esta comprobacion solo comprueba los primeros 3 botones, solo es un ejemplo de como puedes solucionar tu problema
    if(document.getElementById("1").disabled == true){
        document.getElementById("1").removeAttribute("disabled");
    }else{
        if(document.getElementById("2").disabled == true){
            document.getElementById("2").removeAttribute("disabled");
        }else{
         if(document.getElementById("3").disabled == true){
            document.getElementById("3").removeAttribute("disabled");
        }
    }

}
refreshCarrito();

}
carrito();


function devolver(boton,libros){
    if(compra.length=datos[libros]){
        boton.disabled =false;
    }


};
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Compra Libros Online</title>

  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">
  <style>
    .producto {
      padding: 30px 10px;
      border-radius: 10px;
      border: 1px solid #ccc;
      text-align: center;
    }
  </style>
</head>

<body>

  <div class="container-fluid">
    <div class="row">
      <div class="col-md-12">
        <h3>
          Compra libros online
        </h3>
      </div>
    </div>
    <div id="hello">
    </div>

    <div class="row">
      <div class="col-md-12" style="border-bottom: 1px solid #ccc; margin-bottom: 30px;">
        <h3>
          Carrito de Compras:
        </h3>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6">
        <table class="table table-condensed">
          <thead>
            <tr>
              <th>
                #
              </th>
              <th>
                Producto
              </th>
              <th>
                Cantidad
              </th>
              <th>
                Precio
              </th>
              <th>
                Eliminar
              </th>
            </tr>
          </thead>
          <tbody id="tabla-compra">

          </tbody>
        </table>
      </div>
      <div class="col-md-6">
        <table class="table table-condensed" style="margin-top: 30px;">
          <tbody>
            <tr>
              <td>
                Total Compra:
              </td>
              <td>
                00.00
              </td>

            </tr>
            <tr class="active">
              <td>
                Descuento:
              </td>
              <td>
                00.00 (5%)
              </td>

            </tr>
            <tr class="active">
              <td>
                IVA: (21%)
              </td>
              <td>
                00.00
              </td>
            </tr>
            <tr class="success">
              <td>
                Importe Total:
              </td>
              <td>
                00.00
              </td>

            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <script src="js/jquery.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/scripts.js"></script>
</body>

</html>
    
answered by 29.08.2017 в 18:30