Prithviraj Mitra Prithviraj Mitra - 1 month ago 5
HTML Question

Set previously selected value in dropdown if return false

I have 2 dropdowns. One is minimum size and another one is maximum size. I am checking if selected value from minimum select box is greater than the selected value of maximum select box and vice versa. It works well.

I am stuck at one place where I want to set the previous value as 'selected' if the validation returns false. It doesn't let me to do that.

The demo is here -- https://jsfiddle.net/squidraj/2fnxw609/1/

JS code

$("select[name=size-min],select[name=size-max]").focus(function() {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {

var selname = $(this).attr('name');
var selval = $(this).val();
var e1 = document.getElementById("size-min");
var minval = e1.options[e1.selectedIndex].value;
var e2 = document.getElementById("size-max");
var maxval = e2.options[e2.selectedIndex].value;

alert(previous);

if (selname == "size-min" && parseInt(minval) > parseInt(maxval) && maxval != "") {
$('#size-min').val(previous);
alert("The minimum size needs to be smaller than maximum size.");
return false;
}
if (selname == "size-max" && parseInt(selval) < parseInt(minval)) {
$('#size-max').val(previous);
alert("The maximum size needs to be greater than minimum size.");
return false;
}

});


Is it at all possible what I am trying to achieve. Any help or suggestion is highly appreciated.

Answer

Not really an answer: but demonstrating that your logic is sound (and perhaps taking more advantage of jQuery features)

function init() {
  var previous;
 $(".minmax").focus(function() {
   // Store the current value on focus, before it changes
   previous = this.value;
 }).change(function(e) {
   if (parseInt($("#size-max").val()) < parseInt($("#size-min").val())) {
     $(this).val(previous);
     console.log($(this).attr('id')=="size-min"?"The minimum size needs to be smaller than maximum size.":"The maximum size needs to be greater than minimum size.");
   }
 });
}
$(init);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form>
<select class="minmax" id="size-min">
  <option selected>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>
<select class="minmax" id="size-max">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option selected>5</option>
</select>
</form>
</body>

Comments