Danny M.
Danny M.

Reputation: 150

JS function not defined, passing variable

I'm trying to pass a variable in the URL to check a radio button on another page based on whatever link is clicked. Unfortunately, I'm getting an "Uncaught ReferenceError: radio_onload is not defined" error.

Does this have anything to do w/ a document.onload? I've tried different variations and I'm unable to select my radio on the adjacent page. If I can get another set of eyes to help me see what I'm missing, that'd be great.

1.html JS

var locate = window.location.toString();
var text = locate;

function delineate2(str){
point = str.lastIndexOf("=");
return(str.substring(point+1,str.length));
}

var passOpt = delineate2(text);

function radio(){
document.getElementById(passOpt).checked="checked";
}

1.html user options

<!-- if clicked, select test 1 radio on 2.html-->
<a href="2.html?formOpt=test1">test 1</a>
<!-- if clicked, select test 2 radio on 2.html-->
<a href="2.html?formOpt=test2">test 2</a>

2.html, radio form

<form>
  <input type="radio" name="test" value="test1"/>Test #1
  <input type="radio" name="test" value="test2"/>Test #2
</form>

calling my function on 2.html

radio();

If there's another approach you think I can take, feel free to let me know. I'm still learning JS so any help is appreciated.

Upvotes: 1

Views: 155

Answers (1)

jonny
jonny

Reputation: 3098

I got it to work fine in this example. You need to add IDs to your HTML elements in 2.html:

<form>
  <input id="test1" type="radio" name="test" value="test1" />Test #1
  <input id="test2" type="radio" name="test" value="test2"/>Test #2
</form>

I used a sample string as the input for your delineate function (as you cant use URL queries in JSFiddle), and changed up your radio function a little too:

var locate = "2.html?formOpt=test2"

function delineate2(str){
    point = str.lastIndexOf("=");
    return(str.substring(point+1,str.length));
}

var passOpt = delineate2(locate);

//this was used for debugging
document.getElementById("result").innerHTML = passOpt;

function radio(){    
    document.getElementById(passOpt).setAttribute("checked", true);
}

radio();

See the fiddle here

Hope this helps.

Upvotes: 1

Related Questions