Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery to change a form's target

I want to change the form's target based on the option which is selected.

<form id='post_form' target="targetvalue">

<select id="select" name="select">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>

    </form>


 <script>
 $("#select").change(function() {
    var targetvalue = $("#select option:selected").text();
    $("#post_form").attr("target", targetvalue);
    });

 </script>
like image 721
Martijn van den Broeck Avatar asked Nov 28 '11 11:11

Martijn van den Broeck


1 Answers

  1. If you want to set the target to either Option 1 or Option 2, what you have is correct. However, if you want to set the target to either option1 or option2, you should have:

    var targetvalue = $("#select option:selected").val();
    

    which can be simplified to just;

    var targetvalue = $(this).val();
    
  2. If you're using jQuery > 1.6, you should be using prop() instead of attr(). For more details see StackOverflow: .prop() vs .attr()

    $("#select").change(function() {
        var targetvalue = /* which ever you decide */;
        $("#post_form").prop("target", targetvalue);
    });
    
  3. You shouldn't really be linking to just the latest version in a production environment; if a new version of jQuery gets released with breaking changes, you're screwed. Link to a specific version of jQuery, and test thoroughly before you upgrade to a new release;

    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    
  4. If you're only defining the <script> after the <form> element to be able to target it, realise you can use a $(document).ready() block to define the script anywhere;

    <script>
        $(document).ready(function () {
            $('#select').change(function () {
                var targetvalue = /* which ever you decide */;
                $('#post_form').prop("target", targetvalue);
            });
        });
    </script>
    
like image 93
Matt Avatar answered Oct 12 '22 15:10

Matt