CoderChris CoderChris - 1 month ago 6
jQuery Question

JQuery Onsubmit URL Redirect based on Radio Box Value

I have been struggling for days to try and include some jquery to change the page URL, onsubmit, based on the value of a radio box (note the radio box values cannot change).

This is my HTML

<form id="myformid">
<input type="radio" name="selectid" value="1"><span>Google</span><br>
<input type="radio" name="selectid" value="2"><span>Yahoo</span><br>
<input type="radio" name="selectid" value="3"><span>Bing</span>


this is the jquery I WANT to use, but I know it is wrong...

$("#myformid").submit(function(){
if($("#selectid").val()==="1"){
$(this).attr("action","http://www.google.com");
} else {
if($("#selectid").val()==="2"){
$(this).attr("action","http://www.yahoo.com");
});


Any help would be appreciated.

Answer

Try this instead.

Notice that I'm getting the selected value by using "input:radio[name ='selectid']:checked". Using # in a selector as you have looks for ID, whereas your radios are defined by name.

This should look for all radio inputs of name selectid, find the checked one, and get its value. I've also cleaned up some minor issues regarding your curly brackets.

$("#myformid").submit(function(){

    var checkedVal = $("input:radio[name ='selectid']:checked").val();        

    if(checkedVal === "1"){
        $(this).attr("action","http://www.google.com");   
    } else if(checkedVal === "2"){
        $(this).attr("action","http://www.yahoo.com"); 
    }

});
Comments