Jar
Jar

Reputation: 2010

HTML / VUE - Allow user to select/activate multiple <input> elements and type in them at the same time

I have a HTML table with 2 columns that looks like this:

Item       Amount
Icecream   $3
Hotdog     $5
Hamburger  $10

The "amount" column consists of <input> elements that live in a <td>

The user should be able to select the $3 field, (hold down control?) and then also select the $5 field, then type in $6 , causing the $3 and the $5 to be changed to $6.
I understand this is kind of 2 questions. I think once i know how to let the user select multiple inputs I will be able to figure out the typing part. I'm using Vue in case that helps

Upvotes: 0

Views: 294

Answers (1)

Kamil Bęben
Kamil Bęben

Reputation: 1172

You must do a few things to achieve that:

  1. Listen to on click event, which is fairly easy in vuejs
<element @click="firstWay"/> // this will pass only the `$event` as an argument
<element @click="$event => secondWay($event, someOtherProperty)"/> // and this way, you can define your own arguments
methods: {
  firstWay ($event) { },
  secondWay ($event, someOtherProperty) {}
}
  1. Know when ctrl key is pressed (event.ctrlKey is there for you)
  2. Keep track of selected items - using your data object.

Example

Template

    <tr
      v-for="(item, idx) in items"
      :key="idx"
    >
      <td v-text="item.name"/>
      <td>
        <input
          type="number"
          :value="item.price"
          step="0.01"
          :selected="item.selected"
          @click="$event => onClick($event, item)"
          @input="$event => onInput($event, item)"
        />
      </td>
    </tr>

JavaScript

  data: {
    items: [
        { name: 'Icecream',     price: 3.14, selected: false },
        { name: 'Hotdog',       price: 6.00, selected: false },
        { name: 'Hamburger',    price: 2.00, selected: false }
    ]
  },
  methods: {
    onClick (event, item) {
      if (event.ctrlKey) {
        item.selected = !item.selected
      }
    },

    onInput (event, item) {
      const value = event.target.value
      item.price = value

      if (!item.selected) return

      this.items
        .filter(it => it.selected)
        .forEach(it => {
            it.price = value
        })
    }
  }

Styles

input[selected] {
  outline: 1px solid red;
}

Here you play with working demo

Upvotes: 1

Related Questions