create a page that takes in a planet and a weight in kg in svelte, and shows the heaviness in newtons in javascript

Here's a sample code that takes in a planet and weight input from the user, and calculates the weight in newtons based on the gravity of the selected planet, using JavaScript in a Svelte app.

<!-- App.svelte -->
<script>
  const planets = [
    { name: 'Mercury', gravity: 3.7 },
    { name: 'Venus', gravity: 8.87 },
    { name: 'Earth', gravity: 9.8 },
    { name: 'Mars', gravity: 3.71 },
    { name: 'Jupiter', gravity: 24.79 },
    { name: 'Saturn', gravity: 10.44 },
    { name: 'Uranus', gravity: 8.69 },
    { name: 'Neptune', gravity: 11.15 },
    { name: 'Pluto', gravity: 0.62 },
  ];

  let planet = '';
  let weight = '';
  let result = '';
  
  function calculateWeight() {
    const selectedPlanet = planets.find(p => p.name === planet);
    if (selectedPlanet) {
      result = (weight * selectedPlanet.gravity).toFixed(2) + ' newtons';
    } else {
      result = '';
    }
  }
</script>

<main>
  <h1>Planet Weight Calculator</h1>
  
  <form>
    <label>
      Planet:
      <select bind:value={planet}>
        {#each planets as p}
          <option value={p.name}>{p.name}</option>
        {/each}
      </select>
    </label>
    
    <br />
    
    <label>
      Weight (kg):
      <input type="number" step="0.01" bind:value={weight} on:input={calculateWeight} />
    </label>
  </form>
  
  {#if result}
    <p>The weight on {planet} is {result}</p>
  {/if}
</main>
1199 chars
54 lines

In this code, we first define an array of objects, each representing a planet and its surface gravity in m/s². We then create reactive variables for the selected planet, weight input, and the computed weight in newtons.

When the user inputs a weight value, we search for the selected planet's gravity in the array, and multiply the weight value with the gravity to compute the weight in newtons. We update the result variable with the new computed value, and display it in the UI.

You can style the UI elements with CSS as per your requirement. After compiling the code, you can test it by changing the planet and weight inputs in the form and checking the calculated newtons value.

gistlibby LogSnag