John John - 5 months ago 15
Javascript Question

Place jquery result in an input field

I am currently assigning the result of a calculation to a

<p>
element, and I would like the make the same assignment to an input field.

Here is my code.

HTML

<select id="selector" onChange="Expedisi(this);">
<option>Select product</option>
<optgroup label="Sedan">
<option value="Lancer EX">Lancer EX 1.6 / 2.0</option>
<option value="Lancer EX GT">Lancer EX GT</option>
<optgroup label="Sport">
<option value="Lancer Evolution X">Lancer Evolution X</option>
<optgroup label="SUV">
<option value="Outlander">Outlander</option>
</select>

<p id="thetotal"> </p>


JavaScript

$('#selector').on('change', function() {
total = data[$(this).val()].price;

$('#thetotal').text("" + total);
})


The
change
handler will do the assignment, based on which option has been selected in the
#selector
element. I know how to retrieve the selected option's value and how to calculate the
total
, as I'm already assigning this to a
<p>
element.

How do I assign the same value to an
input
element? I just need to know which jQuery method is used to set the input element's value.

Answer

You were very close in your jQuery code. The way to set the contents of a text input field is with the .val() method. Using this, your code would look like this:

$('#selector').on('change', function() {
    var total = data[$(this).val()].price;

    $('#thetotal').val("" + total);
});

Two additional improvements have been made here, in case they existed in the actual code:

  • Added var to the total variable assignment, so that the code doesn't accidentally create (or worse, overwrite) a global variable
  • Added a ; at the end of the code, after registering the event handler callback

The assignment of total assumes that there's a variable named data in scope, and that variable has members with values corresponding to the options in #selector. This means that data would look something like this:

var data = {
    "Lancer EX": { price: 17995 },
    "Lancer EX GT": { price: 21873 },
    "Lancer Evolution X": { price: 26434 },
    "Outlander": { price: 21659 }
};

This data is entirely made up, based on the data structure, so don't rely on it for anything other than understanding the code. You've been warned.

Comments