nitasot
nitasot

Reputation: 31

How to prevent users from submitting false value of datalist in html?

I am having a code for Datalist:

$('input[list]').on('input', function(e) {
  var $input = $(e.target),
    $options = $('#' + $input.attr('list') + ' option'),
    $hiddenInput = $('#' + $input.attr('id') + '-hidden'),
    label = $input.val();

  $hiddenInput.val(label);

  for (var i = 0; i < $options.length; i++) {
    var $option = $options.eq(i);

    if ($option.text() === label) {
      $hiddenInput.val($option.attr('data-value'));
      break;
    }
  }
});

// For debugging purposes
$("#myForm").on('submit', function(e) {
  $('#result').html($('#answer-hidden').val());
  e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<form id="myForm">
  <input list="answers" id="answer">
  <datalist id="answers">
        <option data-value="42">The answer</option>
        <option data-value="1337">Elite</option>
        <option data-value="69">Dirty</option>
        <option data-value="3">Pi</option>
    </datalist>
  <input type="hidden" name="answer" id="answer-hidden">
  <input type="submit">
</form>




<p>Submitted value (for debugging):</p>
<pre id="result"></pre>

I search for Elite as El and select the option Elite and press submit button, the result is 1337. GOOD

But, when I search for Elite as El and press submit button (without selecting option Elite or any other...), the result is El. BAD.

How to prevent users from submitting false value?

Upvotes: 3

Views: 1146

Answers (2)

Quentin
Quentin

Reputation: 943585

The point of providing a datalist to an input is to provide a recommended set of options to pick from. Allowing a custom option is a design goal.

If that isn't what you want then use a select element instead of a text input.

Upvotes: -1

ViqMontana
ViqMontana

Reputation: 5688

As @ecg8 mentioned, you should have an event listener on your dropdown and only enable the submit button if a valid value is selected. This will work for you:

var validValues = [42, 1337, 69, 3];
$("#answer").on("change", function() {
    var validValueSelected = validValues.some(x => x == $('#answer-hidden').val());
    document.getElementById("submitButton").disabled = !validValueSelected;
});

And change your submit button to:

<input id="submitButton" disabled type="submit">

Although, I wouldn't recommend hard coding your data values into the html, then duplicating them in the javascript file (i.e. the variable validValues). I'd recommend using a library such as KnockOut which can help you.

Upvotes: 2

Related Questions