Nakul Tiruviluamala
Nakul Tiruviluamala

Reputation: 565

Passing user HTML input as javascript function argument

I have this line of javascript:

stave.addClef("treble").addTimeSignature("4/4");

Based on what the user types as input in the HTML document, I'd like to change "4/4" to "3/4," or any other fraction that the user comes up with. What is the easiest way to make this conditional substitution?

Thanks, Nakul

Upvotes: 0

Views: 57

Answers (2)

Jay Kariesch
Jay Kariesch

Reputation: 1482

Here's an option that'll allow a user to toggle number inputs up and down:

<input type="number" id="fraction-1"/>
<input type="number" id="fraction-2"/>

Current Signature:
<div id="current-sig"></div>

Then in your javascript...


// Get the select form element
const FRACT_1 = 'fract-1'
const FRACT_2 = 'fract-2'
const fract1 = document.querySelector(`#${FRACT_1}`)
const fract2 = document.querySelector(`#${FRACT_2}`)
const currentSigDiv = document.querySelector('#current-sig')

let currentSignature = '4/4'

const changeSignatureByFraction = ({target}) => {
    if(target.id === FRACT_1)) {
        currentSignature = `${target.value}${currentSignature.substring(1)}`
        stave.addClef("treble").addTimeSignature(currentSignature)
        currentSigDiv.innerHTML = currentSignature
    } else {
        currentSignature = `${currentSignature.slice(0, -1)}${target.value}`
        stave.addClef("treble").addTimeSignature(currentSignature)
        currentSigDiv.innerHTML = currentSignature
    }

}

// Listen for a change event
fract1.addEventListener('change', changeSignatureByFraction)
fract2.addEventListener('change', changeSignatureByFraction)

currentSigDiv.innerHTML = currentSignature

Upvotes: 1

Denis O.
Denis O.

Reputation: 1850

Create a dropdown list with possible fractions. Query its value into the variable. Pass the variable as an argument for addTimeSignature() method.

HTML:

<select id="TimeSignatureSelect">
    <option value='1/4'>1/4</option>
    <option value='2/4'>2/4</option>
    <option value='3/4'>3/4</option>
    <option value='4/4'>4/4</option>
</select>

JS:

const timeSig = document.getElementByID('TimeSignatureSelect').value;
stave.addClef("treble").addTimeSignature(timeSig);

Upvotes: 0

Related Questions