Harpreet Singh
Harpreet Singh

Reputation: 979

Submit my form with new value when I change select form value

I am working on a form where the select value is changing based on a click

When I click on h3, my select option value is changing but it's submitting the form with previous select option value. I want my new value to submit.

jQuery(".monthsele").click(function() {
  var monthval = jQuery(this).find("span").attr('umval');
  jQuery("#formselect #mons option:selected").remove();

  jQuery("#formselect #mons option[value=" + monthval + "]").attr('selected', 'selected');

  setTimeout(function() {
    jQuery('form#formselect').submit();
  }, 1000);


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form name="formselect" id="formselect" method="post" action="">

  <select id="mons" name="mons">
    				
    		<option value="1" selected>1</option>
    		<option value="2">2</option>
    		<option value="3">3</option>
    														
    	</select>

  <button type="submit" name="formselect_form" id="formselect_form" class="btn btn-default">submit</button>
</form>

<h3 class="col-sm-4 monthsele"><span umval="2" class="pull-left">2</span></h3>

Upvotes: 0

Views: 51

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26298

Instead of:

jQuery("#formselect #mons option[value="+monthval+"]").attr('selected', 'selected');

try

jQuery("#formselect #mons").val(monthval).change();

Check this example:

jQuery(".monthsele").click(function() {
  var monthval = jQuery(this).find("span").attr('umval');
  jQuery("#formselect #mons").val(monthval).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="formselect" id="formselect" method="post" action="">

  <select id="mons" name="mons">
    				
    		<option value="1" selected>1</option>
    		<option value="2">2</option>
    		<option value="3">3</option>
    														
    	</select>

  <button type="submit" name="formselect_form" id="formselect_form" class="btn btn-default">submit</button>
</form>

<h3 class="col-sm-4 monthsele"><span umval="2" class="pull-left">2</span></h3>

Upvotes: 1

Related Questions