简体   繁体   中英

Dynamic href generation on link click based on radio button state : PHP interaction with javascript

I am using MVC framework in codeigniter and I have a view where I have this link (please note that href value is generated by call to a PHP function which in turn takes 'auth/mylogin' as a parameter:

<a href = "<?php echo $this->FrontController->myLoginURL(site_url() . 'auth/mylogin'); ?>"> CLICK ME</a>

Now I have a radio button on the same view page.

<input id="ut1" name="usertype" type="radio" value="ut1"<?php echo set_radio('usertype', 'ut1', TRUE); ?> />
<label for="ut1" onclick="">User Type 1</label>

<input id="ut2" name="usertype" type="radio" value="ut2"<?php echo set_radio('usertype', 'ut2'); ?> />  
<label for="ut2" onclick="">User Type 2</label>

Now what I want is this: I want to pass the user type value in addition. What I mean is that depending on which radio button the user has chosen before he clicks the link, I want the code to be:

User Type 1 radio selected before clicking CLICK ME

<a href = "<?php echo $this->FrontController->myLoginURL(site_url() . 'auth/mylogin/ut1'); ?>"> CLICK ME</a>

User Type 2 radio selected before clicking CLICK ME

<a href = "<?php echo $this->FrontController->myLoginURL(site_url() . 'auth/mylogin/ut2'); ?>"> CLICK ME</a>

Since there is not submit, I assume I have to use javascript to do this.
But since javascript is client side and PHP serverside, I am not sure how to get this done.

How do I achieve this?
Please note that the code has been stripped to show only the relevant part.

    <label for="ut2" onclick="messi_fan('ut2');">User Type 2</label>
    <label for="ut1" onclick="messi_fan('ut1');">User Type 1</label>
<a id = "link" href = "<?php echo $this->FrontController->myLoginURL(site_url() . 'auth/mylogin'); ?>"> CLICK ME</a>
<script>

function messi_fan(type){
url = " <?php echo $this->FrontController->myLoginURL(site_url() . 'auth/mylogin/'; ?>";
new_url = url+type;
$("#link").attr('href',new_url);
}
</script>

You can use jQuery like this:

    $('#container_id input[type=radio]').each(function(){
    rad=$(this);
    rad.click(function(e){
    #get new url from PHP
$.get ("file_that_returns your_url.php?user_type="+rad.val(), function(data) {
$("#yourlinkid_here").attr("href", data);
});
    # $("#yourlinkid_here").attr("href", $("#yourlinkid_here").attr("href")+rad.val());
    });

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM