How to select change <a> according to <select> with PHP

Asked

Viewed 36 times

-1

Guys I’m trying to change the tag link , which is within one when the user chooses one of the options of . I’m trying to make this change with PHP. But I’ve done several ways and it didn’t work. Can someone suggest me some solution?

    <!doctype html>
    <html lang="pt-br">

    <head>
        <title>Title</title>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    </head>

    <body>
        <div class="form-group">

            <label for="metrica">Escolha a Métrica Desejada:</label>
            <select class="form-control" name="metrica" id="metrica">
                <option name="host" value="1">Host</option>
                <option name="DG" value="2">Distância Geográfica</option>
                <option name="custo"value="3">Custo</option>


            </select>
            <small class="form-text text-muted">Selecione a métrica do cálculo</small>

            <button type="button" class="btn btn-outline-primary">
            <?php
            //$mt = isset($_GET['metrica']) ? $_GET['metrica']:0;
            $ht = isset($_GET['host']) ? $_GET['host']:0;
            $dg = isset($_GET['DG'])? $_GET['DG']:0;
            $ct = isset($_GET['custo'])? $_GET['custo']:0;
            if($ht):?>
            <a href='principal.html'>Escolher cidades</a>;
            <?php
            elseif($dg):
            ?>
            <a href='principal.1.html'>Escolher cidades</a>;
            <?php
            elseif($ct):
            ?>
            <a href='principal.2.html'>Escolher cidades</a>
            <?php
            endif;
            ?>  
            </button>

            <div id="myDiv"></div>
        </div>


        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
            integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
        </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
            integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
        </script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
            integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
        </script>
    </body>

    </html>
  • Could you give an example? When to select Host the href must be principal.html and so on? No need to change the text? $off: Why put the a within the button? It doesn’t seem ideal...

  • 1

    @Lipespry that’s right.when it’s "host" the href of being main.html, if it’s "Demographic distance" it will go main.1.html and if it chooses "cost", it will go to main.2.html.

  • @Lipespry on the <a> tag is a habit of mine to do so! Maybe a bad habit.

  • 1

    Every nut with his craze (Gambi)! Since the button will not perform any action, the ideal is not to use it. If you want your link to look like a button, make it look like a button!

  • 2

    Your code is wrong. Besides it being wrong to use <a> inside <button>, you should take the value of select in GET, not the option. You must take the value of name="metrica", which will be the value of the selected option.

  • But I do not understand why my if is giving error. I removed the button or no text appears.

  • @Sam made the change you mentioned, now the text appears, but href keeps the same,'main.html', for everyone.

Show 2 more comments

2 answers

1

You can do this with Jquery, when you select something in the metric field, change the link address. You just need to put an ID on it. Follow an example:

$(document).ready(function(){
  $("#metrica").change(function () {
    switch (this.value) {
    case "1":
         $("#link").attr("href", "principal.html");
        break;
    case "2":
         $("#link").attr("href", "principal1.html");
		 break;
	case "3":
         $("#link").attr("href", "principal2.html");
		 break;	 
	} 
  });
});
<!doctype html>
    <html lang="pt-br">

    <head>
        <title>Title</title>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
            integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    </head>

    <body>
        <div class="form-group">

            <label for="metrica">Escolha a Métrica Desejada:</label>
            <select class="form-control" name="metrica" id="metrica">
                <option value="">Selecione...</option>
                <option name="host" value="1">Host</option>
                <option name="DG" value="2">Distância Geográfica</option>
                <option name="custo"value="3">Custo</option>


            </select>
            <small class="form-text text-muted">Selecione a métrica do cálculo</small>

            <button type="button" class="btn btn-outline-primary">
            <a id="link" href="">Escolher cidades</a>;
            </button>
            <div id="myDiv"></div>
        </div>


        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
            integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
        </script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
            integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
        </script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
            integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
        </script>
<script type="text/javascript">
	$(document).ready(function(){
	  $("#metrica").change(function () {
		switch (this.value) {
		case "1":
			 $("#link").attr("href", "principal.html");
			break;
		case "2":
			 $("#link").attr("href", "principal1.html");
			 break;
		case "3":
			 $("#link").attr("href", "principal2.html");
			 break;	 
		} 
	  });
	});
	</script>
    </body>

    </html>

  • I appreciate it. But I tried it like this, it didn’t work. I put it in the head, after the footer and even in separate files and nothing.

  • I edited the answer. Adding the script before closing the body tag it works

1


First of all, it should be understood that PHP runs on the server. So, every time the user changes the select, you would have to submit a form with action for the same page, capture the value of select and then render your link a with the href desired.

It turns out that this is too far back to do something simple. Note: you have three options in your select. And all the values are static. It’s illogical that you go all the way around. Just do it with Javascript:

document.getElementById('metrica').addEventListener(
    'change',
    function(){
        document.getElementById('link-cidade').setAttribute('href', this.value);
    },
    false
);
<!DOCTYPE html>
<html lang="pt-br">

<head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>
    <div class="form-group">

        <label for="metrica">Escolha a Métrica Desejada:</label>
        <select class="form-control" name="metrica" id="metrica">
            <option name="host" value="principal.html">Host</option>
            <option name="DG" value="principal.1.html">Distância Geográfica</option>
            <option name="custo"value="principal.2.html">Custo</option>


        </select>
        <small class="form-text text-muted">Selecione a métrica do cálculo</small>

        <!--<button type="button" class="btn btn-outline-primary">-->
            <a id="link-cidade" href="principal.html">Escolher cidades</a>
        <!--</button>-->

        <div id="myDiv"></div>
    </div>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
    </script>
    <script>
    // código no snippet
    </script>
</body>

</html>

1) I added a id="link-a" to your link a;

2) I added a eventListener in his select who already has ID metrica that captures the event change and defines the attribute href of your link;

3) I have added the links to value of option. Using the numbers would delegate another unnecessary turn: create a condition (switch) returning right link to certain number.

PS: commented the tags button. If you feel better using it, just uncork it.

  • 1

    Thank you so much guy! I’ve never seen it this way, for this javascript way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.