javascripthtmljqueryregexserial-port

How to Regex InnnerHTML value to input text from copied InnerHTML Value to input text?


How to remove leading zero and kg from copied innerHTML to input field text? from 0000300kg to 300?

enter image description here

Html

<button class="tmbltimbang" id="timbangmuatan" onclick="bruto()">BRUTO</button>
<button class="tmbltimbang" id="timbangkosong" onclick="tara()">TARA</button>

BRUTO <input readonly type="text" name="25" id="25" value=""></input>
TARA<input readonly type="text" name="35" id="35" value=""></input>

JS

function bruto() {
    document.getElementById("25").value = document.getElementById("serialResults").innerHTML;
};
enter code here
function tara() {
    document.getElementById("35").value = document.getElementById("serialResults").innerHTML;
};

Solution

  • You can use regx: /^0+/ to remove unnecessary zero. I will provide sample code.

    function bruto() {
        var value = document.getElementById("serialResults").innerHTML;
    
        // Remove zeros and kg
        var result = value.replace(/^0+/, '').replace('kg', '');
        document.getElementById("25").value = result;
    }
    
    function tara() {
        var value = document.getElementById("serialResults").innerHTML;
    
        // Remove zeros and kg
        var result = value.replace(/^0+/, '').replace('kg', '');
        document.getElementById("35").value = result;
    }
    <div id="serialResults">0000300kg</div>
    
    <button class="tmbltimbang" id="timbangmuatan" onclick="bruto()">BRUTO</button>
    <button class="tmbltimbang" id="timbangkosong" onclick="tara()">TARA</button>
    
    BRUTO <input readonly type="text" name="25" id="25" value=""></input>
    TARA <input readonly type="text" name="35" id="35" value=""></input>