I have this code
const salary = document.querySelector('#salary').value;
const brand = document.querySelector('#brands');
function firstDigit(salary) {
// 1: get first digit using regex pattern
const matches = String(salary).match(/d/);
// 2: convert matched item to integer
const digit = Number(matches[0]);
// 3: add sign back as needed
return (num < 0) ? -digit : digit;
}
let firstNumSalary = firstDigit();
salary.addEventListener("change", changeBrandValue);
function changeBrandValue() {
if (firstNumSalary == 1) {
brand.value = 'ford';
} else if (firstNumSalary == 6) {
brand.value = 'mercedes';
}
}
<label for="brands">Choose a brand:</label>
<select name="brands" id="brands">
<option value="ford">Ford</option>
<option value="audi">Audi</option>
<option value="nissan">Nissan</option>
<option value="opel">Opel</option>
<option value="mercedes">Mercedes</option>
</select>
<label for="salary">Your salary:</label>
<input type="text" name="salary" id="salary">
I would like to change the selected value depending on the first digit of the input. For example if a user inputs a number that its first digit is 6 then the selected option will be Mercedes.
I tried the above code but it does not seem to work.
3
Answers
You have many issues with your code.
firstNumSalary
is not correct. It will evaluated at the first time only and after changing the value it won’t get re evaluate. You need to move it insidechangeBrandValue()
function. Also pass salary value in function likefirstDigit(salary.value);
.const salary = document.querySelector('#salary');
instead ofconst salary = document.querySelector('#salary').value;
firstDigit
it should be likereturn (digit < 0) ? -digit : digit;
Try like below
There were several issues which needed to be fixed in your code:
const salary
should only be the element selection – you can extract the value dynamically when called.the declaration of
firstNumSalary
should be within the event listener – this way it updates whenever the change occurs.You do not need to pass in
salary
as a parameter for the firstDigit.