CodeIn
CodeIn

Reputation: 31

div with innerhtml and variable

I need to put a link inside a div or together with a variable value coming from a function in javascript.

function getRadios(){
    		var radios = $("input[name='radio']:checked").val()
    		return radios;
		}
var resultado = getRadios();
var jogar = document.getElementsById('jogar');

jogar.innerHTML = '<a href="somepage.htm?varName='+ resultado +'">click</a>';
<input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar"></div>

I need the radio value to be inserted in the url I'm using ajax.

Upvotes: 0

Views: 223

Answers (2)

JakeParis
JakeParis

Reputation: 11210

You can do this pretty easily without jQuery. Just write a function that will get run each time the input is clicked.

const jogar = document.getElementById('jogar');

const radios = document.querySelectorAll('input[name="radio"]');

const setLink = function(val) {
  let link = "somepage.htm?varName=" + val;
  jogar.querySelector('a').setAttribute('href', link);
};

radios.forEach( r => r.addEventListener('change', e => {
  const resultado = e.target.value;
  setLink( resultado );
}));
<input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar">
  <a href="#">click</a>
</div>

And here the same thing, but a more compact way to do it:

const jogar = document.getElementById('jogar');
const radios = document.querySelectorAll('input[name="radio"]');
radios.forEach( r => r.addEventListener('change', e => {
  let link = "somepage.htm?varName=" + e.target.value;
  jogar.querySelector('a').setAttribute('href', link);
}));
<input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar">
  <a href="#">click</a>
</div>

Upvotes: 1

Mateusz Krawczyk
Mateusz Krawczyk

Reputation: 308

I think your problem is, that you run this code once on page load. You should run t every time radio is changed.

function getRadios(){
    var radios = document.querySelector("input[name='radio']:checked").value;
    return radios;
}
document.querySelectorAll("input[name='radio']").forEach(x => x.onchange = () => { 
    var resultado = getRadios();
    var jogar = document.getElementsById('jogar');
    jogar.innerHTML = '<a href="somepage.htm?varName='+ resultado +'">click</a>';
});

Upvotes: 0

Related Questions