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>
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();
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);
});
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>
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>