javascriptjquerycsselementparseint

Input textfield for a custom Height and Width on a div element with parseInt()


With 2 radio buttons and one textfield, it's possible to give an element a custom height and width:

$(document).ready(function() {
  $('#btnSetColor').on('click', function() {

    const DeBreedte = $('#txtKeuze').val();
    const DeHoogte = $('#txtKeuze').val();

    const keuze = $('input:checked').attr('id');

    if (keuze === 'DeHoogte') {

      $('#divResult').css('height', DeHoogte + 'px');

    } else if (keuze === 'DeBreedte') {

      $('#divResult').css('width', DeBreedte + 'px');
    }
  });
});
<input type="radio" id="DeHoogte" name="type" />Hoogte
<input type="radio" id="DeBreedte" name="type" />Breedte<br />

<input type="text" id="txtKeuze" placeholder="Uw waarde..." />

<button id="btnSetColor">Stel in</button><br />
<div id="divResult">Voorbeeld tekst</div>

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

Now I'm looking for a setup that's based on 2 textfields to input a custom Width and Height with the parseInt() function.

Many thanks for the help!


Solution

  • From what I understood, you don't need parseInt here. Just use the valueAsNumber property of the HTMLInputElement and you can apply directly as style. For instance

    const hoogte = document.getElementById('Hoogte'),
      breedte = document.getElementById('Breedte'),
      btnSetColor = document.getElementById('btnSetColor'),
      divResult = document.getElementById('divResult');
    
    btnSetColor.onclick = function() {
      divResult.style.height = `${hoogte.valueAsNumber}px`;
      divResult.style.width = `${breedte.valueAsNumber}px`;
    };
    #divResult {
      background: lightgrey;
    }
    <input type="number" id="Hoogte" placeholder="Hoogte..." />
    <input type="number" id="Breedte" placeholder="Breedte..." />
    <button id="btnSetColor">Stel in</button>
    <div id="divResult">Voorbeeld tekst</div>