Passing user HTML input as javascript function argument - javascript

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

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

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);

Related

how to use javascript to extract and show a random text from a datalist when using onclick event?

I would like that a JavaScript function could take a random sentence from a datalist in the same file, and then show it when I click on a button with an "onclick" event. I am looking for the easiest way to do that. Does anyone have an example?
(Just looking around, trying JavaScript for the first time)
let dataList =["sentence 1","sentence 2","sentence 3","sentence 4"]
let div = document.getElementById('asd')
document.getElementsByTagName("button")[0].addEventListener("click",myFunc)
function myFunc(){
let x = parseInt(Math.random()* dataList.length )
div.innerHTML = dataList[x]
}
<button>click me</button>
<div id='asd'></div>
This is easy using the function parseInt() and Math.random()*n:
var yourDataList = ["Option 1", "Option 2", "Option 3"]; // Define datalist
var myBtn = document.getElementById("yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Decclre random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * yourDataList.length); //Get random number between 0 and the length of your datalist
return yourDataList[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
alert(getRandom()); //Do whatever you want to with the random value
});
<button id = "yourIdHere">Click me!!</button>
EDIT:
Using the DOM HTML element <datalist> as your input, this is some working code:
var yourDataList = document.getElementById("datalist"); // Define datalist
var myInput = document.getElementById("myInput");
var dataListOptionsElems = yourDataList.querySelectorAll("option");//Get all options elements
var dataListOptions = [];//Declare options
for(var i = 0;i<dataListOptionsElems.length;i++){
dataListOptions.push(dataListOptionsElems[i].value);
}
var myBtn = document.getElementById("yourIdHere"); //Declare button, replace yourIdHere with your ID
var randomNum = 0; //Declare random number
function getRandom() { //Declare your function
randomNum = parseInt(Math.random() * dataListOptions.length); //Get random number between 0 and the length of your datalist
return dataListOptions[randomNum]; //Return your value
}
myBtn.addEventListener("click", function() { //Bind a listener to the button
alert(getRandom());
console.log(getRandom());
myInput.value = getRandom();
//Do whatever you want to with the random value
});
<button id = "yourIdHere">Click me!!</button>
<input list="datalist" id="myInput">
<datalist id="datalist">
<option value="Option1">
<option value="Option2">
<option value="Option3">
<option value="Option4">
<option value="Option5">
</datalist>
<p>Note: the alert box, console message, and input value will not be the same, due to it being random each time the function is called.</p>
Working JSFiddle

convert repetitive variables and functions into loops

can anyone help me how to convert this into loops :) hi newbie here in javaScript:) the output of this is a input form, i want all the value that typed into the form to be appear instantly by using keyup event thanks in advance :)
let textarea = document.querySelectorAll('span')
let bns = document.querySelector('#bns');
let id = document.querySelector('#id');
let img = document.querySelector('#img');
let lg = document.querySelector('#lg');
textarea.forEach(function (item, index) {
item.classList.add('t'+ `${index}`)
//console.log(item)
})
let input = addEventListener('keyup', function(){
let strbns = bns.value;
let strid = id.value;
let strimg = img.value;
let strblg = lg.value;
document.querySelector('.t0').innerText = strbns
document.querySelector('.t1').innerText = strid
document.querySelector('.t2').innerText = strimg
document.querySelector('.t3').innerText = strblg
});
output
i create variables to each input field and used the keyup event to print the out put to individual span. yes it works but its so repetitive and i thinks it is much better if it's convert it into for loops but i dont know how
You can make it more optimal by give a try like this.
const formData = {
bns: document.querySelector('#bns'),
id: document.querySelector('#id'),
img: document.querySelector('#img'),
lg: document.querySelector('#lg')
};
document.addEventListener('keyup', function() {
Object.keys(formData).forEach((key, index) => {
document.querySelector(`.t${index}`).innerText = formData[key].value
})
});
<input type="text" id="bns"/>
<input type="text" id="id"/>
<input type="text" id="img"/>
<input type="text" id="lg"/>
<div class="t0"></div>
<div class="t1"></div>
<div class="t2"></div>
<div class="t3"></div>
Use two arrays which are the same length. Then you can loop over one of them with the index to get the corresponding element:
const elements = [bns, id, img, lg];
const selectors = [".t0", ".t1", ".t2", ".t3"].map((s) => document.querySelector(s));
addEventListener('keyup', function() {
elements.forEach((el, index) => {
selectors[index].innerText = el.value;
});
});

Is there a way to make a search bar like this?

So i am making a search bar with javascript and jquery and i loop through a list of objects and an if statement checks if the input value includes something in my array. Then if it does include the item will get added to a select as an option and if the user removes the characters in the input the list would be empty.
But i can't seem to make it work.
This is what i've got:
<input class="type" value="" />
<select class="opties">
</select>
$('.type').on('keyup', function() {
let input = $('.type').val().toLowerCase();
let pc = ['Processor', 'Ram', 'Videokaart', 'Voeding', 'SSD', 'Fans'];
for(let i=0; i<pc.length;i++) {
if(!pc[i].toLowerCase().includes(input)) {
$('.opties').remove(pc[i])
} else {
$('.opties').append("<option>"+pc[i]+"</option>")
}
if(input == '') {
$('.opties').empty();
}
}
})
The output right now is a few options that are duplicates of each other.
Another approach is to filter() your array and insert new options each update.
You may want to throttle or debounce this to give user time to type
let $sel = $('.opties')
$('.type').on('input', function() {
$sel.empty()
let input = $('.type').val().trim().toLowerCase();
let pc = ['Processor', 'Ram', 'Videokaart', 'Voeding', 'SSD', 'Fans'];
if (input.length) {
const filtered = pc.filter(v => v.toLowerCase().includes(input));
const opts = filtered.map(v => new Option(v, v));
$sel.append(opts)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="type" value="" />
<select class="opties">
</select>
Something like this?
const pc = ['Processor', 'Ram', 'Videokaart', 'Voeding', 'SSD', 'Fans'];
$('.type').on('keyup', function() {
const input = $('.type').val().toLowerCase();
for (let option of pc) {
$(`.opties option[name='${option}']`).remove()
if (option.toLowerCase().includes(input) && input.length)
$('.opties').append(`<option name='${option}'>${option}</option>`)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="type" value="" />
<select class="opties"></select>
Main problem is that $('.opties').remove(pc[i]) is not working. You are trying to remove the select-element instead of its children. Give them name attributes, this is a good way to go!

How to query multiple elements that start with the same ID and then check whether the input has changed

I have a list of text inputs which all start with the same id but are slightly different at the end. When text is entered by the user in any of these input fields I want to execute a function. At the moment this is working with the following code:
var heightInches = document.querySelector("#Height_Inches");
var heightFeet = document.querySelector("#Height_Feet");
var heightCentimeters = document.querySelector("#Height_Centimeters");
heightInches.oninput = function (e) {
console.log("Edited");
}
heightFeet.oninput = function (e) {
console.log("Edited");
}
heightCentimeters.oninput = function (e) {
console.log("Edited")
}
The issue is that I don't like the repetition and would rather query all of the ids that begin with "Height_" and do something (as what is excuted inside each function will be the same.
Here is what I have tried but does not work:
var allHeight = document.querySelector('[id*="Height_"]');
allHeight.oninput = function (e) {
console.log("edited");
}
I have also tried the same with querySelectorAll
Please could someone help with where I am going wrong here? Every other Stack Overflow answer and article I see seems to suggest that id* is the correct way to select? Thank you
If I understand correctly, this is what you are looking for.
The only thing you were missing is looping through your elements.
const inputs = document.querySelectorAll('[id*="Height_"]');
inputs.forEach( input => {
input.oninput = function (e) {
console.log("edited");
}
})
<input type="text" id="Height_1">
<input type="text" id="Height_2">
<input type="text" id="Height_3">
Rather than use an ID, which is intended to be unique, why not add a class like .height-input to each input and then you can select them all?
// Get elements
const inputs = document.querySelectorAll('.height-input');
const outputEl = document.querySelector('.output');
// Attach event handlers
for (let i = 0; i < inputs.length; i++) {
inputs[i].oninput = function(e) {
// Handle input
outputEl.innerHTML = `Input received on #${e.target.id}`;
}
}
.output {
margin-top: 10px;
}
<input type="text" class="height-input" id="HeightInches">
<input type="text" class="height-input" id="HeightFeet">
<input type="text" class="height-input" id="HeightCentimeters">
<div class="output">Waiting for input...</div>

Set input value with JavaScript - depending on value of different input

Hey I got this problem I cannot work out by myself. It's html form which passes data to PHP to send mail.
First, I have dropdown list:
<select id="dropdown" name="dropdown">
<option selected="true" disabled="disabled">Choose</option>
<option id="A" value="one#gmail.com">One</option>
<option id="B" value="two#gmail.com">Two</option>
</select>
This dropdown defines the value of next input:
<input type='text' name="to" id="to" value="e-mail"/>
<script>
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
}
</script>
At last, I need to define third input from the value of second.
<input type='text' name="from" id="from" value="Office manager"/>
But this last code doesn't work for me:
<script>
var name;
if (document.getElementById('to').value == "one#gmail.com" {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
</script>
How do I proceed?
JSFiddle
It does if you put it like this
http://jsfiddle.net/170x1xs9/
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
var name;
if (document.getElementById('to').value == "one#gmail.com") {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
}
Syntax Error.
if (document.getElementById('to').value == "one#gmail.com" // No ')'
If you use event in your function, you should pass it as an argument.
document.getElementById('dropdown').onchange = function (event /* <-------- HERE */) {
document.getElementById('to').value = event.target.value
}
By not declaring it, you're using window.event, which might work in some browsers, but it's bad practise.
Check out the solution at: http://jsfiddle.net/jam7m5ca/1/
You forgot to pass the parameter event.
document.getElementById('dropdown').onchange = function (event) {
document.getElementById('to').value = event.target.value;
};

Categories