JS переключение переключателей на выпадающий - PullRequest
1 голос
/ 22 марта 2020

У меня есть файл JS, который меняет шрифты в зависимости от выбранного шрифта, до сих пор это делалось с помощью переключателей. Но так как у меня сейчас слишком много опций, я бы хотел перейти в выпадающее меню. Со стороны HTML это легко, но мой JS очень ржавый, и этот сценарий был выполнен творчески.

Секция, которая требует работы:

var font = getRadioVal(document.getElementById('form'), 'NewFont');

Здесь getRadioVal имеет значение

function getRadioVal(form, name) {
    var val;
    // get list of radio buttons with specified name
    var radios = form.elements[name];

    // loop through list of radio buttons
    for (var i=0, len=radios.length; i<len; i++) {
        if ( radios[i].checked ) { // radio checked?
            val = radios[i].value; // if so, hold its value in val
            break; // and break out of for loop
        }
    }
    return val; // return value of checked radio or undefined if none checked

Так как это прямой вывод, я ожидаю, что это сработает. Но это не так. Может кто-нибудь указать, где я ошибаюсь?

var font = document.getElementById('form').elements['NewFont'];

Редактировать:

Форма:

<center>
                            <div id="ambidiv" class="container">
                            <form name="ambiform" id="ambiform" action="javascript:void(-1)">
                            <input type="text" name="theWord" id="theWord" size="35" class="input-hidden" value="Ambigram"><br>

                                  <select id="font" name="NewFont">
                                    <option value="ambimaticv2">AmbimaticHD</option>
                                    <option value="Ambinit">Ambinit</option>
                                    <option disabled>_________</option>
                                    <option value="ambimatic">Ambimatic</option>

                                  </select>

                                <br>
                            <input type="button" value="Generate" onclick="makeAmbi()">
                            </form>
<center>
                            <div id="theView" style="height: 120px; background-color: white;">  </div></center>
                            </div>
                            </center>
                            </div>

Тогда я хочу, чтобы значение из этой формы было положить в

function drawWords (word1, word2) {
    var letters = [];
    for(i = 0; i < word1.length; i++) {

        var img = document.createElement('img');
        if(isLetter(word1.charAt(i)) && isLetter(word2.charAt(i))) {
            img.setAttribute('style', 'float: left;height:60px;width:50px;');

                var font = document.getElementById('ambiform').value;

            if(font=='ambimatic'){

            var url = 'link' + word1.charAt(i).toLowerCase() + '' + word2.charAt(i).toLowerCase() + '.png';
            }

1 Ответ

1 голос
/ 22 марта 2020

Может как то так?

const fonts = document.getElementById("fonts")
// Listen to the select change
fonts.addEventListener("change", e => {
  // Destructuring the value from the selected option
  const { value } = e.target
  // Add font style to the DOM element
  // 'value.charAt(0).toUpperCase() + value.slice(1)' just to convert the first letter case (not actually needed)
  heading.style.fontFamily = value.charAt(0).toUpperCase() + value.slice(1)
})
#heading {
  /* fallback */
  font-family: sans-serif
}
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lato&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Oswald&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">

<select id="fonts">
  <option value="">Select a Font</option>
  <option value="roboto">Roboto</option>
  <option value="lato">Lato</option>
  <option value="oswald">Oswald</option>
  <option value="raleway">Raleway</option>
</select>
<h1 id="heading">Hello world</h1>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...