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
targetto eitherOption 1orOption 2, what you have is correct. However, if you want to set the target to eitheroption1oroption2, you should have:which can be simplified to just;
If you’re using jQuery > 1.6, you should be using
prop()instead ofattr(). For more details see StackOverflow: .prop() vs .attr()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;
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;