How to set the default radio in javascript

0

I have a form that has 2 options, and I can not find a way to define the one I want, I found that it should be done with

radiobtn = document.getElementById("theid");
radiobtn.checked = true;

in another stackoverflow thread, but I have

<script type="text/javascript">
function changeSystem(s)


{
    if(s=='english')
    {
        document.getElementById('englishWeight').style.display='block';
        document.getElementById('englishHeight').style.display='block';
        document.getElementById('metricWeight').style.display='none';
        document.getElementById('metricHeight').style.display='none';
    }
    else
    {
        document.getElementById('englishWeight').style.display='none';
        document.getElementById('englishHeight').style.display='none';
        document.getElementById('metricWeight').style.display='block';
        document.getElementById('metricHeight').style.display='block';
    }
}

</script>

and in the form:

<form method="post">
    <div class="calculator_div">
        <div>
<input type="radio" value="metric" name="system" <?php if($_SESSION['bmi_calc_system']!='' and $_SESSION['bmi_calc_system']=='metric') ;?> onclick="changeSystem('metric');"> Metrico &nbsp;
<input type="radio" value="english" name="system" <?php if($_SESSION['bmi_calc_system']=="" or $_SESSION['bmi_calc_system']=='english') ;?> onclick="changeSystem('english');"> Ingles


</div>
        <div><label>Tu peso:</label>
            <span id="englishWeight" style="display:<?php echo ($_SESSION['bmi_calc_system']=='' or $_SESSION['bmi_calc_system']=='english')?'block':'none'?>;"><input type="text" name="weight_en" size="6" value="<?php echo !empty($_SESSION['bmi_calc_weight_en'])?$_SESSION['bmi_calc_weight_en']:""?>"> lbs</span>
            <span id="metricWeight" style="display:<?php echo (($_SESSION['bmi_calc_system']=="" or $_SESSION['bmi_calc_system']=='english'))?'none':'block'?>;"><input type="text" name="weight_met" size="6" value="<?php echo !empty($_SESSION['bmi_calc_weight_met'])?$_SESSION['bmi_calc_weight_met']:""?>"> kg</span>
        </div>   
        <div><label>Tu altura:</label>
            <span id="englishHeight" style="display:<?php echo (($_SESSION['bmi_calc_system']=='' or $_SESSION['bmi_calc_system']=='english'))?'block':'none'?>;"><input type="text" size="6" name="height_ft_en" value="<?php echo !empty($_SESSION['bmi_calc_height_ft_en'])?$_SESSION['bmi_calc_height_ft_en']:""?>"> ft
            &nbsp; <input type="text" size="6" name="height_in_en" value="<?php echo ($_SESSION['bmi_calc_height_in_en']!='')?$_SESSION['bmi_calc_height_in_en']:""?>"> in</span>
            <span id="metricHeight" style="display:<?php echo ($_SESSION['bmi_calc_system']=='' or $_SESSION['bmi_calc_system']=='english')?'none':'block'?>;">
            <input type="text" name="height_met" size="6" value="<?php echo ($_SESSION['bmi_calc_height_met']!='')?$_SESSION['bmi_calc_height_met']:""?>"> cm
            </span>
        </div>
        <div align="center">
            <input type="hidden" name="calculator_ok" value="ok">
<br><br>


<button type="submit" class="btn btn-success btn-lg">Calcular !!!</button>

        </div>

    </div>    
    </form> 
    
asked by Matt 29.01.2017 в 15:18
source

1 answer

0
  

I have a form that has 2 options, and I can not find a way to define the one I want.

It's not difficult at all. What you have to do is add a listener for the event change of the radios and, show / hide the fields according to the unit of measure and, execute the event in the default radius. Consider the following example.

let form = document.getElementById('icmForm');
let englishUnit = form.querySelector('#eng');
let metricUnit = form.querySelector('#met');
let output = form.querySelector('#icm');
let mesUnit = 'english'; // unidad por defecto

form.addEventListener('submit', calculateICM);
englishUnit.addEventListener('change', onUnitChange);
metricUnit.addEventListener('change', onUnitChange);

englishUnit.click(); // unidad por defecto, Inglés


function calculateICM (e) {
	e.preventDefault();
  let weight = 0;
  let height = 0;
  let icm = 0;
  
  if (mesUnit === 'english') {
  	weight = Number(form.querySelector('span[id="englishWeight"] input').value);
    height = Number(form.querySelector('span[id="englishHeight"] input').value);
  }
  else if (mesUnit === 'metric') {
  	weight = Number(form.querySelector('span[id="metricWeight"] input').value);
    height = Number(form.querySelector('span[id="metricHeight"] input').value);
  }
  
  icm = (weight / Math.pow(height, 2)).toFixed(2);
  output.textContent = icm;
  form.querySelector('.results').style.display = 'block';
}

function onUnitChange (e) {
	mesUnit = e.target.value;
  
  if (mesUnit === 'english') {
  	let englishFields = document.querySelectorAll('span[id^="english"]');
    let metricFields = document.querySelectorAll('span[id^="metric"]');
    
    [].forEach.call(metricFields, function (field) {
    	field.style.display = 'none';
    });
    [].forEach.call(englishFields, function (field) {
    	field.style.display = 'block';
    });
  }
  if (mesUnit === 'metric') {
  	let metricFields = document.querySelectorAll('span[id^="metric"]');
    let englishFields = document.querySelectorAll('span[id^="english"]');
    
    [].forEach.call(englishFields, function (field) {
    	field.style.display = 'none';
    });
    [].forEach.call(metricFields, function (field) {
    	field.style.display = 'block';
    });
  }
}
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,600');


*, *:before, *:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  background-color: #fff;
  font-family: 'Open Sans';
}
.form {
  border: 1px solid #e8e8e8;
  border-radius: 3px;
  margin: 20px auto;
   width: 100%; 
}
.form .head {
  background-color: #f5f5f5;
  border-bottom: 1px solid #eee;
  height: 60px;
  line-height: 60px;
  padding: 0 1rem;
}
.form .head h2 {
  color: #444;
  font-weight: 700;
}
.form .body {
  padding: 1rem;
}
.form .body fieldset {
  border: 1px solid #eee;
  padding: .5rem;
}
.form .body fieldset legend {
  font-size: 13px;
}
.form .body fieldset label {
  color: #444;
  font-size: 14px;
  padding-right: 10px;
}
.form .body .row {
  padding: .5rem 0 0 0;
  overflow: hidden;
}
.form .body .row input {
  border: 1px solid #eee;
  border-radius: 3px;
  color: #444;
  font-family: 'Open Sans';
  font-size: 14px;
  padding: .5rem;
  width: 100%;
}
.form .body .row input:focus {
  border-color: rgba(0, 200, 255, .75);
  outline: none;
}
.form .body .results {
  background-color: #F0F9FE;
  border: 1px solid rgba(0, 150, 255, .5);
  border-radius: 3px;
  padding: .5rem 1rem;
  margin-top: .5rem;
}
.form .body .results p {
  color: #2980b9;
  font-size: 15px;
}
.form .foot {
  padding: 0 1rem .5rem 1rem;
  text-align: right;
}
.form .foot .btn {
  background-color: #f5f5f5;
  border: 1px solid transparent;
  border-radius: 3px;
  color: #555;
  font-family: 'Open Sans';
  padding: .5rem 1rem;
}
.form .foot .btn.primary {
  background-color: #2980b9;
  color: #fff;
}
<form id="icmForm" class="form" style="width: 400px">
  <header class="head">
    <h2>Calculadora ICM</h2>
  </header>
  <article class="body">
    <section class="group">
      <fieldset>
        <legend>Tipo de unidad</legend>
        <input type="radio" name="unt" value="english" id="eng">
        <label for="eng">English</label>
        <input type="radio" name="unt" value="metric" id="met">
        <label for="met">Metrics</label>
      </fieldset>
    </section>
    <section class="row">
      <span id="englishWeight">
        <input type="text" placeholder="Ingresa tu peso (kg)">
      </span>
      <span id="metricWeight">
        <input type="text" placeholder="Ingresa tu peso (kg)">
      </span>
    </section>
    <section class="row">
      <span id="englishHeight">
        <input type="text" placeholder="Ingresa tu talla (mt)">
      </span>
      <span id="metricHeight">
        <input type="text" placeholder="Ingresa tu talla (mt)">
      </span>
    </section>
    <section class="results" style="display: none">
      <p>Tu ICM es: <span id="icm">0.0</span></p>
    </section>
  </article>
  <footer class="foot">
    <button type="submit" class="btn primary">
      Calcular
    </button>
  </footer>
</form>

Demo

This code works, however I do not think it's the best option for a reason. If you want to add HTML validation to the inputs by means of the attribute required you will have a problem, since, when executing the form, Chrome will try to show empty input messages even in those that are hidden, which will give you an error when executing the form: Element with name = xxx is not focusable . Obviously this can be fixed by agreating the required attribute dynamically to add it only to visible elements, but it is a lot of code.

Another point that I see totally unnecessary is to hide / show inputs if they are going to have the same purpose: enter data . The type of operation to be carried out can be determined by means of the unit of measure selected in the radios. For example, if for the English unit, it is required to send the form to a different URL than for the metric, only look at what radio is selected and do the process according to it.

Note: StackOverflow blocks the submission of forms for security reasons. You can see the examples in the following below the codes.

    
answered by 30.01.2017 / 14:36
source