0

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.

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>';
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.