Input text value based on a related select

Posted 3 years ago by alex_time

I have a Product and a Category model, a product has a commission field and it belongs to a category, the related category has a suggested_commission field, this is the migrations:

Schema::create('categories', function (Blueprint $table) {
    $table->decimal('suggested_commission', 5, 4);

Schema::create('products', function (Blueprint $table) {
    $table->decimal('commission', 5, 4);

On the view for creating a new product I have to select the category using a select having $category->id as value and $category->name as option text, but also I need the product->commission field to be equal to the suggested_commission value based on the selected category.

My idea is to create one hidden text input containing the suggested_commission value for each select option, and using jQuery I would create an onChange listener to the select, get the selected option value, get the related suggested_commission value from the hidden input and update the product->commission input, something like this:

<input type="hidden" name="suggested_commissions[1]" id="suggested_commissions_1" value="5">
<input type="hidden" name="suggested_commissions[2]" id="suggested_commissions_2" value="10">
<input type="hidden" name="suggested_commissions[3]" id="suggested_commissions_3" value="15">
<select name="category_id" id="category_id">
    <option value="1">Cat. 1</option>
    <option value="2">Cat. 2</option>
    <option value="3">Cat. 3</option>
<input name="commission" type="text">
# basically something like:
    var selected_category = $('#category_id option:selected').val();
    var suggested_commission = $('#suggested_commissions_'+selected_category).val();

But I was wondering if there is a more elegant way to accomplish that using Vue and not jQuery, and I also would like to avoid to create one hidden input for each select option, avoiding also an Ajax request to the server only to get the category json response from Laravel.

What do you think about all this stuff??

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.