Home > Software engineering >  How to set an input value with jquery?
How to set an input value with jquery?

Time:08-06

i have this code, i want when input field #amount is add, jquery will get the value, multiply it with 0.20 and add the value to #agentfee. The value of #agentfee will be used to insert value in sql table using php code. I dont know why my code is not working

HTML
<label for="amount">Rent Amount</label>
    <input type="number" id="amount" name="amount" placeholder="500,000">
<label for="agentfee">Agent fee N</label>
    <input type="Number" id="agentfee" name="agentfee" value="" readonly><br>


JS
$('#amount').change(function() { 
    
    var inputValue = $("#amount").val();
    agentFee = inputValue * 0.20;
    $('#agentfee').val=('agentFee');
});

CodePudding user response:

As @Calvin pointed out already you need to change your $('#agentfee').val() line:

$('#amount').on("input",function() { 

var inputValue = $("#amount").val();
agentFee = inputValue * 0.20;
$('#agentfee').val(agentFee.toFixed(2));
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<label for="amount">Rent Amount</label>
<input type="number" id="amount" name="amount" placeholder="500,000">
<label for="agentfee">Agent fee N</label>
<input type="Number" id="agentfee" name="agentfee" value="" readonly><br>

CodePudding user response:

You don't need the ticks around agentFee, or the equals. It should be

$('#agentfee').val(agentFee);

CodePudding user response:

Try this : $('#amount').change(function() {

var inputValue = $("#amount").val();
agentFee = inputValue * 0.20;
$('#agentfee').val('agentFee');
});

i hope it was useful

CodePudding user response:

Your

$('#agentfee').val=('agentFee');

overrides the val function of $('#agentfee') with the text of agentFee. Instead, you wanted to call val and pass a value, like $('#agentfee').val(yourvalue);. This is a simplified solution (I have changed the event from change to input to make sure the input is more responsive. If you strongly prefer the change event, then let me know)

$('#amount').on('input', function() { 
    $('#agentfee').val($("#amount").val() * 0.20);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="amount">Rent Amount</label>
    <input type="number" id="amount" name="amount" placeholder="500,000">
<label for="agentfee">Agent fee N</label>
    <input type="Number" id="agentfee" name="agentfee" value="" readonly><br>

  • Related