alex_time
327
3
Vue

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->increments('id');
    $table->string('name');
    $table->decimal('suggested_commission', 5, 4);
    $table->timestamps()
});

Schema::create('products', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('category_id')->unsigned()->index();
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade')->onUpdate('cascade');
    $table->string('name');
    $table->decimal('commission', 5, 4);
    $table->timestamps()
});

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>
</select>
<input name="commission" type="text">
<script>
# basically something like:
$('#category_id').change(function(){
    var selected_category = $('#category_id option:selected').val();
    var suggested_commission = $('#suggested_commissions_'+selected_category).val();
    $('#commission').val(suggested_commission);
});
</script>

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.