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

75 views Asked by At

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!

2

There are 2 answers

0
Shreevardhan On BEST ANSWER

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>

1
Clara Raquel On

Okay so as far as I understand you want to switch the value is being set on the input for the height and the width of a div.

you can do something like this.

<form id="programmable-div-config">
    <input type="radio" name="side" value="width">width</input>
    <input type="radio" name="side" value="height">height</input>
    <input type="text"  name="size"/>
    <button type="submit">set</button>
</form>
<div id="programmable-div" style="background-color:red;width:50px;height:50px;"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#programmable-div-config").on("submit", function(event) {
  event.preventDefault();
  const params = new URLSearchParams($(this).serialize());
  const side = params.get("side");
  const size = params.get("size");
  $("#programmable-div").css(side, size+"px");
})
</script>