Удалите установленное по умолчанию значение в переключателе и замените его другим переключателем, который нажимается - PullRequest
0 голосов
/ 14 декабря 2018

Я просто хочу изменить значение проверки по умолчанию в переключателе на значение, выбранное пользователем. Потому что всякий раз, когда я пытаюсь это сделать, в журнале консоли все равно отображается значение по умолчанию, а не проверяемое.Я хочу изменить значение по умолчанию для того, чтобы пользователь выбрал в HTML.Может кто-нибудь мне помочь?Я просто действительно новичок.Любая помощь будет оценена.Спасибо. Вот код.CSS:

    html,
    body {
      font: 400 small-caps 16px/1.25 Arial;
    }

    fieldset {
      width: fit-content;
      padding: 0;
    }

    legend {
      font-size: 1rem
    }

    details {
      width: 150px;
      cursor: pointer;
      margin: 0 4px -5px 0;
      padding: 0 0 0 10px;
    }

    summary {
      position: relative;
      width: 96%;
      outline: 0.5px ridge grey;
    }


    /*
    Hides <detail>'s default arrow
    */

    details summary::-webkit-details-marker {
      visibility: hidden;
      position: absolute;
      z-index: -1;
    }


    /*| Pseudo-<option>
    All pseudo-<option> are initially hidden and 
    <label class='opt'> are the only tags that will show/hide, 
    the next comment explains how.
    */

    .rad {
      display: none
    }

    .opt {
      display: none;
      margin: 0 0 2px 0;
      cursor: pointer;
      font-size: 0.9rem;
      box-shadow: -2px -2px 11px rgba(0, 0, 0, 0.3) inset;
    }


    /*| Two Conditions
    1. If <details open='true'> all <label class='opt'> are visible.
    =============================================
    2. if <input class='rad' type='radio' checked> then the 
       <label class='opt'> that proceeds the radio button is visible.
    */

    [open] .opt,
    .rad:checked+.opt {
      display: block;
    }

    /*| For Demonstration Purposes
    This ruleset changes how the console is displayed.
    */

    .as-console-wrapper {
      width: 50%;
      min-height: 100%;
      margin-left: 50%;
      font-variant: normal;
    }

    .as-console-row.as-console-row::after {
      content: '';
      padding: 0;
      margin: 0;
      border: 0;
      width: 0;
    }
</style>

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Custom select box Jquery Plugin by VJ</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

<!--| Flag Icons
This stylesheet provides the flag icons. 
For details, go to: 
https://afeld.github.io/emoji-css/
-->

  <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet" />
</head>

<body>
 <form id="container">
  <fieldset>
    <legend>Country</legend>

<!--| Pseudo-<select> 
<details> provides the dropdown behavior and
<summary> contains the pseudo-<option>
-->
    <details>
     <summary>

<!--| 4 Pseudo-<option> 
Each <label> and <input type='radio'> pair are
synced to each other by matching the values of
<label for="ID"> and <input id="ID">. 
-->

<!--| Trigger and State
When <label> is clicked ... <input type='radio'>
is checked. This simple "cause and effect" can
be leveraged into a system of states (ie off/on). 
For details, review the CSS. 
-->

  <input id='X' type='radio' class='rad' name='rad' value="" checked>
  <label class='opt' for='X'>
    &nbsp;&nbsp;
    <i class='em em-us'></i> 
    United States
  </label>

  <input id='US' type='radio' class='rad' name='rad' value="United States">
  <label class='opt' for='US'>
    &nbsp;&nbsp;
    <i class='em em-us'></i> 
    United States
  </label>

  <input id='GB' type='radio' class='rad' name='rad' value="Great Britain">
  <label class='opt' for='GB'>
    &nbsp;&nbsp;
    <i class='em em-gb'></i> 
    Great Britain
  </label>

  <input id='IN' type='radio' class='rad' name='rad' value="India">
  <label class='opt' for='IN'>
    &nbsp;&nbsp;
    <i class='em em-flag-in'></i>
    India
  </label>

  <input id='NP' type='radio' class='rad' name='rad' value="Nepal">
  <label class='opt' for='NP'>
    &nbsp;&nbsp;
    <i class='em em-flag-np'></i>
    Nepal
  </label>

  </summary>
</details>
</fieldset>
</form>

</body>
</html>

JAVASCRIPT

<script type="text/javascript">
    var xC = document.forms.container;
    var xE = xC.elements;
    var vR = xE.rad;

    xC.onchange = function() {
      // console.log(vR.value);
      // location.reload();
      if(vR.value=="United States") {
        alert("welcome us");
        location.reload();
      }
      else if(vR.value=="United States") {
        alert("welcome us");
        location.reload();
      }

    }
</script>

Ответы [ 2 ]

0 голосов
/ 17 декабря 2018

localStorage

Используйте localStorage, чтобы сохранить выбранное значение, а затем получить значение при перезагрузке страницы. Примечание: Подробнее о том, как работает остальная часть этой демонстрации, см. В этом сообщении .

var xC = document.forms.container;
var xE = xC.elements;
var vR = xE.rad;
var cty = localStorage.getItem('country');
xC.addEventListener('change', saveCountry);
document.addEventListener('DOMContentLoaded', setCountry);
function saveCountry(e) {
  localStorage.setItem('country', vR.value);
  console.log("Welcome, " + vR.value);
};
function setCountry(e) {
  for (let i = 0; i < vR.length; i++) {
    if (vR[i].value === cty) {
      vR[i].checked = true;
    }
  }
  console.log("Welcome, " + vR.value);
};


Плункер

Демо

Это демо не работает полностью из-за ограничения SO localStorage. Дляполностью функциональная демонстрация, просмотрите этот Plunker .Чтобы проверить это, выберите страну, затем обновите страницу, нажав кнопку обновления на панели предварительного просмотра или CTRL + ENTER для ПК или + RETURN для Mac.

Подробности прокомментированы в демоверсии

var xC = document.forms.container;
var xE = xC.elements;
var vR = xE.rad;
/* 
Get the string saved in localStorage named 'country'
*/
var cty = localStorage.getItem('country');

/*| When <form> is changed
Call saveCountry()
*/
xC.addEventListener('change', saveCountry);

/*| When Page is Reloaded
Call setCountry()
*/
document.addEventListener('DOMContentLoaded', setCountry);

/*
Save the value selected in pseudo-<select> in localStorage
*/
function saveCountry(e) {
  localStorage.setItem('country', vR.value);
  console.log("Welcome, " + vR.value);
};

/*
Loop through the pseudo-<option>s
When a pseudo<option> matches the value saved...
in localStorage under the name of 'country'...
check that pseudo-<option> by assigning it...
the attribute [checked] = true
*/
function setCountry(e) {
  for (let i = 0; i < vR.length; i++) {
    if (vR[i].value === cty) {
      vR[i].checked = true;
    }
  }
  console.log("Welcome, " + vR.value);
};
html,
body {
  font: 400 small-caps 16px/1.25 Arial;
}

fieldset {
  width: fit-content;
  padding: 0;
}

legend {
  font-size: 1rem
}

details {
  width: 170px;
  cursor: pointer;
  margin: 0 4px -5px 0;
  padding: 0 5px 10px 10px;
}

summary {
  width: 100%;
  position: relative;
}


/* 
    Shows <detail>'s default arrow
    */


/*
    summary::-webkit-details-marker {
      position: absolute;
      padding: 0 0 0 5px;
      z-index: 1;
      top: 25%;
    }
    
    [open] summary::-webkit-details-marker {
      top: 5%;
    }
    
    .em {
      padding: 0 0 0 10px;
    }
    */


/*
    Hides <detail>'s default arrow
    */

summary::-webkit-details-marker {
  visibility: hidden;
  position: absolute;
  z-index: -1;
}

.em {
  padding: 0;
}


/*| Pseudo-<option>
    All pseudo-<option> are initially hidden and 
    <label class='opt'> are the only tags that will show/hide, 
    the next comment explains how.
    */

.rad {
  display: none
}

.opt {
  display: none;
  position: relative;
  z-index: 2;
  width: 100%;
  margin: 0;
  cursor: pointer;
  font-size: 0.9rem;
  box-shadow: -2px -2px 11px rgba(0, 0, 0, 0.3) inset;
}


/*| Two Conditions
    1. If <details open='true'> all <label class='opt'> are visible.
    =============================================
    2. if <input class='rad' type='radio' checked> then the 
       <label class='opt'> that proceeds the radio button is visible.
    */

[open] .opt,
.rad:checked+.opt {
  display: block;
}


/*| For Demonstration Purposes
    This ruleset changes how the console is displayed.
    */

.as-console-wrapper {
  max-height: 50%;
  font-variant: normal;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Custom select box Jquery Plugin by VJ</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  <!--| Flag Icons
This stylesheet provides the flag icons. 
For details, go to: 
https://afeld.github.io/emoji-css/
-->

  <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">


</head>

<body>
  <form id="container">
    <fieldset>
      <legend>Country</legend>

      <!--| Pseudo-<select> 
<details> provides the dropdown behavior and
<summary> contains the pseudo-<option>
-->
      <details>
        <summary>

          <!--| 4 Pseudo-<option> 
Each <label> and <input type='radio'> pair are
synced to each other by matching the values of
<label for="ID"> and <input id="ID">. 
-->

          <!--| Trigger and State
When <label> is clicked ... <input type='radio'>
is checked. This simple "cause and effect" can
be leveraged into a system of states (ie off/on). 
For details, review the CSS. 
-->

          <input id='X' type='radio' class='rad' name='rad' value="" checked>
          <label class='opt' for='X'>
            &nbsp;&nbsp;
            <i class='em em-us'></i> United States
          </label>

          <input id='US' type='radio' class='rad' name='rad' value="United States">
          <label class='opt' for='US'>
            &nbsp;&nbsp;
            <i class='em em-us'></i> United States
          </label>

          <input id='GB' type='radio' class='rad' name='rad' value="Great Britain">
          <label class='opt' for='GB'>
            &nbsp;&nbsp;
            <i class='em em-gb'></i> Great Britain
          </label>

          <input id='IN' type='radio' class='rad' name='rad' value="India">
          <label class='opt' for='IN'>
            &nbsp;&nbsp;
            <i class='em em-flag-in'></i> India
          </label>

          <input id='NP' type='radio' class='rad' name='rad' value="Nepal">
          <label class='opt' for='NP'>
            &nbsp;&nbsp;<i class='em em-flag-np'></i>&nbsp;&nbsp;Nepal
          </label>

        </summary>
      </details>

    </fieldset>
  </form>

  <!--|For Demonstration Purposes
Provides console
-->


</body>

</html>
0 голосов
/ 14 декабря 2018

Вы говорите, что при выборе радиокнопки США она по умолчанию выбирает радиокнопку?Строки

location.reload()

перезагружают страницу всякий раз, когда выбирается радиокнопка США, и на новой странице по умолчанию используется первая радиокнопка, которая выбрана.Таким образом, вы можете просто удалить эти строки, и правильный переключатель будет оставаться выбранным.

Если перезагрузка страницы является преднамеренной, и вы хотите, чтобы на новой странице была выбрана та же кнопка переключателя, что и на последней странице, вы можете пропуститьURL-адрес для новой страницы, а затем используйте javascript на новой странице, чтобы прочитать любые параметры и выбрать правильную кнопку радио

например

document.replace('yourpage.html?selectedCountry=US')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...