Search code examples
javascriptjquerystringhref

JQuery convert string to link


I have 3 select fields, and the combined value of these I would like to use as a extra part of an url.

Here's the HTML code:

<select name="cos" id="cos" size="5">
  <option value="/squad">Squad</option>
  <option value="/class">Class</option>
 </select>
<select name="color" id="color" size="5">
  <option value="/purpleblack">PurpleBlack</option>
  <option value="/redblack">RedBlack</option>
  <option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
  <option value="/1984">1984</option>
  <option value="/1985">1985</option>
  <option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>

And the JavaScript:

$("select").change(function () { 
   var str = "";
    $("select option:selected").each(function () {
    var id = $(this).parent().attr('name');
       str += $(this).attr('value');             
       });
      $("div#output").text(str);
    })
    .trigger('change'); 

https://jsfiddle.net/eZKUU/264/

Right now it's working.. after I select an option in all 3 of the selectfields I get an output like /squad/redblack/1985. I would like to use this output in an url, so it would look like:

mysite.com/squad/redblack/1985

Is there an easy way of doing this? And also.. To only get the link visible after all three of the selectfields have an option selected?


Solution

  • You can check to see if the number of selected options is the same amount as the number of select elements.

    var selectedAllLength = $("select").length;
    $("select").change(function () {
       var str = location.origin;
        var selected = $("select option:selected");
        var selectedCount = selected.length;
        if(selectedCount == selectedAllLength) {
            selected.each(
                function () {
                    str += $(this).attr('value');             
                }
            );
            $("#output").html('<a href=' + str + '>The link is here</a>');
        }
    })
    .trigger('change');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <select name="cos" id="cos" size="5">
      <option value="/squad">Squad</option>
      <option value="/class">Class</option>
     </select>
    <select name="color" id="color" size="5">
      <option value="/purpleblack">PurpleBlack</option>
      <option value="/redblack">RedBlack</option>
      <option value="/aquablack">AquaBlack</option>
    </select>
    <select name="year" id="year" size="5">
      <option value="/1984">1984</option>
      <option value="/1985">1985</option>
      <option value="/1986">1986</option>
    </select>
    <br/><br/>
    <div id="output"></div>